diff --git a/.travis.yml b/.travis.yml index c891e1569a..41229df646 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,20 @@ env: # Give Maven 1GB of memory to work with - MAVEN_OPTS=-Xmx1024M +jdk: + # DS-3384 Oracle JDK 8 has DocLint enabled by default. + # Let's use this to catch any newly introduced DocLint issues. + - oraclejdk8 + - oraclejdk7 + +## Should we run into any problems with oraclejdk8 on Travis, we may try the following workaround. +## https://docs.travis-ci.com/user/languages/java#Testing-Against-Multiple-JDKs +## https://github.com/travis-ci/travis-ci/issues/3259#issuecomment-130860338 +#addons: +# apt: +# packages: +# - oracle-java8-installer + # Install prerequisites for building Mirage2 more rapidly before_install: # Install Node.js 6.5.0 & print version info diff --git a/dspace-api/pom.xml b/dspace-api/pom.xml index 61f90291a0..ea3692cf71 100644 --- a/dspace-api/pom.xml +++ b/dspace-api/pom.xml @@ -12,7 +12,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-api/src/main/java/org/apache/solr/handler/extraction/ExtractingParams.java b/dspace-api/src/main/java/org/apache/solr/handler/extraction/ExtractingParams.java index 68319795a6..014d4e0d6b 100644 --- a/dspace-api/src/main/java/org/apache/solr/handler/extraction/ExtractingParams.java +++ b/dspace-api/src/main/java/org/apache/solr/handler/extraction/ExtractingParams.java @@ -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}. *

* See Tika's docs for what the extracted document looks like. - *

+ * * @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. *

- * 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. *

diff --git a/dspace-api/src/main/java/org/dspace/administer/CommunityFiliator.java b/dspace-api/src/main/java/org/dspace/administer/CommunityFiliator.java index 9765753ec2..70b525347b 100644 --- a/dspace-api/src/main/java/org/dspace/administer/CommunityFiliator.java +++ b/dspace-api/src/main/java/org/dspace/administer/CommunityFiliator.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/administer/CreateAdministrator.java b/dspace-api/src/main/java/org/dspace/administer/CreateAdministrator.java index fd40243b50..c1c80e5f52 100644 --- a/dspace-api/src/main/java/org/dspace/administer/CreateAdministrator.java +++ b/dspace-api/src/main/java/org/dspace/administer/CreateAdministrator.java @@ -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"); } } diff --git a/dspace-api/src/main/java/org/dspace/administer/MetadataImporter.java b/dspace-api/src/main/java/org/dspace/administer/MetadataImporter.java index 1e1882d7ae..49e6661a55 100644 --- a/dspace-api/src/main/java/org/dspace/administer/MetadataImporter.java +++ b/dspace-api/src/main/java/org/dspace/administer/MetadataImporter.java @@ -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 : specify which xml source file " + - "contains the DC fields to import.\n"; + " -f : specify which xml source file " + + "contains the DC fields to import.\n"; System.out.println(usage); } } diff --git a/dspace-api/src/main/java/org/dspace/administer/RegistryLoader.java b/dspace-api/src/main/java/org/dspace/administer/RegistryLoader.java index 092a61e145..4ec485fb43 100644 --- a/dspace-api/src/main/java/org/dspace/administer/RegistryLoader.java +++ b/dspace-api/src/main/java/org/dspace/administer/RegistryLoader.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/administer/StructBuilder.java b/dspace-api/src/main/java/org/dspace/administer/StructBuilder.java index e90d4ae962..c1f8f928fd 100644 --- a/dspace-api/src/main/java/org/dspace/administer/StructBuilder.java +++ b/dspace-api/src/main/java/org/dspace/administer/StructBuilder.java @@ -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()]; diff --git a/dspace-api/src/main/java/org/dspace/app/checker/ChecksumChecker.java b/dspace-api/src/main/java/org/dspace/app/checker/ChecksumChecker.java index df8b1eddbf..00ec210ad9 100644 --- a/dspace-api/src/main/java/org/dspace/app/checker/ChecksumChecker.java +++ b/dspace-api/src/main/java/org/dspace/app/checker/ChecksumChecker.java @@ -53,25 +53,25 @@ public final class ChecksumChecker /** * Command line access to the checksum package. * - * @param args - *

- *
-h
- *
Print help on command line options
- *
-l
- *
loop through bitstreams once
- *
-L
- *
loop continuously through bitstreams
- *
-d
- *
specify duration of process run
- *
-b
- *
specify bitstream IDs
- *
-a [handle_id]
- *
check anything by handle
- *
-e
- *
Report only errors in the logs
- *
-p
- *
Don't prune results before running checker
- *
+ *
+ *
-h
+ *
Print help on command line options
+ *
-l
+ *
loop through bitstreams once
+ *
-L
+ *
loop continuously through bitstreams
+ *
-d
+ *
specify duration of process run
+ *
-b
+ *
specify bitstream IDs
+ *
-a [handle_id]
+ *
check anything by handle
+ *
-e
+ *
Report only errors in the logs
+ *
-p
+ *
Don't prune results before running checker
+ *
+ * @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); diff --git a/dspace-api/src/main/java/org/dspace/app/harvest/Harvest.java b/dspace-api/src/main/java/org/dspace/app/harvest/Harvest.java index 3e74bc12e7..ad74ea58bc 100644 --- a/dspace-api/src/main/java/org/dspace/app/harvest/Harvest.java +++ b/dspace-api/src/main/java/org/dspace/app/harvest/Harvest.java @@ -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 harvestedCollections = harvestedCollectionService.findAll(context); - for (HarvestedCollection harvestedCollection : harvestedCollections) - { + + List 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 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 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(); - } + } } /** diff --git a/dspace-api/src/main/java/org/dspace/app/itemupdate/BitstreamFilterByFilename.java b/dspace-api/src/main/java/org/dspace/app/itemupdate/BitstreamFilterByFilename.java index 292db98897..4613540252 100644 --- a/dspace-api/src/main/java/org/dspace/app/itemupdate/BitstreamFilterByFilename.java +++ b/dspace-api/src/main/java/org/dspace/app/itemupdate/BitstreamFilterByFilename.java @@ -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(); + } } diff --git a/dspace-api/src/main/java/org/dspace/app/itemupdate/ItemUpdate.java b/dspace-api/src/main/java/org/dspace/app/itemupdate/ItemUpdate.java index 9963e20256..06dc02a2e2 100644 --- a/dspace-api/src/main/java/org/dspace/app/itemupdate/ItemUpdate.java +++ b/dspace-api/src/main/java/org/dspace/app/itemupdate/ItemUpdate.java @@ -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 filterAliases = new HashMap(); - - public static boolean verbose = false; + public static String HANDLE_PREFIX = null; + public static final Map filterAliases = new HashMap(); + + 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 diff --git a/dspace-api/src/main/java/org/dspace/app/launcher/CommandRunner.java b/dspace-api/src/main/java/org/dspace/app/launcher/CommandRunner.java index 5d7a05ead5..33b21e5c61 100644 --- a/dspace-api/src/main/java/org/dspace/app/launcher/CommandRunner.java +++ b/dspace-api/src/main/java/org/dspace/app/launcher/CommandRunner.java @@ -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 */ diff --git a/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java b/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java index ede7ac4622..eeec55d1c5 100644 --- a/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java +++ b/dspace-api/src/main/java/org/dspace/app/launcher/ScriptLauncher.java @@ -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) { diff --git a/dspace-api/src/main/java/org/dspace/app/mediafilter/MediaFilter.java b/dspace-api/src/main/java/org/dspace/app/mediafilter/MediaFilter.java index 8e60a68155..f8ecf67e21 100644 --- a/dspace-api/src/main/java/org/dspace/app/mediafilter/MediaFilter.java +++ b/dspace-api/src/main/java/org/dspace/app/mediafilter/MediaFilter.java @@ -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) diff --git a/dspace-api/src/main/java/org/dspace/app/requestitem/service/RequestItemService.java b/dspace-api/src/main/java/org/dspace/app/requestitem/service/RequestItemService.java index b3ac1b5004..92876c5dba 100644 --- a/dspace-api/src/main/java/org/dspace/app/requestitem/service/RequestItemService.java +++ b/dspace-api/src/main/java/org/dspace/app/requestitem/service/RequestItemService.java @@ -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); diff --git a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java index c48958ca9f..ec60e87901 100644 --- a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java +++ b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java @@ -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); } diff --git a/dspace-api/src/main/java/org/dspace/app/statistics/ReportGenerator.java b/dspace-api/src/main/java/org/dspace/app/statistics/ReportGenerator.java index c39ae388c2..b8a8143af0 100644 --- a/dspace-api/src/main/java/org/dspace/app/statistics/ReportGenerator.java +++ b/dspace-api/src/main/java/org/dspace/app/statistics/ReportGenerator.java @@ -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 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 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 diff --git a/dspace-api/src/main/java/org/dspace/app/util/CollectionDropDown.java b/dspace-api/src/main/java/org/dspace/app/util/CollectionDropDown.java index 06f4ce5276..8a32986ca8 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/CollectionDropDown.java +++ b/dspace-api/src/main/java/org/dspace/app/util/CollectionDropDown.java @@ -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 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 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 - { - 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 + { + 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()); + } + } } diff --git a/dspace-api/src/main/java/org/dspace/app/util/Configuration.java b/dspace-api/src/main/java/org/dspace/app/util/Configuration.java index b5d945479f..249c38b00e 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/Configuration.java +++ b/dspace-api/src/main/java/org/dspace/app/util/Configuration.java @@ -36,8 +36,7 @@ public class Configuration * * 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) { diff --git a/dspace-api/src/main/java/org/dspace/app/util/DCInput.java b/dspace-api/src/main/java/org/dspace/app/util/DCInput.java index f3281d284b..f094c67805 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/DCInput.java +++ b/dspace-api/src/main/java/org/dspace/app/util/DCInput.java @@ -94,8 +94,10 @@ public class DCInput * a HashMap * * @param fieldMap - * ??? + * named field values. + * * @param listMap + * value-pairs map, computed from the forms definition XML file */ public DCInput(Map fieldMap, Map> listMap) { diff --git a/dspace-api/src/main/java/org/dspace/app/util/DCInputSet.java b/dspace-api/src/main/java/org/dspace/app/util/DCInputSet.java index 752fcb1cfe..0a888b7ad4 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/DCInputSet.java +++ b/dspace-api/src/main/java/org/dspace/app/util/DCInputSet.java @@ -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>> pages, Map> listMap) - { - this.formName = formName; - inputPages = new DCInput[pages.size()][]; - for ( int i = 0; i < inputPages.length; i++ ) - { - List> 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>> pages, Map> listMap) + { + this.formName = formName; + inputPages = new DCInput[pages.size()][]; + for ( int i = 0; i < inputPages.length; i++ ) + { + List> 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 filteredInputs = new ArrayList(); - 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 filteredInputs = new ArrayList(); + 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,36 +111,36 @@ 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") ); } /** * Does the current input set define the named field? * Scan through every field in every page of the input set * - * @param fieldName + * @param fieldName selects the field. * @return true if the current set has the named field */ 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; } } diff --git a/dspace-api/src/main/java/org/dspace/app/util/DCInputsReader.java b/dspace-api/src/main/java/org/dspace/app/util/DCInputsReader.java index a9135f43d4..d2219e0ec0 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/DCInputsReader.java +++ b/dspace-api/src/main/java/org/dspace/app/util/DCInputsReader.java @@ -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>> 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>> pages = new ArrayList>>(); // 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> page = new ArrayList>(); - 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 field = new HashMap(); - 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>> pages = new ArrayList>>(); // 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> page = new ArrayList>(); + 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 field = new HashMap(); + 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 pairs = new ArrayList(); + 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 pairs = new ArrayList(); - 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 ki = formDefns.keySet().iterator(); while (ki.hasNext()) { - String idName = ki.next(); - List>> pages = formDefns.get(idName); - for (int i = 0; i < pages.size(); i++) + String idName = ki.next(); + List>> pages = formDefns.get(idName); + for (int i = 0; i < pages.size(); i++) + { + List> page = pages.get(i); + for (int j = 0; j < page.size(); j++) { - List> page = pages.get(i); - for (int j = 0; j < page.size(); j++) - { - Map fld = page.get(j); - // verify reference in certain input types - String type = fld.get("input-type"); + Map 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 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 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; diff --git a/dspace-api/src/main/java/org/dspace/app/util/DSpaceContextListener.java b/dspace-api/src/main/java/org/dspace/app/util/DSpaceContextListener.java index d0fcf1c5c4..03d70bbea6 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/DSpaceContextListener.java +++ b/dspace-api/src/main/java/org/dspace/app/util/DSpaceContextListener.java @@ -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) diff --git a/dspace-api/src/main/java/org/dspace/app/util/GoogleMetadata.java b/dspace-api/src/main/java/org/dspace/app/util/GoogleMetadata.java index d9995251e1..43e4681b5e 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/GoogleMetadata.java +++ b/dspace-api/src/main/java/org/dspace/app/util/GoogleMetadata.java @@ -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 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 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> 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 - *
    - *
  • the item's only bitstream (in the ORIGINAL bundle); or
  • - *
  • the primary bitstream
  • - *
- * 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 contentBundles = itemService.getBundles(item, "ORIGINAL"); - for (Bundle bundle : contentBundles) { + /** + * A bitstream is considered linkable fulltext when it is either + *
    + *
  • the item's only bitstream (in the ORIGINAL bundle); or
  • + *
  • the primary bitstream
  • + *
+ * 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 contentBundles = itemService.getBundles(item, "ORIGINAL"); + for (Bundle bundle : contentBundles) { List 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]); } } diff --git a/dspace-api/src/main/java/org/dspace/app/util/OpenSearchServiceImpl.java b/dspace-api/src/main/java/org/dspace/app/util/OpenSearchServiceImpl.java index 7dc0695e26..a566fdeb41 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/OpenSearchServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/app/util/OpenSearchServiceImpl.java @@ -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(); - if (enabled) - { - String[] fmts = config.getArrayProperty("websvc.opensearch.formats"); + // read rest of config info if enabled + formats = new ArrayList(); + if (enabled) + { + String[] fmts = config.getArrayProperty("websvc.opensearch.formats"); formats = Arrays.asList(fmts); - } + } } @Override public List 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 results, - Map labels) throws IOException + DSpaceObject scope, List results, + Map 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 results, Map labels) + DSpaceObject scope, List results, Map 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); } } diff --git a/dspace-api/src/main/java/org/dspace/app/util/SubmissionStepConfig.java b/dspace-api/src/main/java/org/dspace/app/util/SubmissionStepConfig.java index cb7f97a862..8edf7cf3ad 100644 --- a/dspace-api/src/main/java/org/dspace/app/util/SubmissionStepConfig.java +++ b/dspace-api/src/main/java/org/dspace/app/util/SubmissionStepConfig.java @@ -39,7 +39,7 @@ public class SubmissionStepConfig implements Serializable /** * the id for this step ('id' only exists if this step is defined in the - * section) + * <step-definitions> section) */ private String id = null; diff --git a/dspace-api/src/main/java/org/dspace/authenticate/IPMatcher.java b/dspace-api/src/main/java/org/dspace/authenticate/IPMatcher.java index 854eb39798..b58a2b748d 100644 --- a/dspace-api/src/main/java/org/dspace/authenticate/IPMatcher.java +++ b/dspace-api/src/main/java/org/dspace/authenticate/IPMatcher.java @@ -13,13 +13,15 @@ import java.net.Inet6Address; import java.net.UnknownHostException; /** + *

* 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. + *

*

* Supported range specifications are: - *

+ *

*
    *
  • Full IPv4 address, e.g. {@code 12.34.56.78}
  • *
  • Full IPv6 address, e.g. {@code 2001:18e8:3:171:218:8bff:fe2a:56a4}
  • @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/authority/AuthorityValue.java b/dspace-api/src/main/java/org/dspace/authority/AuthorityValue.java index c164392c35..883c0edf1d 100644 --- a/dspace-api/src/main/java/org/dspace/authority/AuthorityValue.java +++ b/dspace-api/src/main/java/org/dspace/authority/AuthorityValue.java @@ -242,8 +242,9 @@ public class AuthorityValue { } /** - * Provides a string that will allow this AuthorityType to be recognized and provides information to create a new instance to be created using public AuthorityValue newInstance(String info). - * See the implementation of {@link com.atmire.org.dspace.authority.AuthorityValueGenerator#generateRaw(java.lang.String, java.lang.String) AuthorityValueGenerator#generateRaw(java.lang.String, java.lang.String)} for more details. + * Provides a string that will allow this AuthorityType to be recognized and + * provides information to create a new instance to be created using {@link #newInstance(String)}. + * See the implementation of {@link org.dspace.authority.AuthorityValueServiceImpl#generateRaw(java.lang.String, java.lang.String, java.lang.String)} for more details. * @return see {@link org.dspace.authority.service.AuthorityValueService#GENERATE AuthorityValueService.GENERATE} */ public String generateString() { diff --git a/dspace-api/src/main/java/org/dspace/authorize/AuthorizeException.java b/dspace-api/src/main/java/org/dspace/authorize/AuthorizeException.java index 6aec1199df..66e439688c 100644 --- a/dspace-api/src/main/java/org/dspace/authorize/AuthorizeException.java +++ b/dspace-api/src/main/java/org/dspace/authorize/AuthorizeException.java @@ -37,6 +37,7 @@ public class AuthorizeException extends Exception * create an exception with only a message * * @param message + * Exception message */ public AuthorizeException(String message) { diff --git a/dspace-api/src/main/java/org/dspace/authorize/AuthorizeServiceImpl.java b/dspace-api/src/main/java/org/dspace/authorize/AuthorizeServiceImpl.java index 634a1d68eb..18442bb113 100644 --- a/dspace-api/src/main/java/org/dspace/authorize/AuthorizeServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/authorize/AuthorizeServiceImpl.java @@ -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 rps = getPoliciesActionFilter(context, dso, fromAction); + List 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 policies, DSpaceObject dest) @@ -624,7 +624,7 @@ public class AuthorizeServiceImpl implements AuthorizeService List groups = new ArrayList(); 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."); } diff --git a/dspace-api/src/main/java/org/dspace/authorize/FixDefaultPolicies.java b/dspace-api/src/main/java/org/dspace/authorize/FixDefaultPolicies.java index ac6f2a251b..9323423435 100644 --- a/dspace-api/src/main/java/org/dspace/authorize/FixDefaultPolicies.java +++ b/dspace-api/src/main/java/org/dspace/authorize/FixDefaultPolicies.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/authorize/PolicySet.java b/dspace-api/src/main/java/org/dspace/authorize/PolicySet.java index 1a1459f1f2..32c12dd474 100644 --- a/dspace-api/src/main/java/org/dspace/authorize/PolicySet.java +++ b/dspace-api/src/main/java/org/dspace/authorize/PolicySet.java @@ -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 true, 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); diff --git a/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java b/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java index 4adb2118ac..05648f07e6 100644 --- a/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java +++ b/dspace-api/src/main/java/org/dspace/authorize/ResourcePolicy.java @@ -96,6 +96,7 @@ public class ResourcePolicy implements ReloadableEntity { * 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 { { 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 { /** * set the action this policy authorizes * - * @param myid action ID from org.dspace.core.Constants + * @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 { 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; } } diff --git a/dspace-api/src/main/java/org/dspace/authorize/service/AuthorizeService.java b/dspace-api/src/main/java/org/dspace/authorize/service/AuthorizeService.java index 6e4be3acb7..21eaf32997 100644 --- a/dspace-api/src/main/java/org/dspace/authorize/service/AuthorizeService.java +++ b/dspace-api/src/main/java/org/dspace/authorize/service/AuthorizeService.java @@ -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 - * org.dspace.core.Constants + * org.dspace.core.Constants * @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 org.dspace.core.Constants - * @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 org.dspace.core.Constants - * @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 org.dspace.core.Constants - * @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 { * org.dspace.core.Constants * @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; } diff --git a/dspace-api/src/main/java/org/dspace/browse/BrowseDAO.java b/dspace-api/src/main/java/org/dspace/browse/BrowseDAO.java index 55051ca47a..c9eabc130a 100644 --- a/dspace-api/src/main/java/org/dspace/browse/BrowseDAO.java +++ b/dspace-api/src/main/java/org/dspace/browse/BrowseDAO.java @@ -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); diff --git a/dspace-api/src/main/java/org/dspace/browse/BrowseInfo.java b/dspace-api/src/main/java/org/dspace/browse/BrowseInfo.java index 4d5f32948c..42b1b5d725 100644 --- a/dspace-api/src/main/java/org/dspace/browse/BrowseInfo.java +++ b/dspace-api/src/main/java/org/dspace/browse/BrowseInfo.java @@ -79,25 +79,25 @@ public class BrowseInfo private Collection collection; /** Community we are constrained to */ - private Community community; + private Community community; - /** offset of the item at the top of the next page */ - private int nextOffset = -1; + /** offset of the item at the top of the next page */ + private int nextOffset = -1; - /** offset of the item at the top of the previous page */ - private int prevOffset = -1; + /** offset of the item at the top of the previous page */ + private int prevOffset = -1; - /** the value upon which we are focusing */ - private String focus; + /** the value upon which we are focusing */ + private String focus; - /** number of results to display per page */ - private int resultsPerPage = -1; + /** number of results to display per page */ + private int resultsPerPage = -1; - /** database id of the item upon which we are focusing */ - private int focusItem = -1; + /** database id of the item upon which we are focusing */ + private int focusItem = -1; - /** number of metadata elements to display before truncating using "et al" */ - private int etAl = -1; + /** number of metadata elements to display before truncating using "et al" */ + private int etAl = -1; protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); @@ -128,126 +128,127 @@ public class BrowseInfo } /** - * @return the number of metadata fields at which to truncate with "et al" + * @return the number of metadata fields at which to truncate with "et al" */ public int getEtAl() { - return etAl; + return etAl; } /** * set the number of metadata fields at which to truncate with "et al" * * @param etAl + * the number of metadata fields at which to truncate with "et al" */ public void setEtAl(int etAl) { - this.etAl = etAl; + this.etAl = etAl; } /** - * @return Returns the focusItem. - */ - public int getFocusItem() - { - return focusItem; - } - - /** - * @param focusItem The focusItem to set. - */ - public void setFocusItem(int focusItem) - { - this.focusItem = focusItem; - } - - /** - * Does this browse have an item focus (as opposed to one of: no focus, - * a value focus) - * - * @return true if item focus, false if not - */ - public boolean hasItemFocus() - { - if (focusItem == -1) - { - return false; - } - return true; - } - - /** - * @return Returns the resultsPerPage. - */ - public int getResultsPerPage() - { - return resultsPerPage; - } - - /** - * @param resultsPerPage The resultsPerPage to set. - */ - public void setResultsPerPage(int resultsPerPage) - { - this.resultsPerPage = resultsPerPage; - } - - /** - * Is there a value associated with this browse - * - * @return true if a value, false if not - */ - public boolean hasValue() + * @return Returns the focusItem. + */ + public int getFocusItem() { - if (this.value != null) - { - return true; - } - return false; + return focusItem; } - /** - * Is there an authority key associated with this browse - * - * @return true if an authority key, false if not - */ - public boolean hasAuthority() + /** + * @param focusItem The focusItem to set. + */ + public void setFocusItem(int focusItem) { - if (this.authority != null) - { - return true; - } - return false; + this.focusItem = focusItem; } - /** - * Are there results for this browse, or was the result set empty? - * - * @return true if results, false if not - */ + /** + * Does this browse have an item focus (as opposed to one of: no focus, + * a value focus) + * + * @return true if item focus, false if not + */ + public boolean hasItemFocus() + { + if (focusItem == -1) + { + return false; + } + return true; + } + + /** + * @return Returns the resultsPerPage. + */ + public int getResultsPerPage() + { + return resultsPerPage; + } + + /** + * @param resultsPerPage The resultsPerPage to set. + */ + public void setResultsPerPage(int resultsPerPage) + { + this.resultsPerPage = resultsPerPage; + } + + /** + * Is there a value associated with this browse + * + * @return true if a value, false if not + */ + public boolean hasValue() + { + if (this.value != null) + { + return true; + } + return false; + } + + /** + * Is there an authority key associated with this browse + * + * @return true if an authority key, false if not + */ + public boolean hasAuthority() + { + if (this.authority != null) + { + return true; + } + return false; + } + + /** + * Are there results for this browse, or was the result set empty? + * + * @return true if results, false if not + */ public boolean hasResults() { - if (results.size() > 0) - { - return true; - } - return false; + if (results.size() > 0) + { + return true; + } + return false; } /** - * @param focus the value to focus the browse around + * @param focus the value to focus the browse around */ public void setFocus(String focus) { - this.focus = focus; + this.focus = focus; } /** - * @return the value to focus the browse around + * @return the value to focus the browse around */ public String getFocus() { - return this.focus; + return this.focus; } /** @@ -255,219 +256,219 @@ public class BrowseInfo * is not of type Collection or Community, this method will throw an * exception * - * @param dso the container object; a Community or Collection + * @param dso the container object; a Community or Collection * @throws BrowseException if browse error */ public void setBrowseContainer(DSpaceObject dso) - throws BrowseException + throws BrowseException { - if (dso instanceof Collection) - { - this.collection = (Collection) dso; - } - else if (dso instanceof Community) - { - this.community = (Community) dso; - } - else - { - throw new BrowseException("The container must be a community or a collection"); - } + if (dso instanceof Collection) + { + this.collection = (Collection) dso; + } + else if (dso instanceof Community) + { + this.community = (Community) dso; + } + else + { + throw new BrowseException("The container must be a community or a collection"); + } } /** * Obtain a DSpaceObject that represents the container object. This will be * a Community or a Collection * - * @return A DSpaceObject representing a Community or a Collection + * @return A DSpaceObject representing a Community or a Collection */ public DSpaceObject getBrowseContainer() { - if (this.collection != null) - { - return this.collection; - } - if (this.community != null) - { - return this.community; - } - return null; + if (this.collection != null) + { + return this.collection; + } + if (this.community != null) + { + return this.community; + } + return null; } /** - * @param level the browse level + * @param level the browse level */ public void setBrowseLevel(int level) { - this.level = level; + this.level = level; } /** - * @return the browse level + * @return the browse level */ public int getBrowseLevel() { - return this.level; + return this.level; } /** - * @param offset the database id of the item at the top of the next page + * @param offset the database id of the item at the top of the next page */ public void setNextOffset(int offset) { - this.nextOffset = offset; + this.nextOffset = offset; } /** - * @return the database id of the item at the top of the next page + * @return the database id of the item at the top of the next page */ public int getNextOffset() { - return this.nextOffset; + return this.nextOffset; } /** - * @return Returns the ascending. - */ - public boolean isAscending() - { - return ascending; - } + * @return Returns the ascending. + */ + public boolean isAscending() + { + return ascending; + } - /** - * @param ascending The ascending to set. - */ - public void setAscending(boolean ascending) - { - this.ascending = ascending; - } + /** + * @param ascending The ascending to set. + */ + public void setAscending(boolean ascending) + { + this.ascending = ascending; + } - /** - * @return Returns the browseIndex. - */ - public BrowseIndex getBrowseIndex() - { - return browseIndex; - } + /** + * @return Returns the browseIndex. + */ + public BrowseIndex getBrowseIndex() + { + return browseIndex; + } - /** - * @param browseIndex The browseIndex to set. - */ - public void setBrowseIndex(BrowseIndex browseIndex) - { - this.browseIndex = browseIndex; - } + /** + * @param browseIndex The browseIndex to set. + */ + public void setBrowseIndex(BrowseIndex browseIndex) + { + this.browseIndex = browseIndex; + } - /** - * @return Returns the prevItem. - */ - public int getPrevOffset() - { - return prevOffset > -1 ? prevOffset : 0; - } + /** + * @return Returns the prevItem. + */ + public int getPrevOffset() + { + return prevOffset > -1 ? prevOffset : 0; + } - /** - * @param prevOffset The prevOffset to set. - */ - public void setPrevOffset(int prevOffset) - { - this.prevOffset = prevOffset; - } + /** + * @param prevOffset The prevOffset to set. + */ + public void setPrevOffset(int prevOffset) + { + this.prevOffset = prevOffset; + } - /** - * @return Returns the sortOption. - */ - public SortOption getSortOption() - { - return sortOption; - } + /** + * @return Returns the sortOption. + */ + public SortOption getSortOption() + { + return sortOption; + } - /** - * @param sortOption The sortOption to set. - */ - public void setSortOption(SortOption sortOption) - { - this.sortOption = sortOption; - } + /** + * @param sortOption The sortOption to set. + */ + public void setSortOption(SortOption sortOption) + { + this.sortOption = sortOption; + } - /** - * @return Returns the startsWith. - */ - public boolean isStartsWith() - { - return startsWith; - } + /** + * @return Returns the startsWith. + */ + public boolean isStartsWith() + { + return startsWith; + } - /** - * @param startsWith The startsWith to set. - */ - public void setStartsWith(boolean startsWith) - { - this.startsWith = startsWith; - } + /** + * @param startsWith The startsWith to set. + */ + public void setStartsWith(boolean startsWith) + { + this.startsWith = startsWith; + } - /** - * @return Returns the value. - */ - public String getValue() - { - return value; - } + /** + * @return Returns the value. + */ + public String getValue() + { + return value; + } - /** - * @param value The value to set. - */ - public void setValue(String value) - { - this.value = value; - } + /** + * @param value The value to set. + */ + public void setValue(String value) + { + this.value = value; + } - /** - * @return Returns the authority key. - */ - public String getAuthority() - { - return authority; - } + /** + * @return Returns the authority key. + */ + public String getAuthority() + { + return authority; + } - /** - * @param authority The authority key to set. - */ - public void setAuthority(String authority) - { - this.authority = authority; - } + /** + * @param authority The authority key to set. + */ + public void setAuthority(String authority) + { + this.authority = authority; + } - /** - * is this a top level (0) browse? Examples of this are a full item - * browse or a single browse. Other browse types are considered - * second level (1) - * - * @return true if top level, false if not - */ - public boolean isTopLevel() - { - if (this.level == 0) - { - return true; - } - return false; - } + /** + * is this a top level (0) browse? Examples of this are a full item + * browse or a single browse. Other browse types are considered + * second level (1) + * + * @return true if top level, false if not + */ + public boolean isTopLevel() + { + if (this.level == 0) + { + return true; + } + return false; + } - /** - * Is this a second level (1) browse? Examples of this are a single - * value browse (e.g. all items by a given author) - * - * @return true if second level, false if not - */ - public boolean isSecondLevel() - { - if (this.level == 1) - { - return true; - } - return false; - } + /** + * Is this a second level (1) browse? Examples of this are a single + * value browse (e.g. all items by a given author) + * + * @return true if second level, false if not + */ + public boolean isSecondLevel() + { + if (this.level == 1) + { + return true; + } + return false; + } /** * The results of the Browse. Each member of the list is either a String array @@ -499,13 +500,13 @@ public class BrowseInfo */ public Item[] getItemResults() { - return new Item[0]; + return new Item[0]; } /** * Return the results of the Browse as a BrowseItem array * - * @return the results of the browse as a BrowseItem array + * @return the results of the browse as a BrowseItem array */ public List getBrowseItemResults() { @@ -593,243 +594,243 @@ public class BrowseInfo /** * are we browsing within a Community container? * - * @return true if in community, false if not + * @return true if in community, false if not */ public boolean inCommunity() - { - if (this.community != null) - { - return true; - } - return false; - } + { + if (this.community != null) + { + return true; + } + return false; + } /** * are we browsing within a Collection container * - * @return true if in collection, false if not + * @return true if in collection, false if not */ - public boolean inCollection() - { - if (this.collection != null) - { - return true; - } - return false; - } + public boolean inCollection() + { + if (this.collection != null) + { + return true; + } + return false; + } - /** - * Are there further results for the browse that haven't been returned yet? - * - * @return true if next page, false if not - */ - public boolean hasNextPage() - { - if (nextOffset > -1) - { - return true; - } - return false; - } + /** + * Are there further results for the browse that haven't been returned yet? + * + * @return true if next page, false if not + */ + public boolean hasNextPage() + { + if (nextOffset > -1) + { + return true; + } + return false; + } - /** - * Are there results prior to these that haven't been returned here? - * - * @return true if previous page, false if not - */ - public boolean hasPrevPage() - { - if (offset > 0) - { - return true; - } - return false; - } + /** + * Are there results prior to these that haven't been returned here? + * + * @return true if previous page, false if not + */ + public boolean hasPrevPage() + { + if (offset > 0) + { + return true; + } + return false; + } - /** - * Does this browse have a focus? - * - * @return true if focus, false if not - */ - public boolean hasFocus() - { - if ("".equals(focus) || focus == null) - { - return false; - } - return true; - } + /** + * Does this browse have a focus? + * + * @return true if focus, false if not + */ + public boolean hasFocus() + { + if ("".equals(focus) || focus == null) + { + return false; + } + return true; + } - /** - * Get an integer representing the number within the total set of results which - * marks the position of the first result in the current sub-set - * - * @return the start point of the browse page - */ - public int getStart() - { - return overallPosition + 1; - } + /** + * Get an integer representing the number within the total set of results which + * marks the position of the first result in the current sub-set + * + * @return the start point of the browse page + */ + public int getStart() + { + return overallPosition + 1; + } - /** - * Get an integer representing the number within the total set of results which - * marks the position of the last result in the current sub-set - * - * @return the end point of the browse page - */ - public int getFinish() - { - return overallPosition + results.size(); - } + /** + * Get an integer representing the number within the total set of results which + * marks the position of the last result in the current sub-set + * + * @return the end point of the browse page + */ + public int getFinish() + { + return overallPosition + results.size(); + } - /** - * Utility method for obtaining a string representation of the browse. This is - * useful only for debug + /** + * Utility method for obtaining a string representation of the browse. This is + * useful only for debug * @return String representation - */ + */ public String toString() { - try - { - StringBuffer sb = new StringBuffer(); + try + { + StringBuffer sb = new StringBuffer(); - // calculate the range for display - String from = Integer.toString(overallPosition + 1); - String to = Integer.toString(overallPosition + results.size()); - String of = Integer.toString(total); + // calculate the range for display + String from = Integer.toString(overallPosition + 1); + String to = Integer.toString(overallPosition + results.size()); + String of = Integer.toString(total); - // report on the positional information of the browse - sb.append("BrowseInfo String Representation: "); - sb.append("Browsing " + from + " to " + to + " of " + of + " "); + // report on the positional information of the browse + sb.append("BrowseInfo String Representation: "); + sb.append("Browsing " + from + " to " + to + " of " + of + " "); - // insert the information about which index - sb.append("in index: " + browseIndex.getName() + - " (data type: " + browseIndex.getDataType() + - ", display type: " + browseIndex.getDisplayType() + ") "); + // insert the information about which index + sb.append("in index: " + browseIndex.getName() + + " (data type: " + browseIndex.getDataType() + + ", display type: " + browseIndex.getDisplayType() + ") "); - sb.append("||"); + sb.append("||"); - // report on the browse scope container - String container = "all of DSpace"; - DSpaceObject theContainer = null; - if (inCollection()) - { - container = "collection"; - theContainer = this.collection; - } - else if (inCommunity()) - { - container = "community"; - theContainer = this.community; - } + // report on the browse scope container + String container = "all of DSpace"; + DSpaceObject theContainer = null; + if (inCollection()) + { + container = "collection"; + theContainer = this.collection; + } + else if (inCommunity()) + { + container = "community"; + theContainer = this.community; + } - String containerID = "no id available/necessary"; - if (theContainer != null) - { - containerID = theContainer.getID().toString() + " (" + theContainer.getHandle() + ")"; - } + String containerID = "no id available/necessary"; + if (theContainer != null) + { + containerID = theContainer.getID().toString() + " (" + theContainer.getHandle() + ")"; + } - sb.append("Browsing in " + container + ": " + containerID); - sb.append("||"); + sb.append("Browsing in " + container + ": " + containerID); + sb.append("||"); - // load the item list display configuration - ItemListConfig config = new ItemListConfig(); + // load the item list display configuration + ItemListConfig config = new ItemListConfig(); - // some information about the columns to be displayed - if (browseIndex.isItemIndex()) - { - sb.append("Listing over " + Integer.toString(config.numCols()) + " columns: "); - for (int k = 1; k <= config.numCols(); k++) - { - if (k > 1) - { - sb.append(","); - } - String[] meta = config.getMetadata(k); - sb.append(meta[0] + "." + meta[1] + "." + meta[2]); - } + // some information about the columns to be displayed + if (browseIndex.isItemIndex()) + { + sb.append("Listing over " + Integer.toString(config.numCols()) + " columns: "); + for (int k = 1; k <= config.numCols(); k++) + { + if (k > 1) + { + sb.append(","); + } + String[] meta = config.getMetadata(k); + sb.append(meta[0] + "." + meta[1] + "." + meta[2]); + } - if (value != null) - { - sb.append(" on value: ").append(value); - } + if (value != null) + { + sb.append(" on value: ").append(value); + } - if (isStartsWith()) - { - sb.append(" sort column starting with: ").append(focus); - } - else if (hasFocus()) - { - sb.append(" sort column focus: ").append(focus); - } - } - else if (browseIndex.isMetadataIndex()) - { - sb.append("Listing single column: ").append(browseIndex.getMetadata()); - if (isStartsWith()) - { - sb.append(" sort column starting with: ").append(focus); - } - else if (hasFocus()) - { - sb.append(" sort column focus: ").append(focus); - } - } + if (isStartsWith()) + { + sb.append(" sort column starting with: ").append(focus); + } + else if (hasFocus()) + { + sb.append(" sort column focus: ").append(focus); + } + } + else if (browseIndex.isMetadataIndex()) + { + sb.append("Listing single column: ").append(browseIndex.getMetadata()); + if (isStartsWith()) + { + sb.append(" sort column starting with: ").append(focus); + } + else if (hasFocus()) + { + sb.append(" sort column focus: ").append(focus); + } + } - sb.append("||"); + sb.append("||"); - // some information about how the data is sorted - String direction = (ascending ? "ASC" : "DESC"); - sb.append("Sorting by: " + sortOption.getMetadata() + " " + direction + - " (option " + Integer.toString(sortOption.getNumber()) + ")"); - sb.append("||"); + // some information about how the data is sorted + String direction = (ascending ? "ASC" : "DESC"); + sb.append("Sorting by: " + sortOption.getMetadata() + " " + direction + + " (option " + Integer.toString(sortOption.getNumber()) + ")"); + sb.append("||"); - // output the results - if (browseIndex.isMetadataIndex() && !isSecondLevel()) - { - sb.append(valueListingString()); - } - else if (browseIndex.isItemIndex() || isSecondLevel()) - { - sb.append(fullListingString(config)); - } + // output the results + if (browseIndex.isMetadataIndex() && !isSecondLevel()) + { + sb.append(valueListingString()); + } + else if (browseIndex.isItemIndex() || isSecondLevel()) + { + sb.append(fullListingString(config)); + } - sb.append("||"); + sb.append("||"); - // tell us what the next and previous values are going to be - sb.append("Top of next page: "); - if (hasNextPage()) - { - sb.append("offset: ").append(Integer.toString(this.nextOffset)); - } - else - { - sb.append("n/a"); - } - sb.append(";"); + // tell us what the next and previous values are going to be + sb.append("Top of next page: "); + if (hasNextPage()) + { + sb.append("offset: ").append(Integer.toString(this.nextOffset)); + } + else + { + sb.append("n/a"); + } + sb.append(";"); - sb.append("Top of previous page: "); - if (hasPrevPage()) - { - sb.append("offset: ").append(Integer.toString(this.prevOffset)); - } - else - { - sb.append("n/a"); - } + sb.append("Top of previous page: "); + if (hasPrevPage()) + { + sb.append("offset: ").append(Integer.toString(this.prevOffset)); + } + else + { + sb.append("n/a"); + } - sb.append("||"); + sb.append("||"); - return sb.toString(); - } - catch (SQLException e) - { - return e.getMessage(); - } - catch (BrowseException e) - { - return e.getMessage(); - } + return sb.toString(); + } + catch (SQLException e) + { + return e.getMessage(); + } + catch (BrowseException e) + { + return e.getMessage(); + } } /** @@ -841,55 +842,55 @@ public class BrowseInfo * @throws SQLException if database error */ private String fullListingString(ItemListConfig config) - throws SQLException + throws SQLException { - // report on all the results contained herein - StringBuffer sb = new StringBuffer(); + // report on all the results contained herein + StringBuffer sb = new StringBuffer(); - Iterator itr = results.iterator(); - while (itr.hasNext()) - { - Item bi = (Item) itr.next(); - if (bi == null) - { - sb.append("{{ NULL ITEM }}"); - break; - } - sb.append("{{Item ID: " + bi.getID().toString() + " :: "); + Iterator itr = results.iterator(); + while (itr.hasNext()) + { + Item bi = (Item) itr.next(); + if (bi == null) + { + sb.append("{{ NULL ITEM }}"); + break; + } + sb.append("{{Item ID: " + bi.getID().toString() + " :: "); - for (int j = 1; j <= config.numCols(); j++) - { - String[] md = config.getMetadata(j); - if (md == null) - { - sb.append("{{ NULL METADATA }}"); - break; - } - List values = itemService.getMetadata(bi, md[0], md[1], md[2], Item.ANY); - StringBuffer value = new StringBuffer(); - if (values != null) - { - for (int i = 0; i < values.size(); i++) - { - if (i > 0) - { - value.append(","); - } - value.append(values.get(i).getValue()); - } - } - else - { - value.append("-"); - } - String metadata = "[" + md[0] + "." + md[1] + "." + md[2] + ":" + value.toString() + "]"; - sb.append(metadata); - } + for (int j = 1; j <= config.numCols(); j++) + { + String[] md = config.getMetadata(j); + if (md == null) + { + sb.append("{{ NULL METADATA }}"); + break; + } + List values = itemService.getMetadata(bi, md[0], md[1], md[2], Item.ANY); + StringBuffer value = new StringBuffer(); + if (values != null) + { + for (int i = 0; i < values.size(); i++) + { + if (i > 0) + { + value.append(","); + } + value.append(values.get(i).getValue()); + } + } + else + { + value.append("-"); + } + String metadata = "[" + md[0] + "." + md[1] + "." + md[2] + ":" + value.toString() + "]"; + sb.append(metadata); + } - sb.append("}}"); - } + sb.append("}}"); + } - return sb.toString(); + return sb.toString(); } /** @@ -899,21 +900,21 @@ public class BrowseInfo */ private String valueListingString() { - // report on all the results contained herein - StringBuffer sb = new StringBuffer(); + // report on all the results contained herein + StringBuffer sb = new StringBuffer(); - Iterator itr = results.iterator(); - while (itr.hasNext()) - { - String theValue = (String) itr.next(); - if (theValue == null) - { - sb.append("{{ NULL VALUE }}"); - break; - } - sb.append("{{Value: " + theValue + "}}"); - } + Iterator itr = results.iterator(); + while (itr.hasNext()) + { + String theValue = (String) itr.next(); + if (theValue == null) + { + sb.append("{{ NULL VALUE }}"); + break; + } + sb.append("{{Value: " + theValue + "}}"); + } - return sb.toString(); + return sb.toString(); } } diff --git a/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java b/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java index 6de0051651..da607d9667 100644 --- a/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java +++ b/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java @@ -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 - *
    - *
    -h
    - *
    help
    - *
    -d
    - *
    Select deleted bitstreams
    - *
    -m
    - *
    Bitstreams missing from assetstore
    - *
    -c
    - *
    Bitstreams whose checksums were changed
    - *
    -n
    - *
    Bitstreams whose checksums were changed
    - *
    -a
    - *
    Send all reports in one email
    - *
    + *
    + *
    -h
    + *
    help
    + *
    -d
    + *
    Select deleted bitstreams
    + *
    -m
    + *
    Bitstreams missing from assetstore
    + *
    -c
    + *
    Bitstreams whose checksums were changed
    + *
    -n
    + *
    Bitstreams whose checksums were changed
    + *
    -a
    + *
    Send all reports in one email
    + *
    * + * @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(); } diff --git a/dspace-api/src/main/java/org/dspace/checker/dao/ChecksumHistoryDAO.java b/dspace-api/src/main/java/org/dspace/checker/dao/ChecksumHistoryDAO.java index 0aea30166e..06c74dc88c 100644 --- a/dspace-api/src/main/java/org/dspace/checker/dao/ChecksumHistoryDAO.java +++ b/dspace-api/src/main/java/org/dspace/checker/dao/ChecksumHistoryDAO.java @@ -30,8 +30,11 @@ public interface ChecksumHistoryDAO extends GenericDAO { * 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 { * 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; diff --git a/dspace-api/src/main/java/org/dspace/content/Bitstream.java b/dspace-api/src/main/java/org/dspace/content/Bitstream.java index 8632cd23c3..b0b6c210e4 100644 --- a/dspace-api/src/main/java/org/dspace/content/Bitstream.java +++ b/dspace-api/src/main/java/org/dspace/content/Bitstream.java @@ -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; } -} \ No newline at end of file +} diff --git a/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java b/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java index 4c3c20d798..dfa8f8e9b6 100644 --- a/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java @@ -379,12 +379,13 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl 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 diff --git a/dspace-api/src/main/java/org/dspace/content/DCDate.java b/dspace-api/src/main/java/org/dspace/content/DCDate.java index 0ce8d69989..e3363e1ba0 100644 --- a/dspace-api/src/main/java/org/dspace/content/DCDate.java +++ b/dspace-api/src/main/java/org/dspace/content/DCDate.java @@ -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) { diff --git a/dspace-api/src/main/java/org/dspace/content/ItemComparator.java b/dspace-api/src/main/java/org/dspace/content/ItemComparator.java index 734169c100..ae55691c3d 100644 --- a/dspace-api/src/main/java/org/dspace/content/ItemComparator.java +++ b/dspace-api/src/main/java/org/dspace/content/ItemComparator.java @@ -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) diff --git a/dspace-api/src/main/java/org/dspace/content/ItemServiceImpl.java b/dspace-api/src/main/java/org/dspace/content/ItemServiceImpl.java index e19b4083e1..916be3d62a 100644 --- a/dspace-api/src/main/java/org/dspace/content/ItemServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/content/ItemServiceImpl.java @@ -534,10 +534,10 @@ public class ItemServiceImpl extends DSpaceObjectServiceImpl 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 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 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 implements It /** * Check if the item is an inprogress submission + * * @param context - * @param item + * The relevant DSpace Context. + * @param item item to check * @return true 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 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 diff --git a/dspace-api/src/main/java/org/dspace/content/LicenseUtils.java b/dspace-api/src/main/java/org/dspace/content/LicenseUtils.java index 9effd3cab9..813d92481e 100644 --- a/dspace-api/src/main/java/org/dspace/content/LicenseUtils.java +++ b/dspace-api/src/main/java/org/dspace/content/LicenseUtils.java @@ -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, diff --git a/dspace-api/src/main/java/org/dspace/content/NonUniqueMetadataException.java b/dspace-api/src/main/java/org/dspace/content/NonUniqueMetadataException.java index 4fd8bb7f56..9d55a2aea3 100644 --- a/dspace-api/src/main/java/org/dspace/content/NonUniqueMetadataException.java +++ b/dspace-api/src/main/java/org/dspace/content/NonUniqueMetadataException.java @@ -27,6 +27,7 @@ public class NonUniqueMetadataException extends Exception * Create an exception with only a message * * @param message + * message string */ public NonUniqueMetadataException(String message) { diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/CrosswalkMetadataValidator.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/CrosswalkMetadataValidator.java index 0c704b9580..e6625dc2c0 100644 --- a/dspace-api/src/main/java/org/dspace/content/crosswalk/CrosswalkMetadataValidator.java +++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/CrosswalkMetadataValidator.java @@ -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; diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/METSRightsCrosswalk.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/METSRightsCrosswalk.java index b6786281e7..702495bf73 100644 --- a/dspace-api/src/main/java/org/dspace/content/crosswalk/METSRightsCrosswalk.java +++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/METSRightsCrosswalk.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/MODSDisseminationCrosswalk.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/MODSDisseminationCrosswalk.java index acfb3f6e29..bab81f6411 100644 --- a/dspace-api/src/main/java/org/dspace/content/crosswalk/MODSDisseminationCrosswalk.java +++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/MODSDisseminationCrosswalk.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/ParameterizedDisseminationCrosswalk.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/ParameterizedDisseminationCrosswalk.java index 315f2f655f..51e4918f67 100644 --- a/dspace-api/src/main/java/org/dspace/content/crosswalk/ParameterizedDisseminationCrosswalk.java +++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/ParameterizedDisseminationCrosswalk.java @@ -32,6 +32,7 @@ public interface ParameterizedDisseminationCrosswalk *

    * * @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. diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTDisseminationCrosswalk.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTDisseminationCrosswalk.java index 687bde5a1f..23f11368c8 100644 --- a/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTDisseminationCrosswalk.java +++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTDisseminationCrosswalk.java @@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory; * Configurable XSLT-driven dissemination Crosswalk *

    * See the XSLTCrosswalk superclass for details on configuration. - *

    + *

    *

    Additional Configuration of Dissemination crosswalk:

    * 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 [output-file]} - * @param argv arguments + * + * @param argv the command line arguments given * @throws Exception if error */ public static void main(String[] argv) throws Exception diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTIngestionCrosswalk.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTIngestionCrosswalk.java index 47f5b09bb5..283711dd2a 100644 --- a/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTIngestionCrosswalk.java +++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/XSLTIngestionCrosswalk.java @@ -293,7 +293,8 @@ public class XSLTIngestionCrosswalk /** * Simple command-line rig for testing the DIM output of a stylesheet. * Usage: {@code java XSLTIngestionCrosswalk } - * @param argv arguments + * + * @param argv the command line arguments given * @throws Exception if error */ public static void main(String[] argv) throws Exception diff --git a/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectDAO.java b/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectDAO.java index 8486abf0cd..ae734de684 100644 --- a/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectDAO.java +++ b/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectDAO.java @@ -15,7 +15,7 @@ import org.dspace.core.GenericDAO; * All DSpaceObject DAO classes should implement this class since it ensures that the T object is of type DSpaceObject * * @author kevinvandevelde at atmire.com - * @param + * @param some implementation of DSpaceObject */ public interface DSpaceObjectDAO extends GenericDAO { } diff --git a/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectLegacySupportDAO.java b/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectLegacySupportDAO.java index 4f8130b861..edda89dc14 100644 --- a/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectLegacySupportDAO.java +++ b/dspace-api/src/main/java/org/dspace/content/dao/DSpaceObjectLegacySupportDAO.java @@ -17,7 +17,7 @@ import java.sql.SQLException; * to identify DSpaceObjects prior to DSpace 6.0 * * @author kevinvandevelde at atmire.com - * @param + * @param some implementation of DSpaceObject */ public interface DSpaceObjectLegacySupportDAO extends DSpaceObjectDAO { diff --git a/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSIngester.java b/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSIngester.java index d2e3ef7e62..568ed15731 100644 --- a/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSIngester.java +++ b/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSIngester.java @@ -106,6 +106,7 @@ public abstract class AbstractMETSIngester extends AbstractPackageIngester protected final WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); /** + *

    * An instance of ZipMdrefManager holds the state needed to retrieve the * contents of an external metadata stream referenced by an * mdRef 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

    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 mdref elements) + * the MdrefManager (manages all external metadata files + * referenced by METS mdref elements) * @param dmds -* array of Elements, each a METS dmdSec that -* applies to the Item as a whole. + * array of Elements, each a METS dmdSec 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 diff --git a/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPDisseminator.java b/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPDisseminator.java index ca735905c6..31def67bed 100644 --- a/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPDisseminator.java +++ b/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPDisseminator.java @@ -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, diff --git a/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPIngester.java b/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPIngester.java index edf88aacd8..b964cfa621 100644 --- a/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPIngester.java +++ b/dspace-api/src/main/java/org/dspace/content/packager/DSpaceAIPIngester.java @@ -95,6 +95,21 @@ public class DSpaceAIPIngester * 3. If (1) or (2) succeeds, crosswalk it and ignore all other DMDs with * same GROUPID
    * 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 mdref elements) + * @param dmds + * array of Elements, each a METS dmdSec 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. - *

    + *

    * 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) + *

    * - * @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. diff --git a/dspace-api/src/main/java/org/dspace/content/packager/PackageValidationException.java b/dspace-api/src/main/java/org/dspace/content/packager/PackageValidationException.java index 5600209773..5b36692d95 100644 --- a/dspace-api/src/main/java/org/dspace/content/packager/PackageValidationException.java +++ b/dspace-api/src/main/java/org/dspace/content/packager/PackageValidationException.java @@ -8,15 +8,18 @@ package org.dspace.content.packager; /** + *

    * 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. + *

    *

    * 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. + *

    * * @author Larry Stone * @version $Revision$ diff --git a/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java b/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java index 9e230e0e55..1d9f91e2cb 100644 --- a/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java +++ b/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/content/service/CollectionService.java b/dspace-api/src/main/java/org/dspace/content/service/CollectionService.java index 5ba99ae434..1a82bfa8c3 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/CollectionService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/CollectionService.java @@ -77,8 +77,11 @@ public interface CollectionService extends DSpaceObjectService, 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 */ diff --git a/dspace-api/src/main/java/org/dspace/content/service/CommunityService.java b/dspace-api/src/main/java/org/dspace/content/service/CommunityService.java index 020854b99b..1e20b0470e 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/CommunityService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/CommunityService.java @@ -104,7 +104,7 @@ public interface CommunityService extends DSpaceObjectService, 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, 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, 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 getAllParents(Context context, Collection collection) throws SQLException; diff --git a/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java b/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java index 4997de29ad..6f111fcd86 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java @@ -181,7 +181,7 @@ public interface DSpaceObjectService { * * @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); diff --git a/dspace-api/src/main/java/org/dspace/content/service/ItemService.java b/dspace-api/src/main/java/org/dspace/content/service/ItemService.java index bf44b340c4..a28e947dbf 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/ItemService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/ItemService.java @@ -53,7 +53,7 @@ public interface ItemService extends DSpaceObjectService, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, DSpaceObjectLega */ int countWithdrawnItems(Context context) throws SQLException; - /** - * Check if the supplied item is an inprogress submission - * @param context - * @param item - * @return true 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 true if the item is linked to a workspaceitem or workflowitem + * @throws SQLException if database error + */ boolean isInProgressSubmission(Context context, Item item) throws SQLException; } diff --git a/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java b/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java index 4199498010..b94092d9d1 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java @@ -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) diff --git a/dspace-api/src/main/java/org/dspace/content/service/MetadataSchemaService.java b/dspace-api/src/main/java/org/dspace/content/service/MetadataSchemaService.java index b2a2e45662..0d779f1aa0 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/MetadataSchemaService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/MetadataSchemaService.java @@ -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; diff --git a/dspace-api/src/main/java/org/dspace/content/service/MetadataValueService.java b/dspace-api/src/main/java/org/dspace/content/service/MetadataValueService.java index 841c75d542..6189eb2be5 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/MetadataValueService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/MetadataValueService.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/content/service/WorkspaceItemService.java b/dspace-api/src/main/java/org/dspace/content/service/WorkspaceItemService.java index 68900d3a6a..b8640d7b1e 100644 --- a/dspace-api/src/main/java/org/dspace/content/service/WorkspaceItemService.java +++ b/dspace-api/src/main/java/org/dspace/content/service/WorkspaceItemService.java @@ -143,6 +143,7 @@ public interface WorkspaceItemService extends InProgressSubmissionService implements GenericDAO { * 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 implements GenericDAO { * 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 implements GenericDAO { /** * 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) diff --git a/dspace-api/src/main/java/org/dspace/core/AbstractHibernateDSODAO.java b/dspace-api/src/main/java/org/dspace/core/AbstractHibernateDSODAO.java index db91b7a0fc..8f81c8905c 100644 --- a/dspace-api/src/main/java/org/dspace/core/AbstractHibernateDSODAO.java +++ b/dspace-api/src/main/java/org/dspace/core/AbstractHibernateDSODAO.java @@ -40,8 +40,11 @@ public abstract class AbstractHibernateDSODAO 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 metadataFields) { @@ -63,26 +66,26 @@ public abstract class AbstractHibernateDSODAO extends Ab */ protected void addMetadataValueWhereQuery(StringBuilder query, List 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 extends Ab protected void addMetadataSortQuery(StringBuilder query, List metadataSortFields, List 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(","); } diff --git a/dspace-api/src/main/java/org/dspace/core/Context.java b/dspace-api/src/main/java/org/dspace/core/Context.java index c99adbe13e..e359f5be23 100644 --- a/dspace-api/src/main/java/org/dspace/core/Context.java +++ b/dspace-api/src/main/java/org/dspace/core/Context.java @@ -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) { @@ -630,10 +631,9 @@ public class Context /** - * Returns the size of the cache of all object that have been read from the database so far. A larger number - * 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}). + * Returns the size of the cache of all object that have been read from the database so far. * + * @return connection cache size * @throws SQLException When connecting to the active cache fails. */ public long getCacheSize() throws SQLException { diff --git a/dspace-api/src/main/java/org/dspace/core/DBConnection.java b/dspace-api/src/main/java/org/dspace/core/DBConnection.java index fea8547354..c0d24fbb0c 100644 --- a/dspace-api/src/main/java/org/dspace/core/DBConnection.java +++ b/dspace-api/src/main/java/org/dspace/core/DBConnection.java @@ -48,13 +48,20 @@ public interface DBConnection { /** * Reload a DSpace object from the database. This will make sure the object is valid and stored in the cache. + * @param the type of entity. * @param entity The DSpace object to reload + * @return the reloaded entity. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public E reloadEntity(E entity) throws SQLException; /** * Remove a DSpace object from the cache when batch processing a large number of objects. + * @param the type of entity. * @param entity The DSpace object to reload + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public void uncacheEntity(E entity) throws SQLException ; -} \ No newline at end of file +} diff --git a/dspace-api/src/main/java/org/dspace/core/Email.java b/dspace-api/src/main/java/org/dspace/core/Email.java index 9a5ecb6d90..e3a1bc57b2 100644 --- a/dspace-api/src/main/java/org/dspace/core/Email.java +++ b/dspace-api/src/main/java/org/dspace/core/Email.java @@ -42,25 +42,28 @@ import org.dspace.services.factory.DSpaceServicesFactory; /** * Class representing an e-mail message, also used to send e-mails. - *

    + *

    * Typical use: - *

    + *

    + *

    * Email email = new Email();
    * email.addRecipient("foo@bar.com");
    * email.addArgument("John");
    * email.addArgument("On the Testing of DSpace");
    * email.send();
    - *

    + *

    + *

    * name is the name of an email template in * dspace-dir/config/emails/ (which also includes the subject.) * arg0 and arg1 are arguments to fill out the * message with. - *

    + *

    + *

    * Emails are formatted using java.text.MessageFormat. * 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: - *

    + *

    * *
      *
    @@ -77,10 +80,10 @@ import org.dspace.services.factory.DSpaceServicesFactory;
      *
      * 
    * - *

    + *

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

    + *

    * *
      *
    @@ -91,9 +94,10 @@ import org.dspace.services.factory.DSpaceServicesFactory;
      *
      * 
    * - *

    + *

    * Note that parameters like {0} cannot be placed in the subject * of the e-mail; they won't get filled out. + *

    * * * @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 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 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 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 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 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"); diff --git a/dspace-api/src/main/java/org/dspace/core/GenericDAO.java b/dspace-api/src/main/java/org/dspace/core/GenericDAO.java index 2013905879..20a03f039e 100644 --- a/dspace-api/src/main/java/org/dspace/core/GenericDAO.java +++ b/dspace-api/src/main/java/org/dspace/core/GenericDAO.java @@ -33,6 +33,7 @@ public interface GenericDAO * 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 * 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 * 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 diff --git a/dspace-api/src/main/java/org/dspace/core/LegacyPluginServiceImpl.java b/dspace-api/src/main/java/org/dspace/core/LegacyPluginServiceImpl.java index 35b9f1b0fb..eb80542bbe 100644 --- a/dspace-api/src/main/java/org/dspace/core/LegacyPluginServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/core/LegacyPluginServiceImpl.java @@ -23,38 +23,43 @@ import org.dspace.services.ConfigurationService; import org.springframework.beans.factory.annotation.Autowired; /** + *

    * 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.) + *

    *

    * 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: - *

    - *

    1. Singleton Plugin - *
      There is only one implementation class for the plugin. It is indicated + *

      + *
        + *
      1. Singleton Plugin
        + * 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.
      2. * - *

      3. Sequence Plugins - *
        You need a sequence or series of plugins, to implement a mechanism like + *
      4. Sequence Plugins
        + * 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. - *

      5. Named Plugins - *
        Use a named plugin when the application has to choose one plugin + * whole.
      6. + *
      7. Named Plugins
        + * 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. - *

      + * to one or more names (symbolic identifiers) in the configuration.

    2. + *
    + *

    * The name is just a String 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. + *

    * * @author Larry Stone * @author Tim Donohue (turned old PluginManager into a PluginService) @@ -122,7 +127,7 @@ public class LegacyPluginServiceImpl implements PluginService * * @param interfaceClass interface Class object * @return instance of plugin - * @throws PluginConfigurationError + * @throws PluginConfigurationError if no matching singleton plugin is configured. */ @Override public Object getSinglePlugin(Class interfaceClass) @@ -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 * checkConfiguration 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 diff --git a/dspace-api/src/main/java/org/dspace/core/NewsServiceImpl.java b/dspace-api/src/main/java/org/dspace/core/NewsServiceImpl.java index 12309e74c8..8a0c5a89e5 100644 --- a/dspace-api/src/main/java/org/dspace/core/NewsServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/core/NewsServiceImpl.java @@ -35,27 +35,27 @@ public class NewsServiceImpl implements NewsService { private final Logger log = LoggerFactory.getLogger(NewsServiceImpl.class); - private List acceptableFilenames; + private List acceptableFilenames; @Autowired(required = true) private ConfigurationService configurationService; - - public void setAcceptableFilenames(List acceptableFilenames) { + + public void setAcceptableFilenames(List acceptableFilenames) { this.acceptableFilenames = addLocalesToAcceptableFilenames(acceptableFilenames); } - protected List addLocalesToAcceptableFilenames(List acceptableFilenames){ + protected List addLocalesToAcceptableFilenames(List acceptableFilenames) { String [] locales = configurationService.getArrayProperty("webui.supported.locales"); List 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; + } } diff --git a/dspace-api/src/main/java/org/dspace/core/service/NewsService.java b/dspace-api/src/main/java/org/dspace/core/service/NewsService.java index 7612614f25..a9f9f04e5e 100644 --- a/dspace-api/src/main/java/org/dspace/core/service/NewsService.java +++ b/dspace-api/src/main/java/org/dspace/core/service/NewsService.java @@ -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); } diff --git a/dspace-api/src/main/java/org/dspace/ctask/general/BasicLinkChecker.java b/dspace-api/src/main/java/org/dspace/ctask/general/BasicLinkChecker.java index c53f6fcbe6..b216b75ba1 100644 --- a/dspace-api/src/main/java/org/dspace/ctask/general/BasicLinkChecker.java +++ b/dspace-api/src/main/java/org/dspace/ctask/general/BasicLinkChecker.java @@ -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) diff --git a/dspace-api/src/main/java/org/dspace/ctask/general/BitstreamsIntoMetadata.java b/dspace-api/src/main/java/org/dspace/ctask/general/BitstreamsIntoMetadata.java index bf15c77225..daae192b4b 100644 --- a/dspace-api/src/main/java/org/dspace/ctask/general/BitstreamsIntoMetadata.java +++ b/dspace-api/src/main/java/org/dspace/ctask/general/BitstreamsIntoMetadata.java @@ -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() + "##"; diff --git a/dspace-api/src/main/java/org/dspace/ctask/general/ClamScan.java b/dspace-api/src/main/java/org/dspace/ctask/general/ClamScan.java index eecdd89a25..0a36ad9194 100644 --- a/dspace-api/src/main/java/org/dspace/ctask/general/ClamScan.java +++ b/dspace-api/src/main/java/org/dspace/ctask/general/ClamScan.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/curate/Curator.java b/dspace-api/src/main/java/org/dspace/curate/Curator.java index d52cba77e9..8429f12cea 100644 --- a/dspace-api/src/main/java/org/dspace/curate/Curator.java +++ b/dspace-api/src/main/java/org/dspace/curate/Curator.java @@ -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. - *

    + *

    * 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()) diff --git a/dspace-api/src/main/java/org/dspace/curate/ResolvedTask.java b/dspace-api/src/main/java/org/dspace/curate/ResolvedTask.java index 7c3051cd09..177f5fab88 100644 --- a/dspace-api/src/main/java/org/dspace/curate/ResolvedTask.java +++ b/dspace-api/src/main/java/org/dspace/curate/ResolvedTask.java @@ -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; diff --git a/dspace-api/src/main/java/org/dspace/curate/TaskQueueEntry.java b/dspace-api/src/main/java/org/dspace/curate/TaskQueueEntry.java index 7688356779..dcdf8374ca 100644 --- a/dspace-api/src/main/java/org/dspace/curate/TaskQueueEntry.java +++ b/dspace-api/src/main/java/org/dspace/curate/TaskQueueEntry.java @@ -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 taskNames, String objId) diff --git a/dspace-api/src/main/java/org/dspace/curate/Utils.java b/dspace-api/src/main/java/org/dspace/curate/Utils.java index 20cb6c4b48..01ca98e60b 100644 --- a/dspace-api/src/main/java/org/dspace/curate/Utils.java +++ b/dspace-api/src/main/java/org/dspace/curate/Utils.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/curate/WorkflowCuratorServiceImpl.java b/dspace-api/src/main/java/org/dspace/curate/WorkflowCuratorServiceImpl.java index 2452554a2a..dd94a24563 100644 --- a/dspace-api/src/main/java/org/dspace/curate/WorkflowCuratorServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/curate/WorkflowCuratorServiceImpl.java @@ -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 tsMap = new HashMap(); @@ -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(); diff --git a/dspace-api/src/main/java/org/dspace/curate/service/WorkflowCuratorService.java b/dspace-api/src/main/java/org/dspace/curate/service/WorkflowCuratorService.java index 36cdb60cb5..2240008e22 100644 --- a/dspace-api/src/main/java/org/dspace/curate/service/WorkflowCuratorService.java +++ b/dspace-api/src/main/java/org/dspace/curate/service/WorkflowCuratorService.java @@ -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; } diff --git a/dspace-api/src/main/java/org/dspace/discovery/DiscoverHitHighlightingField.java b/dspace-api/src/main/java/org/dspace/discovery/DiscoverHitHighlightingField.java index 9b8261f2e1..d51d659cf0 100644 --- a/dspace-api/src/main/java/org/dspace/discovery/DiscoverHitHighlightingField.java +++ b/dspace-api/src/main/java/org/dspace/discovery/DiscoverHitHighlightingField.java @@ -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; diff --git a/dspace-api/src/main/java/org/dspace/discovery/IndexClient.java b/dspace-api/src/main/java/org/dspace/discovery/IndexClient.java index b58980de00..595da581f0 100644 --- a/dspace-api/src/main/java/org/dspace/discovery/IndexClient.java +++ b/dspace-api/src/main/java/org/dspace/discovery/IndexClient.java @@ -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 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(); } } -} \ No newline at end of file +} diff --git a/dspace-api/src/main/java/org/dspace/discovery/SearchService.java b/dspace-api/src/main/java/org/dspace/discovery/SearchService.java index d161a2d3d5..641e740bb9 100644 --- a/dspace-api/src/main/java/org/dspace/discovery/SearchService.java +++ b/dspace-api/src/main/java/org/dspace/discovery/SearchService.java @@ -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 true 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 true 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 + * 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 {@link 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); diff --git a/dspace-api/src/main/java/org/dspace/discovery/SearchUtils.java b/dspace-api/src/main/java/org/dspace/discovery/SearchUtils.java index 69a8bdb034..f5d8a33877 100644 --- a/dspace-api/src/main/java/org/dspace/discovery/SearchUtils.java +++ b/dspace-api/src/main/java/org/dspace/discovery/SearchUtils.java @@ -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 getAllDiscoveryConfigurations(Item item) throws SQLException { Map result = new HashMap(); @@ -82,14 +85,14 @@ public class SearchUtils { List 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); } diff --git a/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java b/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java index 67bfc71678..fff6d82d63 100644 --- a/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java @@ -79,7 +79,7 @@ import org.dspace.eperson.factory.EPersonServiceFactory; * that cron. * * The SolrServiceImpl is registered as a Service in the ServiceManager via - * a spring configuration file located under + * a Spring configuration file located under * classpath://spring/spring-dspace-applicationContext.xml * * Its configuration is Autowired by the ApplicationContext @@ -257,6 +257,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { * unIndex removes an Item, Collection, or Community * * @param context + * The relevant DSpace Context. * @param dso DSpace Object, can be Community, Item, or Collection * @throws SQLException if database error * @throws IOException if IO error @@ -271,6 +272,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { * unIndex removes an Item, Collection, or Community * * @param context + * The relevant DSpace Context. * @param dso DSpace Object, can be Community, Item, or Collection * @param commit if true force an immediate commit on SOLR * @throws SQLException if database error @@ -286,7 +288,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } String uniqueID = dso.getType()+"-"+dso.getID(); getSolr().deleteById(uniqueID); - if(commit) + if (commit) { getSolr().commit(); } @@ -320,9 +322,9 @@ public class SolrServiceImpl implements SearchService, IndexingService { throws SQLException, IOException { try { - if(getSolr() != null){ + if (getSolr() != null) { getSolr().deleteByQuery(HANDLE_FIELD + ":\"" + handle + "\""); - if(commit) + if (commit) { getSolr().commit(); } @@ -416,7 +418,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { indexContent(context, community, force); } - if(getSolr() != null) + if (getSolr() != null) { getSolr().commit(); } @@ -445,7 +447,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { try { - if(getSolr() == null) + if (getSolr() == null) { return; } @@ -484,7 +486,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } } } - } catch(Exception e) + } catch (Exception e) { throw new SearchServiceException(e.getMessage(), e); @@ -506,7 +508,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { public void optimize() { try { - if(getSolr() == null) + if (getSolr() == null) { return; } @@ -613,7 +615,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { QueryResponse rsp; try { - if(getSolr() == null) + if (getSolr() == null) { return false; } @@ -630,7 +632,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { Object value = doc.getFieldValue(LAST_INDEXED_FIELD); - if(value instanceof Date) + if (value instanceof Date) { Date lastIndexed = (Date) value; @@ -711,7 +713,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { List allCollections = new ArrayList<>(); - for( ResourcePolicy rp: collectionsPolicies){ + for( ResourcePolicy rp: collectionsPolicies) { Collection collection = ContentServiceFactory.getInstance().getCollectionService() .find(context, rp.getdSpaceObject().getID()); allCollections.add(collection); @@ -761,16 +763,19 @@ public class SolrServiceImpl implements SearchService, IndexingService { /** * Write the document to the index under the appropriate handle. * - * @param doc the solr document to be written to the server + * @param doc + * the solr document to be written to the server * @param streams - * @throws IOException IO exception + * list of bitstream content streams + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ protected void writeDocument(SolrInputDocument doc, List streams) throws IOException { try { - if(getSolr() != null) + if (getSolr() != null) { - if(CollectionUtils.isNotEmpty(streams)) + if (CollectionUtils.isNotEmpty(streams)) { ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract"); @@ -811,6 +816,8 @@ public class SolrServiceImpl implements SearchService, IndexingService { /** * Build a solr document for a DSpace Community. * + * @param context + * The relevant DSpace Context. * @param community Community to be indexed * @throws SQLException if database error * @throws IOException if IO error @@ -824,7 +831,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { DiscoveryConfiguration discoveryConfiguration = SearchUtils.getDiscoveryConfiguration(community); DiscoveryHitHighlightingConfiguration highlightingConfiguration = discoveryConfiguration.getHitHighlightingConfiguration(); List highlightedMetadataFields = new ArrayList(); - if(highlightingConfiguration != null) + if (highlightingConfiguration != null) { for (DiscoveryHitHighlightFieldConfiguration configuration : highlightingConfiguration.getMetadataFields()) { @@ -859,6 +866,8 @@ public class SolrServiceImpl implements SearchService, IndexingService { /** * Build a solr document for a DSpace Collection. * + * @param context + * The relevant DSpace Context. * @param collection Collection to be indexed * @throws SQLException sql exception * @throws IOException IO exception @@ -874,7 +883,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { DiscoveryConfiguration discoveryConfiguration = SearchUtils.getDiscoveryConfiguration(collection); DiscoveryHitHighlightingConfiguration highlightingConfiguration = discoveryConfiguration.getHitHighlightingConfiguration(); List highlightedMetadataFields = new ArrayList(); - if(highlightingConfiguration != null) + if (highlightingConfiguration != null) { for (DiscoveryHitHighlightFieldConfiguration configuration : highlightingConfiguration.getMetadataFields()) { @@ -915,19 +924,21 @@ public class SolrServiceImpl implements SearchService, IndexingService { /** * Add the metadata value of the community/collection to the solr document * IF needed highlighting is added ! + * * @param doc the solr document * @param highlightedMetadataFields the list of metadata fields that CAN be highlighted + * @param toIgnoreMetadataFields the list of metadata fields to skip adding to Solr * @param metadataField the metadata field added * @param value the value (can be NULL !) */ protected void addContainerMetadataField(SolrInputDocument doc, List highlightedMetadataFields, List toIgnoreMetadataFields, String metadataField, String value) { - if(toIgnoreMetadataFields == null || !toIgnoreMetadataFields.contains(metadataField)) + if (toIgnoreMetadataFields == null || !toIgnoreMetadataFields.contains(metadataField)) { - if(StringUtils.isNotBlank(value)) + if (StringUtils.isNotBlank(value)) { doc.addField(metadataField, value); - if(highlightedMetadataFields.contains(metadataField)) + if (highlightedMetadataFields.contains(metadataField)) { doc.addField(metadataField + "_hl", value); } @@ -985,10 +996,10 @@ public class SolrServiceImpl implements SearchService, IndexingService { { String metadataField = discoverySearchFilter.getMetadataFields().get(j); List resultingList; - if(searchFilters.get(metadataField) != null) + if (searchFilters.get(metadataField) != null) { resultingList = searchFilters.get(metadataField); - }else{ + } else { //New metadata field, create a new list for it resultingList = new ArrayList(); } @@ -999,7 +1010,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } DiscoverySortConfiguration sortConfiguration = discoveryConfiguration.getSearchSortConfiguration(); - if(sortConfiguration != null) + if (sortConfiguration != null) { for (DiscoverySortFieldConfiguration discoverySortConfiguration : sortConfiguration.getSortFields()) { @@ -1008,22 +1019,22 @@ public class SolrServiceImpl implements SearchService, IndexingService { } DiscoveryRecentSubmissionsConfiguration recentSubmissionConfiguration = discoveryConfiguration.getRecentSubmissionConfiguration(); - if(recentSubmissionConfiguration != null) + if (recentSubmissionConfiguration != null) { recentSubmissionsConfigurationMap.put(recentSubmissionConfiguration.getMetadataSortField(), recentSubmissionConfiguration); } DiscoveryHitHighlightingConfiguration hitHighlightingConfiguration = discoveryConfiguration.getHitHighlightingConfiguration(); - if(hitHighlightingConfiguration != null) + if (hitHighlightingConfiguration != null) { List fieldConfigurations = hitHighlightingConfiguration.getMetadataFields(); for (DiscoveryHitHighlightFieldConfiguration fieldConfiguration : fieldConfigurations) { hitHighlightingFields.add(fieldConfiguration.getField()); } - } + } DiscoveryMoreLikeThisConfiguration moreLikeThisConfiguration = discoveryConfiguration.getMoreLikeThisConfiguration(); - if(moreLikeThisConfiguration != null) + if (moreLikeThisConfiguration != null) { for(String metadataField : moreLikeThisConfiguration.getSimilarityMetadataFields()) { @@ -1035,7 +1046,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { List toProjectionFields = new ArrayList(); String[] projectionFields = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("discovery.index.projection"); - if(projectionFields != null){ + if (projectionFields != null) { for (String field : projectionFields) { toProjectionFields.add(field.trim()); } @@ -1128,7 +1139,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { if ((searchFilters.get(field) != null || searchFilters.get(unqualifiedField + "." + Item.ANY) != null)) { List searchFilterConfigs = searchFilters.get(field); - if(searchFilterConfigs == null) + if (searchFilterConfigs == null) { searchFilterConfigs = searchFilters.get(unqualifiedField + "." + Item.ANY); } @@ -1137,15 +1148,15 @@ public class SolrServiceImpl implements SearchService, IndexingService { { Date date = null; String separator = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("discovery.solr.facets.split.char"); - if(separator == null) + if (separator == null) { separator = FILTER_SEPARATOR; } - if(searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) + if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) { //For our search filters that are dates we format them properly date = MultiFormatDateParser.parse(value); - if(date != null) + if (date != null) { //TODO: make this date format configurable ! value = DateFormatUtils.formatUTC(date, "yyyy-MM-dd"); @@ -1214,68 +1225,68 @@ public class SolrServiceImpl implements SearchService, IndexingService { } } - if(searchFilter.getFilterType().equals(DiscoverySearchFilterFacet.FILTER_TYPE_FACET)) + if (searchFilter.getFilterType().equals(DiscoverySearchFilterFacet.FILTER_TYPE_FACET)) { - if(searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_TEXT)) + if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_TEXT)) { - //Add a special filter - //We use a separator to split up the lowercase and regular case, this is needed to get our filters in regular case - //Solr has issues with facet prefix and cases - if (authority != null) - { - String facetValue = preferedLabel != null?preferedLabel:value; - doc.addField(searchFilter.getIndexFieldName() + "_filter", facetValue.toLowerCase() + separator + facetValue + AUTHORITY_SEPARATOR + authority); - } - else - { - doc.addField(searchFilter.getIndexFieldName() + "_filter", value.toLowerCase() + separator + value); - } - }else - if(searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) + //Add a special filter + //We use a separator to split up the lowercase and regular case, this is needed to get our filters in regular case + //Solr has issues with facet prefix and cases + if (authority != null) { - if(date != null) + String facetValue = preferedLabel != null?preferedLabel:value; + doc.addField(searchFilter.getIndexFieldName() + "_filter", facetValue.toLowerCase() + separator + facetValue + AUTHORITY_SEPARATOR + authority); + } + else + { + doc.addField(searchFilter.getIndexFieldName() + "_filter", value.toLowerCase() + separator + value); + } + } else + if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) + { + if (date != null) { String indexField = searchFilter.getIndexFieldName() + ".year"; String yearUTC = DateFormatUtils.formatUTC(date, "yyyy"); - doc.addField(searchFilter.getIndexFieldName() + "_keyword", yearUTC); - // add the year to the autocomplete index - doc.addField(searchFilter.getIndexFieldName() + "_ac", yearUTC); - doc.addField(indexField, yearUTC); + doc.addField(searchFilter.getIndexFieldName() + "_keyword", yearUTC); + // add the year to the autocomplete index + doc.addField(searchFilter.getIndexFieldName() + "_ac", yearUTC); + doc.addField(indexField, yearUTC); - if (yearUTC.startsWith("0")) + if (yearUTC.startsWith("0")) { - doc.addField( - searchFilter.getIndexFieldName() - + "_keyword", - yearUTC.replaceFirst("0*", "")); - // add date without starting zeros for autocomplete e filtering - doc.addField( - searchFilter.getIndexFieldName() - + "_ac", - yearUTC.replaceFirst("0*", "")); - doc.addField( - searchFilter.getIndexFieldName() - + "_ac", - value.replaceFirst("0*", "")); - doc.addField( - searchFilter.getIndexFieldName() - + "_keyword", - value.replaceFirst("0*", "")); + doc.addField( + searchFilter.getIndexFieldName() + + "_keyword", + yearUTC.replaceFirst("0*", "")); + // add date without starting zeros for autocomplete e filtering + doc.addField( + searchFilter.getIndexFieldName() + + "_ac", + yearUTC.replaceFirst("0*", "")); + doc.addField( + searchFilter.getIndexFieldName() + + "_ac", + value.replaceFirst("0*", "")); + doc.addField( + searchFilter.getIndexFieldName() + + "_keyword", + value.replaceFirst("0*", "")); } - //Also save a sort value of this year, this is required for determining the upper & lower bound year of our facet - if(doc.getField(indexField + "_sort") == null) + //Also save a sort value of this year, this is required for determining the upper & lower bound year of our facet + if (doc.getField(indexField + "_sort") == null) { - //We can only add one year so take the first one - doc.addField(indexField + "_sort", yearUTC); - } + //We can only add one year so take the first one + doc.addField(indexField + "_sort", yearUTC); + } } - }else - if(searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_HIERARCHICAL)) + } else + if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_HIERARCHICAL)) { HierarchicalSidebarFacetConfiguration hierarchicalSidebarFacetConfiguration = (HierarchicalSidebarFacetConfiguration) searchFilter; String[] subValues = value.split(hierarchicalSidebarFacetConfiguration.getSplitter()); - if(hierarchicalSidebarFacetConfiguration.isSkipFirstNodeLevel() && 1 < subValues.length) + if (hierarchicalSidebarFacetConfiguration.isSkipFirstNodeLevel() && 1 < subValues.length) { //Remove the first element of our array subValues = (String[]) ArrayUtils.subarray(subValues, 1, subValues.length); @@ -1286,7 +1297,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { for(int j = 0; j <= i; j++) { valueBuilder.append(subValues[j]); - if(j < i) + if (j < i) { valueBuilder.append(hierarchicalSidebarFacetConfiguration.getSplitter()); } @@ -1310,34 +1321,34 @@ public class SolrServiceImpl implements SearchService, IndexingService { { //Only add sort value once String type; - if(sortFields.get(field) != null) + if (sortFields.get(field) != null) { type = sortFields.get(field).getType(); - }else{ + } else { type = recentSubmissionsConfigurationMap.get(field).getType(); } - if(type.equals(DiscoveryConfigurationParameters.TYPE_DATE)) + if (type.equals(DiscoveryConfigurationParameters.TYPE_DATE)) { Date date = MultiFormatDateParser.parse(value); - if(date != null) + if (date != null) { doc.addField(field + "_dt", date); - }else{ + } else { log.warn("Error while indexing sort date field, item: " + item.getHandle() + " metadata field: " + field + " date value: " + date); } - }else{ + } else { doc.addField(field + "_sort", value); } sortFieldsAdded.add(field); } - if(hitHighlightingFields.contains(field) || hitHighlightingFields.contains("*") || hitHighlightingFields.contains(unqualifiedField + "." + Item.ANY)) + if (hitHighlightingFields.contains(field) || hitHighlightingFields.contains("*") || hitHighlightingFields.contains(unqualifiedField + "." + Item.ANY)) { doc.addField(field + "_hl", value); } - if(moreLikeThisFields.contains(field) || moreLikeThisFields.contains(unqualifiedField + "." + Item.ANY)) + if (moreLikeThisFields.contains(field) || moreLikeThisFields.contains(unqualifiedField + "." + Item.ANY)) { doc.addField(field + "_mlt", value); } @@ -1384,7 +1395,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { List values = itemService.getMetadataByMetadataString(item, "dc.relation.ispartof"); - if(values != null && values.size() > 0 && values.get(0) != null && values.get(0).getValue() != null) + if (values != null && values.size() > 0 && values.get(0) != null && values.get(0).getValue() != null) { // group on parent String handlePrefix = ConfigurationManager.getProperty("handle.canonical.prefix"); @@ -1434,7 +1445,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { streams.add(new BitstreamContentStream(context, myBitstream)); log.debug(" Added BitStream: " - + myBitstream.getStoreNumber() + " " + + myBitstream.getStoreNumber() + " " + myBitstream.getSequenceID() + " " + myBitstream.getName()); @@ -1472,10 +1483,15 @@ public class SolrServiceImpl implements SearchService, IndexingService { /** * Create Lucene document with all the shared fields initialized. * - * @param type Type of DSpace Object + * @param type + * Type of DSpace Object * @param id + * internal identifier * @param handle - * @param locations @return + * handle string + * @param locations + * list of collection/community internal identifiers + * @return initialized Lucene document */ protected SolrInputDocument buildDocument(int type, UUID id, String handle, List locations) @@ -1534,14 +1550,14 @@ public class SolrServiceImpl implements SearchService, IndexingService { // Choose the likely date formats based on string length switch (t.length()) { - // case from 1 to 3 go through adding anyone a single 0. Case 4 define - // for all the SimpleDateFormat - case 1: - t = "0" + t; - case 2: - t = "0" + t; - case 3: - t = "0" + t; + // case from 1 to 3 go through adding anyone a single 0. Case 4 define + // for all the SimpleDateFormat + case 1: + t = "0" + t; + case 2: + t = "0" + t; + case 3: + t = "0" + t; case 4: dfArr = new SimpleDateFormat[]{new SimpleDateFormat("yyyy")}; break; @@ -1589,7 +1605,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } public String locationToName(Context context, String field, String value) throws SQLException { - if("location.comm".equals(field) || "location.coll".equals(field)) + if ("location.comm".equals(field) || "location.coll".equals(field)) { int type = ("location.comm").equals(field) ? Constants.COMMUNITY : Constants.COLLECTION; DSpaceObject commColl = null; @@ -1597,7 +1613,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { { commColl = contentServiceFactory.getDSpaceObjectService(type).find(context, UUID.fromString(value)); } - if(commColl != null) + if (commColl != null) { return commColl.getName(); } @@ -1623,7 +1639,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { @Override public DiscoverResult search(Context context, DSpaceObject dso, DiscoverQuery discoveryQuery, boolean includeUnDiscoverable) throws SearchServiceException { - if(dso != null) + if (dso != null) { if (dso instanceof Community) { @@ -1644,7 +1660,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { @Override public DiscoverResult search(Context context, DiscoverQuery discoveryQuery, boolean includeUnDiscoverable) throws SearchServiceException { try { - if(getSolr() == null){ + if (getSolr() == null) { return new DiscoverResult(); } SolrQuery solrQuery = resolveToSolrQuery(context, discoveryQuery, includeUnDiscoverable); @@ -1664,10 +1680,10 @@ public class SolrServiceImpl implements SearchService, IndexingService { SolrQuery solrQuery = new SolrQuery(); String query = "*:*"; - if(discoveryQuery.getQuery() != null) + if (discoveryQuery.getQuery() != null) { - query = discoveryQuery.getQuery(); - } + query = discoveryQuery.getQuery(); + } solrQuery.setQuery(query); @@ -1682,7 +1698,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { solrQuery.addField(RESOURCE_TYPE_FIELD); solrQuery.addField(RESOURCE_ID_FIELD); - if(discoveryQuery.isSpellCheck()) + if (discoveryQuery.isSpellCheck()) { solrQuery.setParam(SpellingParams.SPELLCHECK_Q, query); solrQuery.setParam(SpellingParams.SPELLCHECK_COLLATE, Boolean.TRUE); @@ -1691,16 +1707,16 @@ public class SolrServiceImpl implements SearchService, IndexingService { if (!includeUnDiscoverable) { - solrQuery.addFilterQuery("NOT(withdrawn:true)"); - solrQuery.addFilterQuery("NOT(discoverable:false)"); - } + solrQuery.addFilterQuery("NOT(withdrawn:true)"); + solrQuery.addFilterQuery("NOT(discoverable:false)"); + } for (int i = 0; i < discoveryQuery.getFilterQueries().size(); i++) { String filterQuery = discoveryQuery.getFilterQueries().get(i); solrQuery.addFilterQuery(filterQuery); } - if(discoveryQuery.getDSpaceObjectFilter() != -1) + if (discoveryQuery.getDSpaceObjectFilter() != -1) { solrQuery.addFilterQuery(RESOURCE_TYPE_FIELD + ":" + discoveryQuery.getDSpaceObjectFilter()); } @@ -1711,20 +1727,20 @@ public class SolrServiceImpl implements SearchService, IndexingService { solrQuery.addFilterQuery(filterQuery + ":[* TO *]"); } - if(discoveryQuery.getStart() != -1) + if (discoveryQuery.getStart() != -1) { solrQuery.setStart(discoveryQuery.getStart()); } - if(discoveryQuery.getMaxResults() != -1) + if (discoveryQuery.getMaxResults() != -1) { solrQuery.setRows(discoveryQuery.getMaxResults()); } - if(discoveryQuery.getSortField() != null) + if (discoveryQuery.getSortField() != null) { SolrQuery.ORDER order = SolrQuery.ORDER.asc; - if(discoveryQuery.getSortOrder().equals(DiscoverQuery.SORT_ORDER.desc)) + if (discoveryQuery.getSortOrder().equals(DiscoverQuery.SORT_ORDER.desc)) order = SolrQuery.ORDER.desc; solrQuery.addSortField(discoveryQuery.getSortField(), order); @@ -1737,7 +1753,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } List facetFields = discoveryQuery.getFacetFields(); - if(0 < facetFields.size()) + if (0 < facetFields.size()) { //Only add facet information if there are any facets for (DiscoverFacetField facetFieldConfig : facetFields) @@ -1748,10 +1764,10 @@ public class SolrServiceImpl implements SearchService, IndexingService { // Setting the facet limit in this fashion ensures that each facet can have its own max solrQuery.add("f." + field + "." + FacetParams.FACET_LIMIT, String.valueOf(facetFieldConfig.getLimit())); String facetSort; - if(DiscoveryConfigurationParameters.SORT.COUNT.equals(facetFieldConfig.getSortOrder())) + if (DiscoveryConfigurationParameters.SORT.COUNT.equals(facetFieldConfig.getSortOrder())) { facetSort = FacetParams.FACET_SORT_COUNT; - }else{ + } else { facetSort = FacetParams.FACET_SORT_INDEX; } solrQuery.add("f." + field + "." + FacetParams.FACET_SORT, facetSort); @@ -1761,7 +1777,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { + FacetParams.FACET_OFFSET, String.valueOf(facetFieldConfig.getOffset())); } - if(facetFieldConfig.getPrefix() != null) + if (facetFieldConfig.getPrefix() != null) { solrQuery.setFacetPrefix(field, facetFieldConfig.getPrefix()); } @@ -1773,7 +1789,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { solrQuery.addFacetQuery(facetQuery); } - if(discoveryQuery.getFacetMinCount() != -1) + if (discoveryQuery.getFacetMinCount() != -1) { solrQuery.setFacetMinCount(discoveryQuery.getFacetMinCount()); } @@ -1781,7 +1797,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { solrQuery.setParam(FacetParams.FACET_OFFSET, String.valueOf(discoveryQuery.getFacetOffset())); } - if(0 < discoveryQuery.getHitHighlightingFields().size()) + if (0 < discoveryQuery.getHitHighlightingFields().size()) { solrQuery.setHighlight(true); solrQuery.add(HighlightParams.USE_PHRASE_HIGHLIGHTER, Boolean.TRUE.toString()); @@ -1805,7 +1821,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { @Override public InputStream searchJSON(Context context, DiscoverQuery query, DSpaceObject dso, String jsonIdentifier) throws SearchServiceException { - if(dso != null) + if (dso != null) { if (dso instanceof Community) { @@ -1824,7 +1840,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { @Override public InputStream searchJSON(Context context, DiscoverQuery discoveryQuery, String jsonIdentifier) throws SearchServiceException { - if(getSolr() == null) + if (getSolr() == null) { return null; } @@ -1854,7 +1870,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { protected DiscoverResult retrieveResult(Context context, DiscoverQuery query, QueryResponse solrQueryResponse) throws SQLException { DiscoverResult result = new DiscoverResult(); - if(solrQueryResponse != null) + if (solrQueryResponse != null) { result.setSearchTime(solrQueryResponse.getQTime()); result.setStart(query.getStart()); @@ -1866,7 +1882,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { { DSpaceObject dso = findDSpaceObject(context, doc); - if(dso != null) + if (dso != null) { result.addDSpaceObject(dso); } else { @@ -1887,10 +1903,10 @@ public class SolrServiceImpl implements SearchService, IndexingService { } result.addSearchDocument(dso, resultDoc); - if(solrQueryResponse.getHighlighting() != null) + if (solrQueryResponse.getHighlighting() != null) { Map> highlightedFields = solrQueryResponse.getHighlighting().get(dso.getType() + "-" + dso.getID()); - if(MapUtils.isNotEmpty(highlightedFields)) + if (MapUtils.isNotEmpty(highlightedFields)) { //We need to remove all the "_hl" appendix strings from our keys Map> resultMap = new HashMap>(); @@ -1906,7 +1922,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { //Resolve our facet field values List facetFields = solrQueryResponse.getFacetFields(); - if(facetFields != null) + if (facetFields != null) { for (int i = 0; i < facetFields.size(); i++) { @@ -1915,7 +1931,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { List facetValues = facetField.getValues(); if (facetValues != null) { - if(facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE) && facetFieldConfig.getSortOrder().equals(DiscoveryConfigurationParameters.SORT.VALUE)) + if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE) && facetFieldConfig.getSortOrder().equals(DiscoveryConfigurationParameters.SORT.VALUE)) { //If we have a date & are sorting by value, ensure that the results are flipped for a proper result Collections.reverse(facetValues); @@ -1942,11 +1958,11 @@ public class SolrServiceImpl implements SearchService, IndexingService { } } - if(solrQueryResponse.getFacetQuery() != null) + if (solrQueryResponse.getFacetQuery() != null) { - // just retrieve the facets in the order they where requested! - // also for the date we ask it in proper (reverse) order - // At the moment facet queries are only used for dates + // just retrieve the facets in the order they where requested! + // also for the date we ask it in proper (reverse) order + // At the moment facet queries are only used for dates LinkedHashMap sortedFacetQueries = new LinkedHashMap(solrQueryResponse.getFacetQuery()); for(String facetQuery : sortedFacetQueries.keySet()) { @@ -1967,17 +1983,17 @@ public class SolrServiceImpl implements SearchService, IndexingService { Integer count = sortedFacetQueries.get(facetQuery); //No need to show empty years - if(0 < count) + if (0 < count) { result.addFacetResult(facetField, new DiscoverResult.FacetResult(filter, name, null, name, count)); } } } - if(solrQueryResponse.getSpellCheckResponse() != null) + if (solrQueryResponse.getSpellCheckResponse() != null) { String recommendedQuery = solrQueryResponse.getSpellCheckResponse().getCollatedResult(); - if(StringUtils.isNotBlank(recommendedQuery)) + if (StringUtils.isNotBlank(recommendedQuery)) { result.setSpellCheckQuery(recommendedQuery); } @@ -1987,6 +2003,17 @@ public class SolrServiceImpl implements SearchService, IndexingService { return result; } + /** + * Find DSpace object by type and UUID or by handle from given Solr document + * + * @param context + * The relevant DSpace Context. + * @param doc + * the solr document + * @return DSpace object + * @throws SQLException + * An exception that provides information on a database access error or other errors. + */ protected DSpaceObject findDSpaceObject(Context context, SolrDocument doc) throws SQLException { Integer type = (Integer) doc.getFirstValue(RESOURCE_TYPE_FIELD); @@ -2005,9 +2032,17 @@ public class SolrServiceImpl implements SearchService, IndexingService { } - /** Simple means to return the search result as an InputStream */ + /** + * Simple means to return the search result as an InputStream + * + * @param query discovery query + * @return input stream + * @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 java.io.InputStream searchAsInputStream(DiscoverQuery query) throws SearchServiceException, java.io.IOException { - if(getSolr() == null) + if (getSolr() == null) { return null; } @@ -2038,7 +2073,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { { try { - if(getSolr() == null) + if (getSolr() == null) { return Collections.emptyList(); } @@ -2074,13 +2109,13 @@ public class SolrServiceImpl implements SearchService, IndexingService { } } return result; - } catch (Exception e) + } catch (Exception e) { - // Any acception that we get ignore it. - // We do NOT want any crashed to shown by the user + // Any acception that we get ignore it. + // We do NOT want any crashed to shown by the user log.error(LogManager.getHeader(context, "Error while quering solr", "Queyr: " + query), e); return new ArrayList(0); - } + } } @Override @@ -2088,10 +2123,10 @@ public class SolrServiceImpl implements SearchService, IndexingService { DiscoverFilterQuery result = new DiscoverFilterQuery(); StringBuilder filterQuery = new StringBuilder(); - if(StringUtils.isNotBlank(field) && StringUtils.isNotBlank(value)) + if (StringUtils.isNotBlank(field) && StringUtils.isNotBlank(value)) { filterQuery.append(field); - if("equals".equals(operator)) + if ("equals".equals(operator)) { //Query the keyword indexed field ! filterQuery.append("_keyword"); @@ -2108,28 +2143,28 @@ public class SolrServiceImpl implements SearchService, IndexingService { filterQuery.insert(0, "-"); } filterQuery.append(":"); - if("equals".equals(operator) || "notequals".equals(operator)) + if ("equals".equals(operator) || "notequals".equals(operator)) { //DO NOT ESCAPE RANGE QUERIES ! - if(!value.matches("\\[.*TO.*\\]")) + if (!value.matches("\\[.*TO.*\\]")) { value = ClientUtils.escapeQueryChars(value); filterQuery.append(value); } else { - if (value.matches("\\[\\d{1,4} TO \\d{1,4}\\]")) - { - int minRange = Integer.parseInt(value.substring(1, value.length()-1).split(" TO ")[0]); - int maxRange = Integer.parseInt(value.substring(1, value.length()-1).split(" TO ")[1]); - value = "["+String.format("%04d", minRange) + " TO "+ String.format("%04d", maxRange) + "]"; - } - filterQuery.append(value); + if (value.matches("\\[\\d{1,4} TO \\d{1,4}\\]")) + { + int minRange = Integer.parseInt(value.substring(1, value.length()-1).split(" TO ")[0]); + int maxRange = Integer.parseInt(value.substring(1, value.length()-1).split(" TO ")[1]); + value = "["+String.format("%04d", minRange) + " TO "+ String.format("%04d", maxRange) + "]"; + } + filterQuery.append(value); } } - else{ + else { //DO NOT ESCAPE RANGE QUERIES ! - if(!value.matches("\\[.*TO.*\\]")) + if (!value.matches("\\[.*TO.*\\]")) { value = ClientUtils.escapeQueryChars(value); filterQuery.append("(").append(value).append(")"); @@ -2176,13 +2211,13 @@ public class SolrServiceImpl implements SearchService, IndexingService { solrQuery.setParam(MoreLikeThisParams.DOC_COUNT, String.valueOf(mltConfig.getMax())); solrQuery.setParam(MoreLikeThisParams.MIN_WORD_LEN, String.valueOf(mltConfig.getMinWordLength())); - if(getSolr() == null) + if (getSolr() == null) { return Collections.emptyList(); } QueryResponse rsp = getSolr().query(solrQuery); NamedList mltResults = (NamedList) rsp.getResponse().get("moreLikeThis"); - if(mltResults != null && mltResults.get(item.getType() + "-" + item.getID()) != null) + if (mltResults != null && mltResults.get(item.getType() + "-" + item.getID()) != null) { SolrDocumentList relatedDocs = (SolrDocumentList) mltResults.get(item.getType() + "-" + item.getID()); for (Object relatedDoc : relatedDocs) @@ -2207,67 +2242,67 @@ public class SolrServiceImpl implements SearchService, IndexingService { @Override public String toSortFieldIndex(String metadataField, String type) { - if(type.equals(DiscoveryConfigurationParameters.TYPE_DATE)) + if (type.equals(DiscoveryConfigurationParameters.TYPE_DATE)) { return metadataField + "_dt"; - }else{ + } else { return metadataField + "_sort"; } } protected String transformFacetField(DiscoverFacetField facetFieldConfig, String field, boolean removePostfix) { - if(facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_TEXT)) + if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_TEXT)) { - if(removePostfix) + if (removePostfix) { return field.substring(0, field.lastIndexOf("_filter")); - }else{ + } else { return field + "_filter"; } - }else if(facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) + } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) { - if(removePostfix) + if (removePostfix) { return field.substring(0, field.lastIndexOf(".year")); - }else{ + } else { return field + ".year"; } - }else if(facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_AC)) + } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_AC)) { - if(removePostfix) + if (removePostfix) { return field.substring(0, field.lastIndexOf("_ac")); - }else{ + } else { return field + "_ac"; } - }else if(facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_HIERARCHICAL)) + } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_HIERARCHICAL)) { - if(removePostfix) + if (removePostfix) { return StringUtils.substringBeforeLast(field, "_tax_"); - }else{ + } else { //Only display top level filters ! return field + "_tax_0_filter"; } - }else if(facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_AUTHORITY)) + } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_AUTHORITY)) { - if(removePostfix) + if (removePostfix) { return field.substring(0, field.lastIndexOf("_acid")); - }else{ + } else { return field + "_acid"; } - }else if(facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_STANDARD)) + } else if (facetFieldConfig.getType().equals(DiscoveryConfigurationParameters.TYPE_STANDARD)) { return field; - }else{ + } else { return field; } } protected String transformDisplayedValue(Context context, String field, String value) throws SQLException { - if(field.equals("location.comm") || field.equals("location.coll")) + if (field.equals("location.comm") || field.equals("location.coll")) { value = locationToName(context, field, value); } @@ -2276,7 +2311,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { { //We have a filter make sure we split ! String separator = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("discovery.solr.facets.split.char"); - if(separator == null) + if (separator == null) { separator = FILTER_SEPARATOR; } @@ -2291,7 +2326,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { valueBuffer.append(split[0]); } value = valueBuffer.toString(); - }else if(value.matches("\\((.*?)\\)")) + } else if (value.matches("\\((.*?)\\)")) { //The brackets where added for better solr results, remove the first & last one value = value.substring(1, value.length() -1); @@ -2300,16 +2335,16 @@ public class SolrServiceImpl implements SearchService, IndexingService { } protected String transformAuthorityValue(Context context, String field, String value) throws SQLException { - if(field.equals("location.comm") || field.equals("location.coll")) - { + if (field.equals("location.comm") || field.equals("location.coll")) + { return value; - } - if (field.endsWith("_filter") || field.endsWith("_ac") + } + if (field.endsWith("_filter") || field.endsWith("_ac") || field.endsWith("_acid")) { //We have a filter make sure we split ! String separator = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("discovery.solr.facets.split.char"); - if(separator == null) + if (separator == null) { separator = FILTER_SEPARATOR; } @@ -2335,7 +2370,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { } protected String transformSortValue(Context context, String field, String value) throws SQLException { - if(field.equals("location.comm") || field.equals("location.coll")) + if (field.equals("location.comm") || field.equals("location.coll")) { value = locationToName(context, field, value); } @@ -2344,7 +2379,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { { //We have a filter make sure we split ! String separator = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("discovery.solr.facets.split.char"); - if(separator == null) + if (separator == null) { separator = FILTER_SEPARATOR; } @@ -2358,7 +2393,7 @@ public class SolrServiceImpl implements SearchService, IndexingService { valueBuffer.append(fqParts[i]); } value = valueBuffer.toString(); - }else if(value.matches("\\((.*?)\\)")) + } else if (value.matches("\\((.*?)\\)")) { //The brackets where added for better solr results, remove the first & last one value = value.substring(1, value.length() -1); @@ -2366,27 +2401,27 @@ public class SolrServiceImpl implements SearchService, IndexingService { return value; } - @Override - public void indexContent(Context context, DSpaceObject dso, boolean force, - boolean commit) throws SearchServiceException, SQLException { - indexContent(context, dso, force); - if (commit) - { - commit(); - } - } + @Override + public void indexContent(Context context, DSpaceObject dso, boolean force, + boolean commit) throws SearchServiceException, SQLException { + indexContent(context, dso, force); + if (commit) + { + commit(); + } + } - @Override - public void commit() throws SearchServiceException { - try { - if(getSolr() != null) + @Override + public void commit() throws SearchServiceException { + try { + if (getSolr() != null) { getSolr().commit(); } - } catch (Exception e) { - throw new SearchServiceException(e.getMessage(), e); - } - } + } catch (Exception e) { + throw new SearchServiceException(e.getMessage(), e); + } + } @Override public String escapeQueryChars(String query) { diff --git a/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoveryHitHighlightFieldConfiguration.java b/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoveryHitHighlightFieldConfiguration.java index d7cd1cd213..81b79b4bfe 100644 --- a/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoveryHitHighlightFieldConfiguration.java +++ b/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoveryHitHighlightFieldConfiguration.java @@ -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() { diff --git a/dspace-api/src/main/java/org/dspace/embargo/EmbargoCLITool.java b/dspace-api/src/main/java/org/dspace/embargo/EmbargoCLITool.java index cc21a383c8..2778bc7d24 100644 --- a/dspace-api/src/main/java/org/dspace/embargo/EmbargoCLITool.java +++ b/dspace-api/src/main/java/org/dspace/embargo/EmbargoCLITool.java @@ -62,10 +62,11 @@ public class EmbargoCLITool { *

    -q,--quiet
    *
    No output except upon error.
    * + * + * @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; } } diff --git a/dspace-api/src/main/java/org/dspace/embargo/EmbargoLifter.java b/dspace-api/src/main/java/org/dspace/embargo/EmbargoLifter.java index 080581d821..71ec1763bb 100644 --- a/dspace-api/src/main/java/org/dspace/embargo/EmbargoLifter.java +++ b/dspace-api/src/main/java/org/dspace/embargo/EmbargoLifter.java @@ -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; diff --git a/dspace-api/src/main/java/org/dspace/embargo/EmbargoServiceImpl.java b/dspace-api/src/main/java/org/dspace/embargo/EmbargoServiceImpl.java index f8c90b9dcf..87c13a6bfe 100644 --- a/dspace-api/src/main/java/org/dspace/embargo/EmbargoServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/embargo/EmbargoServiceImpl.java @@ -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 { diff --git a/dspace-api/src/main/java/org/dspace/embargo/EmbargoSetter.java b/dspace-api/src/main/java/org/dspace/embargo/EmbargoSetter.java index c0fc0ec368..08de5349c2 100644 --- a/dspace-api/src/main/java/org/dspace/embargo/EmbargoSetter.java +++ b/dspace-api/src/main/java/org/dspace/embargo/EmbargoSetter.java @@ -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; diff --git a/dspace-api/src/main/java/org/dspace/embargo/service/EmbargoService.java b/dspace-api/src/main/java/org/dspace/embargo/service/EmbargoService.java index 44c81a152a..c5e5f37d32 100644 --- a/dspace-api/src/main/java/org/dspace/embargo/service/EmbargoService.java +++ b/dspace-api/src/main/java/org/dspace/embargo/service/EmbargoService.java @@ -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; diff --git a/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java b/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java index b6f306487f..4a11f1e7ca 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java @@ -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 true, 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); } } -} \ No newline at end of file +} diff --git a/dspace-api/src/main/java/org/dspace/eperson/EPerson.java b/dspace-api/src/main/java/org/dspace/eperson/EPerson.java index 0bd0b2aca6..1adc4a380f 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/EPerson.java +++ b/dspace-api/src/main/java/org/dspace/eperson/EPerson.java @@ -104,8 +104,8 @@ public class EPerson extends DSpaceObject implements DSpaceObjectLegacySupport /** * Return true if this object equals obj, false otherwise. * - * @param obj - * @return true if ResourcePolicy objects are equal + * @param obj another EPerson. + * @return true if EPerson objects are equal in ID, email, and full name */ @Override public boolean equals(Object obj) @@ -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() diff --git a/dspace-api/src/main/java/org/dspace/eperson/EPersonCLITool.java b/dspace-api/src/main/java/org/dspace/eperson/EPersonCLITool.java index 1d70b6e51a..1c86e0aa33 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/EPersonCLITool.java +++ b/dspace-api/src/main/java/org/dspace/eperson/EPersonCLITool.java @@ -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. + * @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 { diff --git a/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java b/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java index f5c6cced62..9e9b7fbd47 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java +++ b/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java @@ -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) diff --git a/dspace-api/src/main/java/org/dspace/eperson/Groomer.java b/dspace-api/src/main/java/org/dspace/eperson/Groomer.java index a573ecc027..9a4ae42130 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/Groomer.java +++ b/dspace-api/src/main/java/org/dspace/eperson/Groomer.java @@ -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 diff --git a/dspace-api/src/main/java/org/dspace/eperson/Group.java b/dspace-api/src/main/java/org/dspace/eperson/Group.java index 1e7babdaf6..c8c2539fcd 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/Group.java +++ b/dspace-api/src/main/java/org/dspace/eperson/Group.java @@ -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 getMembers() { @@ -146,6 +148,8 @@ public class Group extends DSpaceObject implements DSpaceObjectLegacySupport /** * Return Group members of a Group. + * + * @return list of groups */ public List getMemberGroups() { diff --git a/dspace-api/src/main/java/org/dspace/eperson/GroupServiceImpl.java b/dspace-api/src/main/java/org/dspace/eperson/GroupServiceImpl.java index aeebd5e0e5..2a56b03600 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/GroupServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/eperson/GroupServiceImpl.java @@ -167,16 +167,16 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl 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 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 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 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 implements @Override @Deprecated public List 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 implements @Override public List findAll(Context context, List 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 implements { List 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 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 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 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 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 getEmptyGroups(Context context) throws SQLException { return groupDAO.getEmptyGroups(context); @@ -434,6 +443,16 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl 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 implements group.clearDetails(); } - if(group.isGroupsChanged()) + if (group.isGroupsChanged()) { rethinkGroupCache(context, true); group.clearGroupsChanged(); @@ -473,6 +492,12 @@ public class GroupServiceImpl extends DSpaceObjectServiceImpl 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 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 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 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)); } diff --git a/dspace-api/src/main/java/org/dspace/eperson/SubscribeCLITool.java b/dspace-api/src/main/java/org/dspace/eperson/SubscribeCLITool.java index 28bf66e707..8e1f0ea682 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/SubscribeCLITool.java +++ b/dspace-api/src/main/java/org/dspace/eperson/SubscribeCLITool.java @@ -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 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."; diff --git a/dspace-api/src/main/java/org/dspace/eperson/service/EPersonService.java b/dspace-api/src/main/java/org/dspace/eperson/service/EPersonService.java index eb1679092d..25c95efdff 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/service/EPersonService.java +++ b/dspace-api/src/main/java/org/dspace/eperson/service/EPersonService.java @@ -45,7 +45,13 @@ public interface EPersonService extends DSpaceObjectService, 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, 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 null + * @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, 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 search(Context context, String query) throws SQLException; @@ -82,15 +92,17 @@ public interface EPersonService extends DSpaceObjectService, 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 search(Context context, String query, int offset, int limit) throws SQLException; @@ -100,11 +112,13 @@ public interface EPersonService extends DSpaceObjectService, 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, DSpaceObje *
  • NETID
  • *
* + * @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 findAll(Context context, int sortField) throws SQLException; @@ -127,7 +147,13 @@ public interface EPersonService extends DSpaceObjectService, 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, 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, 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 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 findNotActiveSince(Context context, Date date) throws SQLException; /** @@ -196,13 +251,48 @@ public interface EPersonService extends DSpaceObjectService, 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 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 findByGroups(Context c, Set 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 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; } diff --git a/dspace-api/src/main/java/org/dspace/eperson/service/GroupService.java b/dspace-api/src/main/java/org/dspace/eperson/service/GroupService.java index 892bd8be32..25af68efa4 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/service/GroupService.java +++ b/dspace-api/src/main/java/org/dspace/eperson/service/GroupService.java @@ -160,9 +160,9 @@ public interface GroupService extends DSpaceObjectService, DSpaceObjectLe * specified group, etc. * * @param context - * DSpace context + * The relevant DSpace Context. * @param group - * Group object + * Group object * @return List of EPerson objects * @throws SQLException if error */ @@ -172,7 +172,9 @@ public interface GroupService extends DSpaceObjectService, DSpaceObjectLe * Find the group by its name - assumes name is unique * * @param context + * The relevant DSpace Context. * @param name + * Group name to search for * * @return the named Group, or null if not found * @throws SQLException if error @@ -183,9 +185,9 @@ public interface GroupService extends DSpaceObjectService, DSpaceObjectLe * Finds all groups in the site * * @param context - * DSpace context + * The relevant DSpace Context. * @param metadataSortFields - * metadata fields to sort by, leave empty to sort by Name + * metadata fields to sort by, leave empty to sort by Name * * @return List of all groups in the site * @throws SQLException if error @@ -256,7 +258,7 @@ public interface GroupService extends DSpaceObjectService, DSpaceObjectLe public boolean isEmpty(Group group); /** - * Initializes the group names for anonymous & administrator, and marks them + * Initializes the group names for anonymous and administrator, and marks them * "permanent". * * @param context the DSpace context @@ -282,7 +284,9 @@ public interface GroupService extends DSpaceObjectService, DSpaceObjectLe int countTotal(Context context) throws SQLException; /** - * Look up groups based on their value for a certain metadata field (NOTE: name is not stored as metadata) + * Look up groups based on their value for a certain metadata field + * (NOTE: name is not stored as metadata) + * * @param context The DSpace context * @param searchValue The value to match * @param metadataField The metadata field to search in diff --git a/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java b/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java index 2f776c353b..125d8cd008 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java +++ b/dspace-api/src/main/java/org/dspace/eperson/service/SubscribeService.java @@ -25,6 +25,16 @@ import java.util.List; */ public interface SubscribeService { + /** + * Subscribe an e-person to a collection. An e-mail will be sent every day a + * new item appears in the collection. + * + * @param context + * DSpace context + * @return list of Subscription objects + * @throws SQLException + * An exception that provides information on a database access error or other errors. + */ public List findAll(Context context) throws SQLException; /** @@ -37,6 +47,11 @@ public interface SubscribeService { * EPerson to subscribe * @param collection * Collection to subscribe to + * @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 subscribe(Context context, EPerson eperson, Collection collection) throws SQLException, AuthorizeException; @@ -52,6 +67,11 @@ public interface SubscribeService { * EPerson to unsubscribe * @param collection * Collection to unsubscribe from + * @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 unsubscribe(Context context, EPerson eperson, Collection collection) throws SQLException, AuthorizeException; @@ -64,6 +84,8 @@ public interface SubscribeService { * @param eperson * EPerson * @return array of collections e-person is subscribed to + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List getSubscriptions(Context context, EPerson eperson) throws SQLException; @@ -73,6 +95,8 @@ public interface SubscribeService { * @param context * DSpace context * @return array of collections the currently logged in e-person can subscribe to + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List getAvailableSubscriptions(Context context) throws SQLException; @@ -85,6 +109,8 @@ public interface SubscribeService { * @param eperson * EPerson * @return array of collections e-person can subscribe to + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List getAvailableSubscriptions(Context context, EPerson eperson) throws SQLException; @@ -99,11 +125,33 @@ public interface SubscribeService { * @param collection * find out if subscribed to this collection * @return true if they are subscribed + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public boolean isSubscribed(Context context, EPerson eperson, Collection collection) throws SQLException; + /** + * Delete subscription by collection. + * + * @param context + * DSpace context + * @param collection + * find out if subscribed to this collection + * @throws SQLException + * An exception that provides information on a database access error or other errors. + */ public void deleteByCollection(Context context, Collection collection) throws SQLException; + /** + * Delete subscription by eperson (subscriber). + * + * @param context + * DSpace context + * @param ePerson + * find out if this e-person is subscribed + * @throws SQLException + * An exception that provides information on a database access error or other errors. + */ public void deleteByEPerson(Context context, EPerson ePerson) throws SQLException; } diff --git a/dspace-api/src/main/java/org/dspace/eperson/service/SupervisorService.java b/dspace-api/src/main/java/org/dspace/eperson/service/SupervisorService.java index 14b1d47050..8a20c19fa0 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/service/SupervisorService.java +++ b/dspace-api/src/main/java/org/dspace/eperson/service/SupervisorService.java @@ -42,6 +42,8 @@ public interface SupervisorService { * @param group the group to be doing the supervising * * @return boolean true if there is an order that matches, false if not + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public boolean isOrder(Context context, WorkspaceItem workspaceItem, Group group) throws SQLException; @@ -54,6 +56,11 @@ public interface SupervisorService { * @param context the context this object exists in * @param workspaceItem the ID of the workspace item * @param group the ID of the group to be removed from the item + * @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 remove(Context context, WorkspaceItem workspaceItem, Group group) throws SQLException, AuthorizeException; @@ -65,6 +72,11 @@ public interface SupervisorService { * @param group the ID of the group which will supervise * @param workspaceItem the ID of the workspace item to be supervised * @param policy String containing the policy type to be used + * @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 add(Context context, Group group, WorkspaceItem workspaceItem, int policy) throws SQLException, AuthorizeException; diff --git a/dspace-api/src/main/java/org/dspace/event/Consumer.java b/dspace-api/src/main/java/org/dspace/event/Consumer.java index 2e628180aa..86ca537eef 100644 --- a/dspace-api/src/main/java/org/dspace/event/Consumer.java +++ b/dspace-api/src/main/java/org/dspace/event/Consumer.java @@ -26,6 +26,8 @@ public interface Consumer * initializing any pooled JMS resources. Called ONCE when created by the * dispatcher pool. This should be used to set up expensive resources that * will remain for the lifetime of the consumer. + * + * @throws Exception if error */ public void initialize() throws Exception; @@ -37,21 +39,29 @@ public interface Consumer * * @param ctx * the execution context object - * * @param event * the content event + * @throws Exception if error */ public void consume(Context ctx, Event event) throws Exception; /** * Signal that there are no more events queued in this event stream and * event processing for the preceding consume calls should be finished up. + * + * @param ctx + * the execution context object + * @throws Exception if error */ public void end(Context ctx) throws Exception; /** * Finish - free any allocated resources. Called when consumer (via it's * parent dispatcher) is going to be destroyed by the dispatcher pool. + * + * @param ctx + * the execution context object + * @throws Exception if error */ public void finish(Context ctx) throws Exception; diff --git a/dspace-api/src/main/java/org/dspace/event/ConsumerProfile.java b/dspace-api/src/main/java/org/dspace/event/ConsumerProfile.java index 58f0950906..af012cc6c7 100644 --- a/dspace-api/src/main/java/org/dspace/event/ConsumerProfile.java +++ b/dspace-api/src/main/java/org/dspace/event/ConsumerProfile.java @@ -15,8 +15,7 @@ import org.dspace.core.ConfigurationManager; /** * An instance of this class contains the configuration profile of a specific, - * named Consumer, in the context of a specific - * Dispatcher. This + * named Consumer, in the context of a specific Dispatcher. This * includes the name, the class to instantiate and event filters. Note that all * characteristics are "global" and the same for all dispatchers. * @@ -53,20 +52,38 @@ public class ConsumerProfile * @param name * configuration name of the consumer profile * @return a new ConsumerProfile; never null. + * @throws IllegalArgumentException if no class or no filters configured for the specified consumer + * @throws ClassNotFoundException passed through. + * + * @throws InstantiationException passed through. + * + * @throws IllegalAccessException passed through. + * */ public static ConsumerProfile makeConsumerProfile(String name) - throws IllegalArgumentException, ClassNotFoundException, - InstantiationException, IllegalAccessException + throws IllegalArgumentException, ClassNotFoundException, + InstantiationException, IllegalAccessException { ConsumerProfile result = new ConsumerProfile(name); result.readConfiguration(); return result; } - // Get class and filters from DSpace Configuration. - private void readConfiguration() throws IllegalArgumentException, - ClassNotFoundException, InstantiationException, - IllegalAccessException + /** + * Get class and filters from DSpace Configuration. + * + * @throws IllegalArgumentException if no class or no filters configured for the specified consumer + * @throws ClassNotFoundException passed through. + * + * @throws InstantiationException passed through. + * + * @throws IllegalAccessException passed through. + * + */ + + private void readConfiguration() + throws IllegalArgumentException, ClassNotFoundException, + InstantiationException, IllegalAccessException { String className = ConfigurationManager.getProperty(CONSUMER_PREFIX + name + ".class"); @@ -94,12 +111,11 @@ public class ConsumerProfile String fpart[] = part[j].split("\\+"); if (fpart.length != 2) { - log - .error("Bad Filter clause in consumer stanza in Configuration entry for " - + CONSUMER_PREFIX - + name - + ".consumers: " - + part[j]); + log.error("Bad Filter clause in consumer stanza in Configuration entry for " + + CONSUMER_PREFIX + + name + + ".consumers: " + + part[j]); } else { @@ -112,11 +128,10 @@ public class ConsumerProfile int ot = Event.parseObjectType(objectNames[k]); if (ot == 0) { - log - .error("Bad ObjectType in Consumer Stanza in Configuration entry for " - + CONSUMER_PREFIX - + name - + ".consumers: " + objectNames[k]); + log.error("Bad ObjectType in Consumer Stanza in Configuration entry for " + + CONSUMER_PREFIX + + name + + ".consumers: " + objectNames[k]); } else { @@ -129,11 +144,10 @@ public class ConsumerProfile int et = Event.parseEventType(eventNames[k]); if (et == 0) { - log - .error("Bad EventType in Consumer Stanza in Configuration entry for " - + CONSUMER_PREFIX - + name - + ".consumers: " + eventNames[k]); + log.error("Bad EventType in Consumer Stanza in Configuration entry for " + + CONSUMER_PREFIX + + name + + ".consumers: " + eventNames[k]); } else { diff --git a/dspace-api/src/main/java/org/dspace/event/Event.java b/dspace-api/src/main/java/org/dspace/event/Event.java index b042950ac3..d3ab5af28f 100644 --- a/dspace-api/src/main/java/org/dspace/event/Event.java +++ b/dspace-api/src/main/java/org/dspace/event/Event.java @@ -373,7 +373,11 @@ public class Event implements Serializable /** * Get the DSpace object which is the "object" of an event. * + * @param context + * The relevant DSpace Context. * @return DSpaceObject or null if none can be found or no object was set. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public DSpaceObject getObject(Context context) throws SQLException { @@ -393,7 +397,11 @@ public class Event implements Serializable * Syntactic sugar to get the DSpace object which is the "subject" of an * event. * + * @param context + * The relevant DSpace Context. * @return DSpaceObject or null if none can be found. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public DSpaceObject getSubject(Context context) throws SQLException { @@ -671,11 +679,12 @@ public class Event implements Serializable } /** - * Keeps track of which consumers the event has been consumed by. Should be + * Keeps track of which consumers have consumed the event. Should be * called by a dispatcher when calling consume(Context ctx, String name, * Event event) on an event. * * @param consumerName + * name of consumer which has consumed the event */ public void setBitSet(String consumerName) { diff --git a/dspace-api/src/main/java/org/dspace/event/service/EventService.java b/dspace-api/src/main/java/org/dspace/event/service/EventService.java index cdbe58137e..5c032c3f74 100644 --- a/dspace-api/src/main/java/org/dspace/event/service/EventService.java +++ b/dspace-api/src/main/java/org/dspace/event/service/EventService.java @@ -25,6 +25,9 @@ public interface EventService { /** * Get dispatcher for configuration named by "name". Returns cached instance * if one exists. + * + * @param name dispatcher name + * @return chached instance of dispatcher */ public Dispatcher getDispatcher(String name); diff --git a/dspace-api/src/main/java/org/dspace/handle/HandlePlugin.java b/dspace-api/src/main/java/org/dspace/handle/HandlePlugin.java index 57401f51bb..06e984514b 100644 --- a/dspace-api/src/main/java/org/dspace/handle/HandlePlugin.java +++ b/dspace-api/src/main/java/org/dspace/handle/HandlePlugin.java @@ -257,7 +257,7 @@ public class HandlePlugin implements HandleStorage * ignored * @return A byte array with the raw data for this handle. Currently, this * consists of a single URL value. - * @exception HandleException + * @throws HandleException * If an error occurs while calling the Handle API. */ @Override @@ -354,7 +354,7 @@ public class HandlePlugin implements HandleStorage * @param theHandle * byte array representation of handle * @return True if we have this handle in storage - * @exception HandleException + * @throws HandleException * If an error occurs while calling the Handle API. */ @Override @@ -410,7 +410,7 @@ public class HandlePlugin implements HandleStorage * byte array representation of naming authority handle * @return All handles in local storage which start with the naming * authority handle. - * @exception HandleException + * @throws HandleException * If an error occurs while calling the Handle API. */ @Override diff --git a/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java b/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java index 8d2b0cb101..474f88d003 100644 --- a/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java @@ -167,10 +167,10 @@ public class HandleServiceImpl implements HandleService { //Check if the supplied handle is already in use -- cannot use the same handle twice Handle handle = findHandleInternal(context, suppliedHandle); - if(handle!=null && handle.getDSpaceObject() != null) + if (handle != null && handle.getDSpaceObject() != null) { //Check if this handle is already linked up to this specified DSpace Object - if(handle.getDSpaceObject().getID().equals(dso.getID())) + if (handle.getDSpaceObject().getID().equals(dso.getID())) { //This handle already links to this DSpace Object -- so, there's nothing else we need to do return suppliedHandle; @@ -181,7 +181,7 @@ public class HandleServiceImpl implements HandleService throw new IllegalStateException("Attempted to create a handle which is already in use: " + suppliedHandle); } } - else if(handle!=null && handle.getResourceTypeId() != null) + else if (handle!=null && handle.getResourceTypeId() != null) { //If there is a 'resource_type_id' (but 'resource_id' is empty), then the object using // this handle was previously unbound (see unbindHandle() method) -- likely because object was deleted @@ -189,14 +189,14 @@ public class HandleServiceImpl implements HandleService //Since we are restoring an object to a pre-existing handle, double check we are restoring the same *type* of object // (e.g. we will not allow an Item to be restored to a handle previously used by a Collection) - if(previousType != dso.getType()) + if (previousType != dso.getType()) { throw new IllegalStateException("Attempted to reuse a handle previously used by a " + Constants.typeText[previousType] + " for a new " + Constants.typeText[dso.getType()]); } } - else if(handle==null) //if handle not found, create it + else if (handle==null) //if handle not found, create it { //handle not found in DB table -- create a new table entry handle = handleDAO.create(context, new Handle()); @@ -233,7 +233,7 @@ public class HandleServiceImpl implements HandleService handle.setDSpaceObject(null); handleDAO.save(context, handle); - if(log.isDebugEnabled()) + if (log.isDebugEnabled()) { log.debug("Unbound Handle " + handle.getHandle() + " from object " + Constants.typeText[dso.getType()] + " id=" + dso.getID()); } @@ -281,7 +281,7 @@ public class HandleServiceImpl implements HandleService { //Ensure that the handle doesn't look like this 12346/213.{version} //If we find a match that indicates that we have a proper handle - if(!handle.getHandle().matches(".*/.*\\.\\d+")) + if (!handle.getHandle().matches(".*/.*\\.\\d+")) { result = handle.getHandle(); } @@ -328,7 +328,7 @@ public class HandleServiceImpl implements HandleService @Override public void modifyHandleDSpaceObject(Context context, String handle, DSpaceObject newOwner) throws SQLException { Handle dbHandle = findHandleInternal(context, handle); - if(dbHandle != null) + if (dbHandle != null) { // Check if we have to remove the handle from the current handle list // or if object is alreday deleted. @@ -358,7 +358,7 @@ public class HandleServiceImpl implements HandleService * @param dso * DSpaceObject for which we require our handles * @return The handle for object, or null if the object has no handle. - * @exception SQLException + * @throws SQLException * If a database error occurs */ protected List getInternalHandles(Context context, DSpaceObject dso) @@ -375,7 +375,7 @@ public class HandleServiceImpl implements HandleService * @param handle * The handle to resolve * @return The database row corresponding to the handle - * @exception SQLException + * @throws SQLException * If a database error occurs */ protected Handle findHandleInternal(Context context, String handle) @@ -394,7 +394,7 @@ public class HandleServiceImpl implements HandleService * * @param context DSpace Context * @return A new handle id - * @exception SQLException + * @throws SQLException * If a database error occurs */ protected String createId(Context context) throws SQLException diff --git a/dspace-api/src/main/java/org/dspace/handle/UpdateHandlePrefix.java b/dspace-api/src/main/java/org/dspace/handle/UpdateHandlePrefix.java index ea2af63015..bfc7e8852d 100644 --- a/dspace-api/src/main/java/org/dspace/handle/UpdateHandlePrefix.java +++ b/dspace-api/src/main/java/org/dspace/handle/UpdateHandlePrefix.java @@ -37,7 +37,7 @@ public class UpdateHandlePrefix * When invoked as a command-line tool, updates handle prefix * * @param args the command-line arguments, none used - * @throws java.lang.Exception + * @throws Exception on generic exception * */ public static void main(String[] args) throws Exception @@ -81,7 +81,7 @@ public class UpdateHandlePrefix if (choiceString.equalsIgnoreCase("y")) { - context.turnOffAuthorisationSystem(); + context.turnOffAuthorisationSystem(); try { log.info("Updating handle prefix from " + oldH + " to " + newH); @@ -97,7 +97,7 @@ public class UpdateHandlePrefix List metadataValues = metadataValueService.findByValueLike(context, "http://hdl.handle.net/"); int updMeta = metadataValues.size(); for (MetadataValue metadataValue : metadataValues) { - metadataValue.setValue(metadataValue.getValue().replace("http://hdl.handle.net/" + oldH, "http://hdl.handle.net/" + newH)); + metadataValue.setValue(metadataValue.getValue().replace("http://hdl.handle.net/" + oldH, "http://hdl.handle.net/" + newH)); metadataValueService.update(context, metadataValue, true); } System.out.println( @@ -160,4 +160,4 @@ public class UpdateHandlePrefix } } } -} \ No newline at end of file +} diff --git a/dspace-api/src/main/java/org/dspace/handle/service/HandleService.java b/dspace-api/src/main/java/org/dspace/handle/service/HandleService.java index 369c00a695..c1780eadbe 100644 --- a/dspace-api/src/main/java/org/dspace/handle/service/HandleService.java +++ b/dspace-api/src/main/java/org/dspace/handle/service/HandleService.java @@ -39,7 +39,7 @@ public interface HandleService { * @param handle * The handle * @return The local URL - * @exception SQLException + * @throws SQLException * If a database error occurs */ public String resolveToURL(Context context, String handle) @@ -77,7 +77,7 @@ public interface HandleService { * @param dso * The DSpaceObject to create a handle for * @return The newly created handle - * @exception SQLException + * @throws SQLException * If a database error occurs */ public String createHandle(Context context, DSpaceObject dso) @@ -94,6 +94,8 @@ public interface HandleService { * @param suppliedHandle * existing handle value * @return the Handle + * @throws SQLException + * An exception that provides information on a database access error or other errors. * @throws IllegalStateException if specified handle is already in use by another object */ public String createHandle(Context context, DSpaceObject dso, String suppliedHandle) @@ -109,7 +111,11 @@ public interface HandleService { * DSpaceObject * @param suppliedHandle * existing handle value + * @param force + * FIXME: currently unused * @return the Handle + * @throws SQLException + * An exception that provides information on a database access error or other errors. * @throws IllegalStateException if specified handle is already in use by another object */ public String createHandle(Context context, DSpaceObject dso, String suppliedHandle, boolean force) @@ -122,6 +128,8 @@ public interface HandleService { * * @param context DSpace context * @param dso DSpaceObject whose Handle to unbind. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public void unbindHandle(Context context, DSpaceObject dso) throws SQLException; @@ -136,9 +144,9 @@ public interface HandleService { * The handle to resolve * @return The object which handle maps to, or null if handle is not mapped * to any object. - * @exception IllegalStateException + * @throws IllegalStateException * If handle was found but is not bound to an object - * @exception SQLException + * @throws SQLException * If a database error occurs */ public DSpaceObject resolveToObject(Context context, String handle) @@ -153,7 +161,7 @@ public interface HandleService { * @param dso * The object to obtain a handle for * @return The handle for object, or null if the object has no handle. - * @exception SQLException + * @throws SQLException * If a database error occurs */ public String findHandle(Context context, DSpaceObject dso) @@ -168,7 +176,7 @@ public interface HandleService { * The handle prefix * @return A list of the handles starting with prefix. The list is * guaranteed to be non-null. Each element of the list is a String. - * @exception SQLException + * @throws SQLException * If a database error occurs */ public List getHandlesForPrefix(Context context, String prefix) diff --git a/dspace-api/src/main/java/org/dspace/harvest/HarvestConsumer.java b/dspace-api/src/main/java/org/dspace/harvest/HarvestConsumer.java index 0585d4cac0..8d075f09dc 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/HarvestConsumer.java +++ b/dspace-api/src/main/java/org/dspace/harvest/HarvestConsumer.java @@ -33,8 +33,8 @@ public class HarvestConsumer implements Consumer /** log4j logger */ private static Logger log = Logger.getLogger(HarvestConsumer.class); - protected HarvestedCollectionService harvestedCollectionService; - protected HarvestedItemService harvestedItemService; + protected HarvestedCollectionService harvestedCollectionService; + protected HarvestedItemService harvestedItemService; /** * Initialise the consumer @@ -42,69 +42,72 @@ public class HarvestConsumer implements Consumer * @throws Exception if error */ @Override - public void initialize() + public void initialize() throws Exception { - harvestedItemService = HarvestServiceFactory.getInstance().getHarvestedItemService(); + harvestedItemService = HarvestServiceFactory.getInstance().getHarvestedItemService(); } /** * Consume the event * * @param context + * The relevant DSpace Context. * @param event + * DSpace event * @throws Exception if error */ @Override - public void consume(Context context, Event event) + public void consume(Context context, Event event) throws Exception { - int st = event.getSubjectType(); - int et = event.getEventType(); - UUID id = event.getSubjectID(); - - switch (st) - { - case Constants.ITEM: - if (et == Event.DELETE) - { - HarvestedItem hi = harvestedItemService.find(context, (Item) event.getSubject(context)); - if (hi != null) { - log.debug("Deleted item '" + id + "', also deleting associated harvested_item '" + hi.getOaiID() + "'."); - harvestedItemService.delete(context, hi); - } - else + int st = event.getSubjectType(); + int et = event.getEventType(); + UUID id = event.getSubjectID(); + + switch (st) + { + case Constants.ITEM: + if (et == Event.DELETE) + { + HarvestedItem hi = harvestedItemService.find(context, (Item) event.getSubject(context)); + if (hi != null) { + log.debug("Deleted item '" + id + "', also deleting associated harvested_item '" + hi.getOaiID() + "'."); + harvestedItemService.delete(context, hi); + } + else { log.debug("Deleted item '" + id + "' and the associated harvested_item."); } - } - break; - case Constants.COLLECTION: - if (et == Event.DELETE) - { - HarvestedCollection hc = harvestedCollectionService.find(context, (Collection) event.getSubject(context)); - if (hc != null) { - log.debug("Deleted collection '" + id + "', also deleting associated harvested_collection '" + hc.getOaiSource() + ":" + hc.getOaiSetId() + "'."); - harvestedCollectionService.delete(context, hc); - } - else + } + break; + case Constants.COLLECTION: + if (et == Event.DELETE) + { + HarvestedCollection hc = harvestedCollectionService.find(context, (Collection) event.getSubject(context)); + if (hc != null) { + log.debug("Deleted collection '" + id + "', also deleting associated harvested_collection '" + hc.getOaiSource() + ":" + hc.getOaiSetId() + "'."); + harvestedCollectionService.delete(context, hc); + } + else { log.debug("Deleted collection '" + id + "' and the associated harvested_collection."); } - } - default: - log.warn("consume() got unrecognized event: " + event.toString()); - } + } + default: + log.warn("consume() got unrecognized event: " + event.toString()); + } } /** * Handle the end of the event * * @param ctx + * The relevant DSpace Context. * @throws Exception if error */ @Override - public void end(Context ctx) + public void end(Context ctx) throws Exception { @@ -114,9 +117,10 @@ public class HarvestConsumer implements Consumer * Finish the event * * @param ctx + * The relevant DSpace Context. */ @Override - public void finish(Context ctx) + public void finish(Context ctx) { } diff --git a/dspace-api/src/main/java/org/dspace/harvest/HarvestScheduler.java b/dspace-api/src/main/java/org/dspace/harvest/HarvestScheduler.java index 2a692f253e..2b6ce104d9 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/HarvestScheduler.java +++ b/dspace-api/src/main/java/org/dspace/harvest/HarvestScheduler.java @@ -94,16 +94,21 @@ public class HarvestScheduler implements Runnable } public static String getStatus() { - switch(status) { - case HARVESTER_STATUS_RUNNING: - switch(interrupt) { - case HARVESTER_INTERRUPT_PAUSE: return("The scheduler is finishing active harvests before pausing. "); - case HARVESTER_INTERRUPT_STOP: return("The scheduler is shutting down. "); - } - return("The scheduler is actively harvesting collections. "); - case HARVESTER_STATUS_SLEEPING: return("The scheduler is waiting for collections to harvest. "); - case HARVESTER_STATUS_PAUSED: return("The scheduler is paused. "); - default: return("Automatic harvesting is not active. "); + switch (status) { + case HARVESTER_STATUS_RUNNING: + switch (interrupt) { + case HARVESTER_INTERRUPT_PAUSE: + return("The scheduler is finishing active harvests before pausing. "); + case HARVESTER_INTERRUPT_STOP: + return("The scheduler is shutting down. "); + } + return("The scheduler is actively harvesting collections. "); + case HARVESTER_STATUS_SLEEPING: + return("The scheduler is waiting for collections to harvest. "); + case HARVESTER_STATUS_PAUSED: + return("The scheduler is paused. "); + default: + return("Automatic harvesting is not active. "); } } @@ -278,6 +283,18 @@ public class HarvestScheduler implements Runnable * for harvesting before it is "due" for another cycle. This allows starting a harvest process * from the UI that still "plays nice" with these thread mechanics instead of making an * asynchronous call to runHarvest(). + * + * @param context + * The relevant DSpace Context. + * @param harvestedCollection + * collection to be harvested + * @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 addThread(Context context, HarvestedCollection harvestedCollection) throws SQLException, IOException, AuthorizeException { log.debug("****** Entered the addThread method. Active threads: " + harvestThreads.toString()); diff --git a/dspace-api/src/main/java/org/dspace/harvest/HarvestedCollection.java b/dspace-api/src/main/java/org/dspace/harvest/HarvestedCollection.java index 8a75b1cb3d..c78a45cdea 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/HarvestedCollection.java +++ b/dspace-api/src/main/java/org/dspace/harvest/HarvestedCollection.java @@ -59,31 +59,31 @@ public class HarvestedCollection implements ReloadableEntity private Date lastHarvested; @Transient - public static final int TYPE_NONE = 0; + public static final int TYPE_NONE = 0; @Transient - public static final int TYPE_DMD = 1; + public static final int TYPE_DMD = 1; @Transient - public static final int TYPE_DMDREF = 2; + public static final int TYPE_DMDREF = 2; @Transient - public static final int TYPE_FULL = 3; + public static final int TYPE_FULL = 3; @Transient - public static final int STATUS_READY = 0; + public static final int STATUS_READY = 0; @Transient - public static final int STATUS_BUSY = 1; + public static final int STATUS_BUSY = 1; @Transient - public static final int STATUS_QUEUED = 2; + public static final int STATUS_QUEUED = 2; @Transient - public static final int STATUS_OAI_ERROR = 3; + public static final int STATUS_OAI_ERROR = 3; @Transient - public static final int STATUS_UNKNOWN_ERROR = -1; + public static final int STATUS_UNKNOWN_ERROR = -1; /** * Protected constructor, create object using: * {@link org.dspace.harvest.service.HarvestedCollectionService#create(Context, Collection)} * */ - protected HarvestedCollection() + protected HarvestedCollection() { } @@ -93,32 +93,57 @@ public class HarvestedCollection implements ReloadableEntity /** * A function to set all harvesting-related parameters at once + * @param type + * harvest type (TYPE_NONE, TYPE_DMD, TYPE_DMDREF, TYPE_FULL) + * @param oaiSource + * base URL of the OAI-PMH server + * @param oaiSetId + * OAI set identifier + * @param mdConfigId + * harvest metadata config ID */ public void setHarvestParams(int type, String oaiSource, String oaiSetId, String mdConfigId) { - setHarvestType(type); - setOaiSource(oaiSource); - setOaiSetId(oaiSetId); - setHarvestMetadataConfig(mdConfigId); + setHarvestType(type); + setOaiSource(oaiSource); + setOaiSetId(oaiSetId); + setHarvestMetadataConfig(mdConfigId); } - /* Setters for the appropriate harvesting-related columns */ + /* + * Setters for the appropriate harvesting-related columns + * + * @param type + * harvest type (TYPE_NONE, TYPE_DMD, TYPE_DMDREF, TYPE_FULL + */ public void setHarvestType(int type) { - this.harvestType = type; + this.harvestType = type; } /** * Sets the current status of the collection. * - * @param status a HarvestInstance.STATUS_... constant + * @param status a HarvestInstance.STATUS_... constant (STATUS_READY, STATUS_BUSY, STATUS_QUEUED, STATUS_OAI_ERROR, STATUS_UNKNOWN_ERROR) */ public void setHarvestStatus(int status) { - this.harvestStatus = status; + this.harvestStatus = status; } + /** + * Sets the base URL of the OAI-PMH server. + * + * @param oaiSource base URL of the OAI-PMH server + * + */ public void setOaiSource(String oaiSource) { this.oaiSource = oaiSource; } + /** + * Sets the OAI set to harvest. + * + * @param oaiSetId OAI set to harvest + * + */ public void setOaiSetId(String oaiSetId) { this.oaiSetId = oaiSetId; } @@ -142,7 +167,7 @@ public class HarvestedCollection implements ReloadableEntity /* Getting for the appropriate harvesting-related columns */ public Collection getCollection() { - return collection; + return collection; } void setCollection(Collection collection) { @@ -150,34 +175,34 @@ public class HarvestedCollection implements ReloadableEntity } public int getHarvestType() { - return harvestType; + return harvestType; } public int getHarvestStatus() { - return harvestStatus; + return harvestStatus; } public String getOaiSource() { - return oaiSource; + return oaiSource; } public String getOaiSetId() { - return oaiSetId; + return oaiSetId; } public String getHarvestMetadataConfig() { - return metadataConfigId; + return metadataConfigId; } public String getHarvestMessage() { - return harvestMessage; + return harvestMessage; } public Date getHarvestDate() { - return lastHarvested; + return lastHarvested; } public Date getHarvestStartTime() { - return harvestStartTime; + return harvestStartTime; } } diff --git a/dspace-api/src/main/java/org/dspace/harvest/HarvestedItem.java b/dspace-api/src/main/java/org/dspace/harvest/HarvestedItem.java index 4393fb0094..5b2f840665 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/HarvestedItem.java +++ b/dspace-api/src/main/java/org/dspace/harvest/HarvestedItem.java @@ -62,12 +62,15 @@ public class HarvestedItem implements ReloadableEntity return item; } + // FIXME: duplicate below? void setOaiId(String oaiId) { this.oaiId = oaiId; } /** * Get the oai_id associated with this item + * + * @return itemOaiID item's OAI identifier */ public String getOaiID() { @@ -76,6 +79,8 @@ public class HarvestedItem implements ReloadableEntity /** * Set the oai_id associated with this item + * + * @param itemOaiID item's OAI identifier */ public void setOaiID(String itemOaiID) { diff --git a/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java b/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java index 0fc86d845c..7e079bd4e1 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java +++ b/dspace-api/src/main/java/org/dspace/harvest/OAIHarvester.java @@ -53,7 +53,7 @@ import java.util.*; public class OAIHarvester { - /** log4j category */ + /** log4j category */ private static Logger log = Logger.getLogger(OAIHarvester.class); private static final Namespace ATOM_NS = Namespace.getNamespace("http://www.w3.org/2005/Atom"); @@ -64,26 +64,26 @@ public class OAIHarvester { public static final String OAI_SET_ERROR = "noSuchSet"; public static final String OAI_DMD_ERROR = "metadataNotSupported"; public static final String OAI_ORE_ERROR = "oreNotSupported"; - protected BitstreamService bitstreamService; - protected BitstreamFormatService bitstreamFormatService; - protected BundleService bundleService; - protected CollectionService collectionService; - protected HarvestedCollectionService harvestedCollection; - protected InstallItemService installItemService; - protected ItemService itemService; - protected HandleService handleService; - protected HarvestedItemService harvestedItemService; - protected WorkspaceItemService workspaceItemService; + protected BitstreamService bitstreamService; + protected BitstreamFormatService bitstreamFormatService; + protected BundleService bundleService; + protected CollectionService collectionService; + protected HarvestedCollectionService harvestedCollection; + protected InstallItemService installItemService; + protected ItemService itemService; + protected HandleService handleService; + protected HarvestedItemService harvestedItemService; + protected WorkspaceItemService workspaceItemService; protected PluginService pluginService; protected ConfigurationService configurationService; // The collection this harvester instance is dealing with - Collection targetCollection; - HarvestedCollection harvestRow; + Collection targetCollection; + HarvestedCollection harvestRow; - // our context - Context ourContext; + // our context + Context ourContext; // Namespace used by the ORE serialization format // Set in dspace.cfg as oai.harvester.oreSerializationFormat.{ORESerialKey} = {ORESerialNS} @@ -100,40 +100,40 @@ public class OAIHarvester { // The point at which this thread should terminate itself /* Initialize the harvester with a collection object */ - public OAIHarvester(Context c, DSpaceObject dso, HarvestedCollection hc) throws HarvestingException, SQLException - { - bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); - bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); - bundleService = ContentServiceFactory.getInstance().getBundleService(); - collectionService = ContentServiceFactory.getInstance().getCollectionService(); - handleService = HandleServiceFactory.getInstance().getHandleService(); - harvestedCollection = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); - harvestedItemService = HarvestServiceFactory.getInstance().getHarvestedItemService(); - itemService = ContentServiceFactory.getInstance().getItemService(); - installItemService = ContentServiceFactory.getInstance().getInstallItemService(); + public OAIHarvester(Context c, DSpaceObject dso, HarvestedCollection hc) throws HarvestingException, SQLException + { + bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); + bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); + bundleService = ContentServiceFactory.getInstance().getBundleService(); + collectionService = ContentServiceFactory.getInstance().getCollectionService(); + handleService = HandleServiceFactory.getInstance().getHandleService(); + harvestedCollection = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); + harvestedItemService = HarvestServiceFactory.getInstance().getHarvestedItemService(); + itemService = ContentServiceFactory.getInstance().getItemService(); + installItemService = ContentServiceFactory.getInstance().getInstallItemService(); - workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); + workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); pluginService = CoreServiceFactory.getInstance().getPluginService(); - configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); + configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); - if (dso.getType() != Constants.COLLECTION) + if (dso.getType() != Constants.COLLECTION) { throw new HarvestingException("OAIHarvester can only harvest collections"); } - ourContext = c; - targetCollection = (Collection)dso; + ourContext = c; + targetCollection = (Collection)dso; - harvestRow = hc; - if (harvestRow == null || !harvestedCollection.isHarvestable(harvestRow)) + harvestRow = hc; + if (harvestRow == null || !harvestedCollection.isHarvestable(harvestRow)) { throw new HarvestingException("Provided collection is not set up for harvesting"); } // Set the ORE options - Namespace ORESerializationNamespace = OAIHarvester.getORENamespace(); + Namespace ORESerializationNamespace = OAIHarvester.getORENamespace(); //No need to worry about ORESerializationNamespace, this can never be null ORESerialNS = Namespace.getNamespace(ORESerializationNamespace.getURI()); @@ -144,20 +144,20 @@ public class OAIHarvester { metadataNS = OAIHarvester.getDMDNamespace(metadataKey); if (metadataNS == null) { - log.error("No matching metadata namespace found for \"" + metadataKey + "\", see oai.cfg option \"oai.harvester.metadataformats.{MetadataKey} = {MetadataNS},{Display Name}\""); - throw new HarvestingException("Metadata declaration not found"); + log.error("No matching metadata namespace found for \"" + metadataKey + "\", see oai.cfg option \"oai.harvester.metadataformats.{MetadataKey} = {MetadataNS},{Display Name}\""); + throw new HarvestingException("Metadata declaration not found"); } - } + } - /** - * Search the configuration options and find the ORE serialization string - * @return Namespace of the supported ORE format. Returns null if not found. - */ - private static Namespace getORENamespace() { - String ORESerializationString = null; - String ORESeialKey = null; - String oreString = "oai.harvester.oreSerializationFormat"; + /** + * Search the configuration options and find the ORE serialization string + * @return Namespace of the supported ORE format. Returns null if not found. + */ + private static Namespace getORENamespace() { + String ORESerializationString = null; + String ORESeialKey = null; + String oreString = "oai.harvester.oreSerializationFormat"; List keys = DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyKeys(oreString); @@ -171,16 +171,16 @@ public class OAIHarvester { // Fallback if the configuration option is not present return Namespace.getNamespace("ore", ATOM_NS.getURI()); - } + } - /** - * Cycle through the options and find the metadata namespace matching the provided key. - * @param metadataKey - * @return Namespace of the designated metadata format. Returns null of not found. - */ - private static Namespace getDMDNamespace(String metadataKey) { - String metadataString = null; + /** + * Cycle through the options and find the metadata namespace matching the provided key. + * @param metadataKey + * @return Namespace of the designated metadata format. Returns null of not found. + */ + private static Namespace getDMDNamespace(String metadataKey) { + String metadataString = null; String metaString = "oai.harvester.metadataformats"; List keys = DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyKeys(metaString); @@ -188,411 +188,431 @@ public class OAIHarvester { for(String key : keys) { if (key.substring(metaString.length()+1).equals((metadataKey))) { - metadataString = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key); - String namespacePiece; - if (metadataString.indexOf(',') != -1) + metadataString = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key); + String namespacePiece; + if (metadataString.indexOf(',') != -1) { namespacePiece = metadataString.substring(0, metadataString.indexOf(',')); } - else + else { namespacePiece = metadataString; } - return Namespace.getNamespace(namespacePiece); + return Namespace.getNamespace(namespacePiece); } } return null; - } + } - - - - /** + /** * Performs a harvest cycle on this collection. This will query the remote OAI-PMH provider, check for updates since last * harvest, and ingest the returned items. + * + * @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 runHarvest() throws SQLException, IOException, AuthorizeException - { - boolean originalMode = ourContext.isBatchModeEnabled(); - ourContext.enableBatchMode(true); + public void runHarvest() throws SQLException, IOException, AuthorizeException + { + boolean originalMode = ourContext.isBatchModeEnabled(); + ourContext.enableBatchMode(true); - // figure out the relevant parameters - String oaiSource = harvestRow.getOaiSource(); - String oaiSetId = harvestRow.getOaiSetId(); + // figure out the relevant parameters + String oaiSource = harvestRow.getOaiSource(); + String oaiSetId = harvestRow.getOaiSetId(); //If we have all selected then make sure that we do not include a set filter - if("all".equals(oaiSetId)) + if ("all".equals(oaiSetId)) { oaiSetId = null; } - Date lastHarvestDate = harvestRow.getHarvestDate(); - String fromDate = null; - if (lastHarvestDate != null) + Date lastHarvestDate = harvestRow.getHarvestDate(); + String fromDate = null; + if (lastHarvestDate != null) { fromDate = processDate(harvestRow.getHarvestDate()); } - long totalListSize = 0; - long currentRecord = 0; - Date startTime = new Date(); - String toDate = processDate(startTime,0); + long totalListSize = 0; + long currentRecord = 0; + Date startTime = new Date(); + String toDate = processDate(startTime,0); - String dateGranularity; + String dateGranularity; - try - { - // obtain the desired descriptive metadata format and verify that the OAI server actually provides it - // do the same thing for ORE, which should be encoded in Atom and carry its namespace - String descMDPrefix = null; - String OREPrefix; - try { - dateGranularity = oaiGetDateGranularity(oaiSource); - if (fromDate != null) + try + { + // obtain the desired descriptive metadata format and verify that the OAI server actually provides it + // do the same thing for ORE, which should be encoded in Atom and carry its namespace + String descMDPrefix = null; + String OREPrefix; + try { + dateGranularity = oaiGetDateGranularity(oaiSource); + if (fromDate != null) { fromDate = fromDate.substring(0, dateGranularity.length()); } - toDate = toDate.substring(0, dateGranularity.length()); + toDate = toDate.substring(0, dateGranularity.length()); - descMDPrefix = oaiResolveNamespaceToPrefix(oaiSource, metadataNS.getURI()); - OREPrefix = oaiResolveNamespaceToPrefix(oaiSource, ORESerialNS.getURI()); - } - catch (FileNotFoundException fe) { - log.error("The OAI server did not respond."); - throw new HarvestingException("The OAI server did not respond.", fe); - } - catch (ConnectException fe) { - log.error("The OAI server did not respond."); - throw new HarvestingException("The OAI server did not respond.", fe); - } - if (descMDPrefix == null) { - log.error("The OAI server does not support this metadata format"); - throw new HarvestingException("The OAI server does not support this metadata format: " + metadataNS.getURI()); - } - if (OREPrefix == null && harvestRow.getHarvestType() != HarvestedCollection.TYPE_DMD) { - throw new HarvestingException("The OAI server does not support ORE dissemination in the configured serialization format: " + ORESerialNS.getURI()); - } + descMDPrefix = oaiResolveNamespaceToPrefix(oaiSource, metadataNS.getURI()); + OREPrefix = oaiResolveNamespaceToPrefix(oaiSource, ORESerialNS.getURI()); + } + catch (FileNotFoundException fe) { + log.error("The OAI server did not respond."); + throw new HarvestingException("The OAI server did not respond.", fe); + } + catch (ConnectException fe) { + log.error("The OAI server did not respond."); + throw new HarvestingException("The OAI server did not respond.", fe); + } + if (descMDPrefix == null) { + log.error("The OAI server does not support this metadata format"); + throw new HarvestingException("The OAI server does not support this metadata format: " + metadataNS.getURI()); + } + if (OREPrefix == null && harvestRow.getHarvestType() != HarvestedCollection.TYPE_DMD) { + throw new HarvestingException("The OAI server does not support ORE dissemination in the configured serialization format: " + ORESerialNS.getURI()); + } - Document oaiResponse = null; - Element root = null; - String resumptionToken; + Document oaiResponse = null; + Element root = null; + String resumptionToken; - // set the status indicating the collection is currently being processed - harvestRow.setHarvestStatus(HarvestedCollection.STATUS_BUSY); - harvestRow.setHarvestMessage("Collection harvesting is initializing..."); - harvestRow.setHarvestStartTime(startTime); - harvestedCollection.update(ourContext, harvestRow); - intermediateCommit(); + // set the status indicating the collection is currently being processed + harvestRow.setHarvestStatus(HarvestedCollection.STATUS_BUSY); + harvestRow.setHarvestMessage("Collection harvesting is initializing..."); + harvestRow.setHarvestStartTime(startTime); + harvestedCollection.update(ourContext, harvestRow); + intermediateCommit(); - // expiration timer starts - int expirationInterval = configurationService.getIntProperty("oai.harvester.threadTimeout"); - if (expirationInterval == 0) + // expiration timer starts + int expirationInterval = configurationService.getIntProperty("oai.harvester.threadTimeout"); + if (expirationInterval == 0) { expirationInterval = 24; } - Calendar calendar = Calendar.getInstance(); - calendar.setTime(startTime); - calendar.add(Calendar.HOUR, expirationInterval); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(startTime); + calendar.add(Calendar.HOUR, expirationInterval); Date expirationTime = calendar.getTime(); - // main loop to keep requesting more objects until we're done - List records; - Set errorSet = new HashSet(); + // main loop to keep requesting more objects until we're done + List records; + Set errorSet = new HashSet(); - ListRecords listRecords = new ListRecords(oaiSource, fromDate, toDate, oaiSetId, descMDPrefix); - log.debug("Harvesting request parameters: listRecords " + oaiSource + " " + fromDate + " " + toDate + " " + oaiSetId + " " + descMDPrefix); - if (listRecords != null) + ListRecords listRecords = new ListRecords(oaiSource, fromDate, toDate, oaiSetId, descMDPrefix); + log.debug("Harvesting request parameters: listRecords " + oaiSource + " " + fromDate + " " + toDate + " " + oaiSetId + " " + descMDPrefix); + if (listRecords != null) { log.info("HTTP Request: " + listRecords.getRequestURL()); } - while (listRecords != null) - { - records = new ArrayList(); - oaiResponse = db.build(listRecords.getDocument()); + while (listRecords != null) + { + records = new ArrayList(); + oaiResponse = db.build(listRecords.getDocument()); - if (listRecords.getErrors() != null && listRecords.getErrors().getLength() > 0) - { - for (int i=0; i 0) + { + for (int i=0; i0) - { - log.info("Found " + records.size() + " records to process"); - for (Element record : records) { - // check for STOP interrupt from the scheduler - if (HarvestScheduler.getInterrupt() == HarvestScheduler.HARVESTER_INTERRUPT_STOP) + // Process the obtained records + if (records != null && records.size()>0) + { + log.info("Found " + records.size() + " records to process"); + for (Element record : records) { + // check for STOP interrupt from the scheduler + if (HarvestScheduler.getInterrupt() == HarvestScheduler.HARVESTER_INTERRUPT_STOP) { throw new HarvestingException("Harvest process for " + targetCollection.getID() + " interrupted by stopping the scheduler."); } - // check for timeout - if (expirationTime.before(new Date())) + // check for timeout + if (expirationTime.before(new Date())) { throw new HarvestingException("runHarvest method timed out for collection " + targetCollection.getID()); } - currentRecord++; + currentRecord++; - processRecord(record, OREPrefix, currentRecord, totalListSize); - ourContext.dispatchEvents(); + processRecord(record, OREPrefix, currentRecord, totalListSize); + ourContext.dispatchEvents(); - intermediateCommit(); - } - } + intermediateCommit(); + } + } - // keep going if there are more records to process - resumptionToken = listRecords.getResumptionToken(); - if (resumptionToken == null || resumptionToken.length() == 0) { - listRecords = null; - } - else { - listRecords = new ListRecords(oaiSource, resumptionToken); - } + // keep going if there are more records to process + resumptionToken = listRecords.getResumptionToken(); + if (resumptionToken == null || resumptionToken.length() == 0) { + listRecords = null; + } + else { + listRecords = new ListRecords(oaiSource, resumptionToken); + } ourContext.turnOffAuthorisationSystem(); try { collectionService.update(ourContext, targetCollection); - harvestRow.setHarvestMessage(String.format("Collection is currently being harvested (item %d of %d)", currentRecord, totalListSize)); - harvestedCollection.update(ourContext, harvestRow); + harvestRow.setHarvestMessage(String.format("Collection is currently being harvested (item %d of %d)", currentRecord, totalListSize)); + harvestedCollection.update(ourContext, harvestRow); } finally { //In case of an exception, make sure to restore our authentication state to the previous state ourContext.restoreAuthSystemState(); } - ourContext.dispatchEvents(); - intermediateCommit(); - } - } - catch (HarvestingException hex) { - log.error("Harvesting error occurred while processing an OAI record: " + hex.getMessage(), hex); - harvestRow.setHarvestMessage("Error occurred while processing an OAI record"); + ourContext.dispatchEvents(); + intermediateCommit(); + } + } + catch (HarvestingException hex) { + log.error("Harvesting error occurred while processing an OAI record: " + hex.getMessage(), hex); + harvestRow.setHarvestMessage("Error occurred while processing an OAI record"); - // if the last status is also an error, alert the admin - if (harvestRow.getHarvestMessage().contains("Error")) { - alertAdmin(HarvestedCollection.STATUS_OAI_ERROR, hex); - } - harvestRow.setHarvestStatus(HarvestedCollection.STATUS_OAI_ERROR); - harvestedCollection.update(ourContext, harvestRow); - ourContext.complete(); - return; - } - catch (Exception ex) { - harvestRow.setHarvestMessage("Unknown error occurred while generating an OAI response"); - harvestRow.setHarvestStatus(HarvestedCollection.STATUS_UNKNOWN_ERROR); - harvestedCollection.update(ourContext, harvestRow); - alertAdmin(HarvestedCollection.STATUS_UNKNOWN_ERROR, ex); - log.error("Error occurred while generating an OAI response: " + ex.getMessage() + " " + ex.getCause(), ex); - ourContext.complete(); - return; - } - finally { - harvestedCollection.update(ourContext, harvestRow); + // if the last status is also an error, alert the admin + if (harvestRow.getHarvestMessage().contains("Error")) { + alertAdmin(HarvestedCollection.STATUS_OAI_ERROR, hex); + } + harvestRow.setHarvestStatus(HarvestedCollection.STATUS_OAI_ERROR); + harvestedCollection.update(ourContext, harvestRow); + ourContext.complete(); + return; + } + catch (Exception ex) { + harvestRow.setHarvestMessage("Unknown error occurred while generating an OAI response"); + harvestRow.setHarvestStatus(HarvestedCollection.STATUS_UNKNOWN_ERROR); + harvestedCollection.update(ourContext, harvestRow); + alertAdmin(HarvestedCollection.STATUS_UNKNOWN_ERROR, ex); + log.error("Error occurred while generating an OAI response: " + ex.getMessage() + " " + ex.getCause(), ex); + ourContext.complete(); + return; + } + finally { + harvestedCollection.update(ourContext, harvestRow); ourContext.turnOffAuthorisationSystem(); - collectionService.update(ourContext, targetCollection); - ourContext.restoreAuthSystemState(); - } + collectionService.update(ourContext, targetCollection); + ourContext.restoreAuthSystemState(); + } - // If we got to this point, it means the harvest was completely successful - Date finishTime = new Date(); - long timeTaken = finishTime.getTime() - startTime.getTime(); - harvestRow.setHarvestStartTime(startTime); - harvestRow.setHarvestMessage("Harvest from " + oaiSource + " successful"); - harvestRow.setHarvestStatus(HarvestedCollection.STATUS_READY); - log.info("Harvest from " + oaiSource + " successful. The process took " + timeTaken + " milliseconds. Harvested " + currentRecord + " items."); - harvestedCollection.update(ourContext, harvestRow); + // If we got to this point, it means the harvest was completely successful + Date finishTime = new Date(); + long timeTaken = finishTime.getTime() - startTime.getTime(); + harvestRow.setHarvestStartTime(startTime); + harvestRow.setHarvestMessage("Harvest from " + oaiSource + " successful"); + harvestRow.setHarvestStatus(HarvestedCollection.STATUS_READY); + log.info("Harvest from " + oaiSource + " successful. The process took " + timeTaken + " milliseconds. Harvested " + currentRecord + " items."); + harvestedCollection.update(ourContext, harvestRow); - ourContext.enableBatchMode(originalMode); - } + ourContext.enableBatchMode(originalMode); + } - private void intermediateCommit() throws SQLException { - ourContext.commit(); - reloadRequiredEntities(); - } + private void intermediateCommit() throws SQLException { + ourContext.commit(); + reloadRequiredEntities(); + } - private void reloadRequiredEntities() throws SQLException { - //Reload our objects in our cache - targetCollection = ourContext.reloadEntity(targetCollection); - harvestRow = ourContext.reloadEntity(harvestRow); - } + private void reloadRequiredEntities() throws SQLException { + //Reload our objects in our cache + targetCollection = ourContext.reloadEntity(targetCollection); + harvestRow = ourContext.reloadEntity(harvestRow); + } - /** + /** * Process an individual PMH record, making (or updating) a corresponding DSpace Item. - * @param record a JDOM Element containing the actual PMH record with descriptive metadata. + * + * @param record a JDOM Element containing the actual PMH record with descriptive metadata. * @param OREPrefix the metadataprefix value used by the remote PMH server to disseminate ORE. Only used for collections set up to harvest content. - * @param currentRecord - * @param totalListSize The total number of records that this Harvest contains - */ - protected void processRecord(Element record, String OREPrefix, final long currentRecord, long totalListSize) throws SQLException, AuthorizeException, IOException, CrosswalkException, HarvestingException, ParserConfigurationException, SAXException, TransformerException + * @param currentRecord current record number to log + * @param totalListSize The total number of records that this Harvest contains + * + * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws CrosswalkException if crosswalk error + * @throws HarvestingException if harvesting error + * @throws ParserConfigurationException XML parsing error + * @throws SAXException if XML processing error + * @throws TransformerException if XML transformer error + */ + protected void processRecord(Element record, String OREPrefix, final long currentRecord, long totalListSize) + throws SQLException, AuthorizeException, IOException, CrosswalkException, HarvestingException, ParserConfigurationException, SAXException, TransformerException { - WorkspaceItem wi = null; - Date timeStart = new Date(); + WorkspaceItem wi = null; + Date timeStart = new Date(); - // grab the oai identifier - String itemOaiID = record.getChild("header", OAI_NS).getChild("identifier", OAI_NS).getText(); - Element header = record.getChild("header",OAI_NS); + // grab the oai identifier + String itemOaiID = record.getChild("header", OAI_NS).getChild("identifier", OAI_NS).getText(); + Element header = record.getChild("header",OAI_NS); - // look up the item corresponding to the OAI identifier - Item item = harvestedItemService.getItemByOAIId(ourContext, itemOaiID, targetCollection); + // look up the item corresponding to the OAI identifier + Item item = harvestedItemService.getItemByOAIId(ourContext, itemOaiID, targetCollection); - // Make sure the item hasn't been deleted in the mean time - if (header.getAttribute("status") != null && header.getAttribute("status").getValue().equals("deleted")) { - log.info("Item " + itemOaiID + " has been marked as deleted on the OAI server."); - if (item != null) + // Make sure the item hasn't been deleted in the mean time + if (header.getAttribute("status") != null && header.getAttribute("status").getValue().equals("deleted")) { + log.info("Item " + itemOaiID + " has been marked as deleted on the OAI server."); + if (item != null) { collectionService.removeItem(ourContext, targetCollection, item); } - ourContext.restoreAuthSystemState(); - return; - } + ourContext.restoreAuthSystemState(); + return; + } - // If we are only harvesting descriptive metadata, the record should already contain all we need - List descMD = record.getChild("metadata", OAI_NS).getChildren(); - IngestionCrosswalk MDxwalk = (IngestionCrosswalk)pluginService.getNamedPlugin(IngestionCrosswalk.class, this.metadataKey); + // If we are only harvesting descriptive metadata, the record should already contain all we need + List descMD = record.getChild("metadata", OAI_NS).getChildren(); + IngestionCrosswalk MDxwalk = (IngestionCrosswalk)pluginService.getNamedPlugin(IngestionCrosswalk.class, this.metadataKey); - // Otherwise, obtain the ORE ReM and initiate the ORE crosswalk - IngestionCrosswalk ORExwalk = null; - Element oreREM = null; - if (harvestRow.getHarvestType() > 1) { - oreREM = getMDrecord(harvestRow.getOaiSource(), itemOaiID, OREPrefix).get(0); - ORExwalk = (IngestionCrosswalk)pluginService.getNamedPlugin(IngestionCrosswalk.class, this.ORESerialKey); - } + // Otherwise, obtain the ORE ReM and initiate the ORE crosswalk + IngestionCrosswalk ORExwalk = null; + Element oreREM = null; + if (harvestRow.getHarvestType() > 1) { + oreREM = getMDrecord(harvestRow.getOaiSource(), itemOaiID, OREPrefix).get(0); + ORExwalk = (IngestionCrosswalk)pluginService.getNamedPlugin(IngestionCrosswalk.class, this.ORESerialKey); + } - // Ignore authorization - ourContext.turnOffAuthorisationSystem(); + // Ignore authorization + ourContext.turnOffAuthorisationSystem(); - HarvestedItem hi; + HarvestedItem hi; - if (item != null) // found an item so we modify - { - log.debug("Item " + item.getHandle() + " was found locally. Using it to harvest " + itemOaiID + "."); + if (item != null) // found an item so we modify + { + log.debug("Item " + item.getHandle() + " was found locally. Using it to harvest " + itemOaiID + "."); - // FIXME: check for null pointer if for some odd reason we don't have a matching hi - hi = harvestedItemService.find(ourContext, item); + // FIXME: check for null pointer if for some odd reason we don't have a matching hi + hi = harvestedItemService.find(ourContext, item); - // Compare last-harvest on the item versus the last time the item was updated on the OAI provider side - // If ours is more recent, forgo this item, since it's probably a left-over from a previous harvesting attempt - Date OAIDatestamp = Utils.parseISO8601Date(header.getChildText("datestamp", OAI_NS)); - Date itemLastHarvest = hi.getHarvestDate(); - if (itemLastHarvest != null && OAIDatestamp.before(itemLastHarvest)) { - log.info("Item " + item.getHandle() + " was harvested more recently than the last update time reported by the OAI server; skipping."); - return; - } + // Compare last-harvest on the item versus the last time the item was updated on the OAI provider side + // If ours is more recent, forgo this item, since it's probably a left-over from a previous harvesting attempt + Date OAIDatestamp = Utils.parseISO8601Date(header.getChildText("datestamp", OAI_NS)); + Date itemLastHarvest = hi.getHarvestDate(); + if (itemLastHarvest != null && OAIDatestamp.before(itemLastHarvest)) { + log.info("Item " + item.getHandle() + " was harvested more recently than the last update time reported by the OAI server; skipping."); + return; + } - // Otherwise, clear and re-import the metadata and bitstreams - itemService.clearMetadata(ourContext, item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); - if (descMD.size() == 1) + // Otherwise, clear and re-import the metadata and bitstreams + itemService.clearMetadata(ourContext, item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); + if (descMD.size() == 1) { MDxwalk.ingest(ourContext, item, descMD.get(0), true); } - else + else { MDxwalk.ingest(ourContext, item, descMD, true); } - // Import the actual bitstreams - if (harvestRow.getHarvestType() == 3) { - log.info("Running ORE ingest on: " + item.getHandle()); + // Import the actual bitstreams + if (harvestRow.getHarvestType() == 3) { + log.info("Running ORE ingest on: " + item.getHandle()); - List allBundles = item.getBundles(); - for (Bundle bundle : allBundles) { - itemService.removeBundle(ourContext, item, bundle); - } - ORExwalk.ingest(ourContext, item, oreREM, true); - } - } - else - // NOTE: did not find, so we create (presumably, there will never be a case where an item already - // exists in a harvest collection but does not have an OAI_id) - { - wi = workspaceItemService.create(ourContext, targetCollection, false); - item = wi.getItem(); + List allBundles = item.getBundles(); + for (Bundle bundle : allBundles) { + itemService.removeBundle(ourContext, item, bundle); + } + ORExwalk.ingest(ourContext, item, oreREM, true); + } + } + else + // NOTE: did not find, so we create (presumably, there will never be a case where an item already + // exists in a harvest collection but does not have an OAI_id) + { + wi = workspaceItemService.create(ourContext, targetCollection, false); + item = wi.getItem(); - hi = harvestedItemService.create(ourContext, item, itemOaiID); - //item.setOaiID(itemOaiID); + hi = harvestedItemService.create(ourContext, item, itemOaiID); + //item.setOaiID(itemOaiID); - if (descMD.size() == 1) + if (descMD.size() == 1) { MDxwalk.ingest(ourContext, item, descMD.get(0), true); } - else + else { MDxwalk.ingest(ourContext, item, descMD, true); } - if (harvestRow.getHarvestType() == 3) { - ORExwalk.ingest(ourContext, item, oreREM, true); - } + if (harvestRow.getHarvestType() == 3) { + ORExwalk.ingest(ourContext, item, oreREM, true); + } - // see if a handle can be extracted for the item - String handle = extractHandle(item); + // see if a handle can be extracted for the item + String handle = extractHandle(item); - if (handle != null) - { - DSpaceObject dso = handleService.resolveToObject(ourContext, handle); - if (dso != null) + if (handle != null) + { + DSpaceObject dso = handleService.resolveToObject(ourContext, handle); + if (dso != null) { throw new HarvestingException("Handle collision: attempted to re-assign handle '" + handle + "' to an incoming harvested item '" + hi.getOaiID() + "'."); } - } + } - try { - item = installItemService.installItem(ourContext, wi, handle); - //item = InstallItem.installItem(ourContext, wi); - } - // clean up the workspace item if something goes wrong before - catch(SQLException | IOException | AuthorizeException se) { - workspaceItemService.deleteWrapper(ourContext, wi); - throw se; - } - } + try { + item = installItemService.installItem(ourContext, wi, handle); + //item = InstallItem.installItem(ourContext, wi); + } + // clean up the workspace item if something goes wrong before + catch(SQLException | IOException | AuthorizeException se) { + workspaceItemService.deleteWrapper(ourContext, wi); + throw se; + } + } - // Now create the special ORE bundle and drop the ORE document in it - if (harvestRow.getHarvestType() == 2 || harvestRow.getHarvestType() == 3) - { - Bundle OREBundle = null; + // Now create the special ORE bundle and drop the ORE document in it + if (harvestRow.getHarvestType() == 2 || harvestRow.getHarvestType() == 3) + { + Bundle OREBundle = null; List OREBundles = itemService.getBundles(item, "ORE"); - Bitstream OREBitstream = null; + Bitstream OREBitstream = null; if ( OREBundles.size() > 0 ) OREBundle = OREBundles.get(0); else OREBundle = bundleService.create(ourContext, item, "ORE"); - XMLOutputter outputter = new XMLOutputter(); - String OREString = outputter.outputString(oreREM); - ByteArrayInputStream OREStream = new ByteArrayInputStream(OREString.getBytes()); + XMLOutputter outputter = new XMLOutputter(); + String OREString = outputter.outputString(oreREM); + ByteArrayInputStream OREStream = new ByteArrayInputStream(OREString.getBytes()); OREBitstream = bundleService.getBitstreamByName(OREBundle, "ORE.xml"); @@ -600,33 +620,33 @@ public class OAIHarvester { bundleService.removeBitstream(ourContext, OREBundle, OREBitstream); OREBitstream = bitstreamService.create(ourContext, OREBundle, OREStream); - OREBitstream.setName(ourContext, "ORE.xml"); + OREBitstream.setName(ourContext, "ORE.xml"); - BitstreamFormat bf = bitstreamFormatService.guessFormat(ourContext, OREBitstream); - bitstreamService.setFormat(ourContext, OREBitstream, bf); - bitstreamService.update(ourContext, OREBitstream); + BitstreamFormat bf = bitstreamFormatService.guessFormat(ourContext, OREBitstream); + bitstreamService.setFormat(ourContext, OREBitstream, bf); + bitstreamService.update(ourContext, OREBitstream); - bundleService.addBitstream(ourContext, OREBundle, OREBitstream); - bundleService.update(ourContext, OREBundle); - } + bundleService.addBitstream(ourContext, OREBundle, OREBitstream); + bundleService.update(ourContext, OREBundle); + } - //item.setHarvestDate(new Date()); - hi.setHarvestDate(new Date()); + //item.setHarvestDate(new Date()); + hi.setHarvestDate(new Date()); - // Add provenance that this item was harvested via OAI - String provenanceMsg = "Item created via OAI harvest from source: " - + this.harvestRow.getOaiSource() + " on " + new DCDate(hi.getHarvestDate()) - + " (GMT). Item's OAI Record identifier: " + hi.getOaiID(); - itemService.addMetadata(ourContext, item, "dc", "description", "provenance", "en", provenanceMsg); + // Add provenance that this item was harvested via OAI + String provenanceMsg = "Item created via OAI harvest from source: " + + this.harvestRow.getOaiSource() + " on " + new DCDate(hi.getHarvestDate()) + + " (GMT). Item's OAI Record identifier: " + hi.getOaiID(); + itemService.addMetadata(ourContext, item, "dc", "description", "provenance", "en", provenanceMsg); - itemService.update(ourContext, item); - harvestedItemService.update(ourContext, hi); - long timeTaken = new Date().getTime() - timeStart.getTime(); - log.info(String.format("Item %s (%s) has been ingested (item %d of %d). The whole process took: %d ms.", - item.getHandle(), item.getID(), currentRecord, totalListSize, timeTaken)); + itemService.update(ourContext, item); + harvestedItemService.update(ourContext, hi); + long timeTaken = new Date().getTime() - timeStart.getTime(); + log.info(String.format("Item %s (%s) has been ingested (item %d of %d). The whole process took: %d ms.", + item.getHandle(), item.getID(), currentRecord, totalListSize, timeTaken)); - // Stop ignoring authorization - ourContext.restoreAuthSystemState(); + // Stop ignoring authorization + ourContext.restoreAuthSystemState(); } @@ -640,98 +660,98 @@ public class OAIHarvester { */ protected String extractHandle(Item item) { - String[] acceptedHandleServers = configurationService.getArrayProperty("oai.harvester.acceptedHandleServer"); - if (acceptedHandleServers == null) + String[] acceptedHandleServers = configurationService.getArrayProperty("oai.harvester.acceptedHandleServer"); + if (acceptedHandleServers == null) { acceptedHandleServers = new String[]{"hdl.handle.net"}; } - String[] rejectedHandlePrefixes = configurationService.getArrayProperty("oai.harvester.rejectedHandlePrefix"); - if (rejectedHandlePrefixes == null) + String[] rejectedHandlePrefixes = configurationService.getArrayProperty("oai.harvester.rejectedHandlePrefix"); + if (rejectedHandlePrefixes == null) { rejectedHandlePrefixes = new String[]{"123456789"}; } - List values = itemService.getMetadata(item, "dc", "identifier", Item.ANY, Item.ANY); + List values = itemService.getMetadata(item, "dc", "identifier", Item.ANY, Item.ANY); - if (values.size() > 0 && acceptedHandleServers != null) - { - for (MetadataValue value : values) - { - // 0 1 2 3 4 - // http://hdl.handle.net/1234/12 - String[] urlPieces = value.getValue().split("/"); - if (urlPieces.length != 5) + if (values.size() > 0 && acceptedHandleServers != null) + { + for (MetadataValue value : values) + { + // 0 1 2 3 4 + // http://hdl.handle.net/1234/12 + String[] urlPieces = value.getValue().split("/"); + if (urlPieces.length != 5) { continue; } - for (String server : acceptedHandleServers) { - if (urlPieces[2].equals(server)) { - for (String prefix : rejectedHandlePrefixes) { - if (!urlPieces[3].equals(prefix)) + for (String server : acceptedHandleServers) { + if (urlPieces[2].equals(server)) { + for (String prefix : rejectedHandlePrefixes) { + if (!urlPieces[3].equals(prefix)) { return urlPieces[3] + "/" + urlPieces[4]; } - } + } - } - } - } - } + } + } + } + } - return null; + return null; } - /** - * Process a date, converting it to RFC3339 format, setting the timezone to UTC and subtracting time padding - * from the config file. - * @param date source Date - * @return a string in the format 'yyyy-mm-ddThh:mm:ssZ' and converted to UTC timezone - */ + /** + * Process a date, converting it to RFC3339 format, setting the timezone to UTC and subtracting time padding + * from the config file. + * @param date source Date + * @return a string in the format 'yyyy-mm-ddThh:mm:ssZ' and converted to UTC timezone + */ private String processDate(Date date) { - Integer timePad = configurationService.getIntProperty("oai.harvester.timePadding"); + Integer timePad = configurationService.getIntProperty("oai.harvester.timePadding"); - if (timePad == 0) { - timePad = 120; - } + if (timePad == 0) { + timePad = 120; + } - return processDate(date, timePad); + return processDate(date, timePad); } /** - * Process a date, converting it to RFC3339 format, setting the timezone to UTC and subtracting time padding - * from the config file. - * @param date source Date - * @param secondsPad number of seconds to subtract from the date - * @return a string in the format 'yyyy-mm-ddThh:mm:ssZ' and converted to UTC timezone - */ + * Process a date, converting it to RFC3339 format, setting the timezone to UTC and subtracting time padding + * from the config file. + * @param date source Date + * @param secondsPad number of seconds to subtract from the date + * @return a string in the format 'yyyy-mm-ddThh:mm:ssZ' and converted to UTC timezone + */ private String processDate(Date date, int secondsPad) { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - formatter.setTimeZone(TimeZone.getTimeZone("UTC")); + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + formatter.setTimeZone(TimeZone.getTimeZone("UTC")); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.add(Calendar.SECOND, -1*secondsPad); - date = calendar.getTime(); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.SECOND, -1*secondsPad); + date = calendar.getTime(); - return formatter.format(date); + return formatter.format(date); } /** * Query OAI-PMH server for the granularity of its datestamps. - * @throws TransformerException - * @throws SAXException - * @throws ParserConfigurationException * @throws IOException if IO error + * @throws SAXException if XML processing error + * @throws ParserConfigurationException XML parsing error + * @throws TransformerException if XML transformer error */ private String oaiGetDateGranularity(String oaiSource) throws IOException, ParserConfigurationException, SAXException, TransformerException { - Identify iden = new Identify(oaiSource); - return iden.getDocument().getElementsByTagNameNS(OAI_NS.getURI(), "granularity").item(0).getTextContent(); + Identify iden = new Identify(oaiSource); + return iden.getDocument().getElementsByTagNameNS(OAI_NS.getURI(), "granularity").item(0).getTextContent(); } /** @@ -740,28 +760,35 @@ public class OAIHarvester { * @param oaiSource the address of the OAI-PMH provider * @param MDNamespace the namespace that we are trying to resolve to the metadataPrefix * @return metadataPrefix the OAI-PMH provider has assigned to the supplied namespace + * + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws ParserConfigurationException XML parsing error + * @throws SAXException if XML processing error + * @throws TransformerException if XML transformer error + * @throws ConnectException if could not connect to OAI server */ public static String oaiResolveNamespaceToPrefix(String oaiSource, String MDNamespace) throws IOException, ParserConfigurationException, SAXException, TransformerException, ConnectException { - String metaPrefix = null; + String metaPrefix = null; - // Query the OAI server for the metadata - ListMetadataFormats lmf = new ListMetadataFormats(oaiSource); + // Query the OAI server for the metadata + ListMetadataFormats lmf = new ListMetadataFormats(oaiSource); - if (lmf != null) { - Document lmfResponse = db.build(lmf.getDocument()); - List mdFormats = lmfResponse.getRootElement().getChild("ListMetadataFormats", OAI_NS).getChildren("metadataFormat", OAI_NS); + if (lmf != null) { + Document lmfResponse = db.build(lmf.getDocument()); + List mdFormats = lmfResponse.getRootElement().getChild("ListMetadataFormats", OAI_NS).getChildren("metadataFormat", OAI_NS); - for (Element mdFormat : mdFormats) { - if (MDNamespace.equals(mdFormat.getChildText("metadataNamespace", OAI_NS))) - { - metaPrefix = mdFormat.getChildText("metadataPrefix", OAI_NS); - break; - } - } - } + for (Element mdFormat : mdFormats) { + if (MDNamespace.equals(mdFormat.getChildText("metadataNamespace", OAI_NS))) + { + metaPrefix = mdFormat.getChildText("metadataPrefix", OAI_NS); + break; + } + } + } - return metaPrefix; + return metaPrefix; } /** @@ -771,36 +798,36 @@ public class OAIHarvester { */ protected void alertAdmin(int status, Exception ex) { - try { - String recipient = configurationService.getProperty("alert.recipient"); + try { + String recipient = configurationService.getProperty("alert.recipient"); - if (StringUtils.isNotBlank(recipient)) { - Email email = Email.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "harvesting_error")); - email.addRecipient(recipient); - email.addArgument(targetCollection.getID()); - email.addArgument(new Date()); - email.addArgument(status); + if (StringUtils.isNotBlank(recipient)) { + Email email = Email.getEmail(I18nUtil.getEmailFilename(Locale.getDefault(), "harvesting_error")); + email.addRecipient(recipient); + email.addArgument(targetCollection.getID()); + email.addArgument(new Date()); + email.addArgument(status); - String stackTrace; + String stackTrace; - if (ex != null) { + if (ex != null) { email.addArgument(ex.getMessage()); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - ex.printStackTrace(pw); - pw.flush(); - stackTrace = sw.toString(); - } else { - stackTrace = "No exception"; - } + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + ex.printStackTrace(pw); + pw.flush(); + stackTrace = sw.toString(); + } else { + stackTrace = "No exception"; + } - email.addArgument(stackTrace); - email.send(); - } - } catch (Exception e) { - log.warn("Unable to send email alert", e); - } + email.addArgument(stackTrace); + email.send(); + } + } catch (Exception e) { + log.warn("Unable to send email alert", e); + } } @@ -812,24 +839,31 @@ public class OAIHarvester { * @param itemOaiId the OAI identifier of the target item * @param metadataPrefix the OAI metadataPrefix of the desired metadata * @return list of JDOM elements corresponding to the metadata entries in the located record. + * + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws ParserConfigurationException XML parsing error + * @throws SAXException if XML processing error + * @throws TransformerException if XML transformer error + * @throws HarvestingException if harvesting error */ protected List getMDrecord(String oaiSource, String itemOaiId, String metadataPrefix) throws IOException, ParserConfigurationException, SAXException, TransformerException, HarvestingException { - GetRecord getRecord = new GetRecord(oaiSource,itemOaiId,metadataPrefix); - Set errorSet = new HashSet(); - // If the metadata is not available for this item, can the whole thing - if (getRecord != null && getRecord.getErrors() != null && getRecord.getErrors().getLength() > 0) { - for (int i=0; i errorSet = new HashSet(); + // If the metadata is not available for this item, can the whole thing + if (getRecord != null && getRecord.getErrors() != null && getRecord.getErrors().getLength() > 0) { + for (int i=0; i verifyOAIharvester() { - String oaiSource = harvestRow.getOaiSource(); - String oaiSetId = harvestRow.getOaiSetId(); - String metaPrefix = harvestRow.getHarvestMetadataConfig(); + String oaiSource = harvestRow.getOaiSource(); + String oaiSetId = harvestRow.getOaiSetId(); + String metaPrefix = harvestRow.getHarvestMetadataConfig(); - return verifyOAIharvester(oaiSource, oaiSetId, metaPrefix, true); + return verifyOAIharvester(oaiSource, oaiSetId, metaPrefix, true); } /** * Verify the existence of an OAI server with the specified set and * supporting the provided metadata formats. * - * @param oaiSource the address of the OAI-PMH provider + * @param oaiSource + * the address of the OAI-PMH provider * @param oaiSetId + * OAI set identifier * @param metaPrefix + * OAI metadataPrefix * @param testORE whether the method should also check the PMH provider for ORE support * @return list of errors encountered during verification. Empty list indicates a "success" condition. */ public static List verifyOAIharvester(String oaiSource, String oaiSetId, String metaPrefix, boolean testORE) { - List errorSet = new ArrayList(); + List errorSet = new ArrayList(); // First, see if we can contact the target server at all. - try { - new Identify(oaiSource); - } - catch (Exception ex) { - errorSet.add(OAI_ADDRESS_ERROR + ": OAI server could not be reached."); - return errorSet; - } + try { + new Identify(oaiSource); + } + catch (Exception ex) { + errorSet.add(OAI_ADDRESS_ERROR + ": OAI server could not be reached."); + return errorSet; + } // Next, make sure the metadata we need is supported by the target server Namespace DMD_NS = OAIHarvester.getDMDNamespace(metaPrefix); @@ -883,30 +920,30 @@ public class OAIHarvester { try { OREOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, getORENamespace().getURI()); DMDOAIPrefix = OAIHarvester.oaiResolveNamespaceToPrefix(oaiSource, DMD_NS.getURI()); - } - catch (Exception ex) { + } + catch (Exception ex) { errorSet.add(OAI_ADDRESS_ERROR + ": OAI did not respond to ListMetadataFormats query (" + ORE_NS.getPrefix() + ":" + OREOAIPrefix + " ; " + DMD_NS.getPrefix() + ":" + DMDOAIPrefix + "): " + ex.getMessage()); return errorSet; - } + } - if (testORE && OREOAIPrefix == null) + if (testORE && OREOAIPrefix == null) { errorSet.add(OAI_ORE_ERROR + ": The OAI server does not support ORE dissemination"); } - if (DMDOAIPrefix == null) + if (DMDOAIPrefix == null) { errorSet.add(OAI_DMD_ERROR + ": The OAI server does not support dissemination in this format"); } - // Now scan the sets and make sure the one supplied is in the list - boolean foundSet = false; - try { + // Now scan the sets and make sure the one supplied is in the list + boolean foundSet = false; + try { //If we do not want to harvest from one set, then skip this. - if(!"all".equals(oaiSetId)){ + if (!"all".equals(oaiSetId)) { ListIdentifiers ls = new ListIdentifiers(oaiSource, null, null, oaiSetId, DMDOAIPrefix); // The only error we can really get here is "noSetHierarchy" @@ -928,7 +965,7 @@ public class OAIHarvester { } } } - } + } catch (RuntimeException re) { throw re; } diff --git a/dspace-api/src/main/java/org/dspace/harvest/service/HarvestSchedulingService.java b/dspace-api/src/main/java/org/dspace/harvest/service/HarvestSchedulingService.java index 0341385e78..9e2ba5d8fc 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/service/HarvestSchedulingService.java +++ b/dspace-api/src/main/java/org/dspace/harvest/service/HarvestSchedulingService.java @@ -22,24 +22,58 @@ public interface HarvestSchedulingService { /** * Start harvest scheduler. + * + * @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 startNewScheduler() throws SQLException, AuthorizeException; /** * Stop an active harvest scheduler. + * + * @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 stopScheduler() throws SQLException, AuthorizeException; /** - * Pause an active harvest scheduler. - */ + * Pause an active harvest scheduler. + * + * @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 pauseScheduler() throws SQLException, AuthorizeException; /** - * Resume a paused harvest scheduler. - */ + * Resume a paused harvest scheduler. + * + * @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 resumeScheduler() throws SQLException, AuthorizeException; - + /** + * + * + * @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. + */ void resetScheduler() throws SQLException, AuthorizeException, IOException; } diff --git a/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedCollectionService.java b/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedCollectionService.java index a02d723faf..e8a45e3bf7 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedCollectionService.java +++ b/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedCollectionService.java @@ -25,67 +25,126 @@ public interface HarvestedCollectionService { /** * Find the harvest settings corresponding to this collection * + * @param context + * The relevant DSpace Context. + * @param collection + * target collection * @return a HarvestInstance object corresponding to this collection's settings, null if not found. + * @throws SQLException if database error */ public HarvestedCollection find(Context context, Collection collection) throws SQLException; /** * Create a new harvest instance row for a specified collection. * + * @param context + * The relevant DSpace Context. + * @param collection + * target collection * @return a new HarvestInstance object + * @throws SQLException if database error */ public HarvestedCollection create(Context context, Collection collection) throws SQLException; - /** Returns whether the specified collection is harvestable, i.e. whether its harvesting + /** + * Returns whether the specified collection is harvestable, i.e. whether its harvesting * options are set up correctly. This is distinct from "ready", since this collection may * be in process of being harvested. + * + * @param context + * The relevant DSpace Context. + * @param collection + * target collection + * @return is collection harvestable? + * @throws SQLException if database error */ public boolean isHarvestable(Context context, Collection collection) throws SQLException; - /** Returns whether this harvest instance is actually harvestable, i.e. whether its settings + /** + * Returns whether this harvest instance is actually harvestable, i.e. whether its settings * options are set up correctly. This is distinct from "ready", since this collection may * be in process of being harvested. + * + * @param harvestedCollection + * collection to be harvested + * @return is collection harvestable? + * @throws SQLException if database error */ public boolean isHarvestable(HarvestedCollection harvestedCollection) throws SQLException; - /** Returns whether the specified collection is ready for immediate harvest. + /** + * Returns whether the specified collection is ready for immediate harvest. + * + * @param context + * The relevant DSpace Context. + * @param collection + * collection to be harvested + * @return is collection ready for immediate harvest? + * @throws SQLException if database error */ public boolean isReady(Context context, Collection collection) throws SQLException; + /** + * Returns whether the specified collection is ready for immediate harvest. + * + * @param harvestedCollection + * collection to be harvested + * @return is collection ready for immediate harvest? + * @throws SQLException if database error + */ public boolean isReady(HarvestedCollection harvestedCollection) throws SQLException; - /** Find all collections that are set up for harvesting + /** + * Find all collections that are set up for harvesting * - * return: list of collection id's + * @param context + * The relevant DSpace Context. + * @return list of collection id's * @throws SQLException if database error */ public List findAll(Context context) throws SQLException; - /** Find all collections that are ready for harvesting + /** + * Find all collections that are ready for harvesting * - * return: list of collection id's + * @param context + * The relevant DSpace Context. + * @return list of collection id's * @throws SQLException if database error */ public List findReady(Context context) throws SQLException; /** * Find all collections with the specified status flag. + * * @param context + * The relevant DSpace Context. * @param status see HarvestInstance.STATUS_... + * @return all collections with the specified status flag * @throws SQLException if database error */ public List findByStatus(Context context, int status) throws SQLException; - /** Find the collection that was harvested the longest time ago. + /** + * Find the collection that was harvested the longest time ago. + * + * @param context + * The relevant DSpace Context. + * @return collection that was harvested the longest time ago * @throws SQLException if database error */ - public HarvestedCollection findOldestHarvest (Context context) throws SQLException; + public HarvestedCollection findOldestHarvest(Context context) throws SQLException; - /** Find the collection that was harvested most recently. + /** + * Find the collection that was harvested most recently. + * + * @param context + * The relevant DSpace Context. + * @return collection that was harvested most recently * @throws SQLException if database error */ - public HarvestedCollection findNewestHarvest (Context context) throws SQLException; + public HarvestedCollection findNewestHarvest(Context context) throws SQLException; public void delete(Context context, HarvestedCollection harvestedCollection) throws SQLException; diff --git a/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedItemService.java b/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedItemService.java index 1ace182504..6c5f3bf06e 100644 --- a/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedItemService.java +++ b/dspace-api/src/main/java/org/dspace/harvest/service/HarvestedItemService.java @@ -25,7 +25,13 @@ public interface HarvestedItemService { /** * Find the harvest parameters corresponding to the specified DSpace item * + * @param context + * The relevant DSpace Context. + * @param item + * target item * @return a HarvestedItem object corresponding to this item, null if not found. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public HarvestedItem find(Context context, Item item) throws SQLException; @@ -33,16 +39,27 @@ public interface HarvestedItemService { * Retrieve a DSpace Item that corresponds to this particular combination of owning collection and OAI ID. * * @param context + * The relevant DSpace Context. * @param itemOaiID the string used by the OAI-PMH provider to identify the item * @param collection the local collection that the item should be found in * @return DSpace Item or null if no item was found + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public Item getItemByOAIId(Context context, String itemOaiID, Collection collection) throws SQLException; /** * Create a new harvested item row for a specified item id. * + * @param context + * The relevant DSpace Context. + * @param item + * target item + * @param itemOAIid + * the string used by the OAI-PMH provider to identify the item * @return a new HarvestedItem object + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public HarvestedItem create(Context context, Item item, String itemOAIid) throws SQLException; diff --git a/dspace-api/src/main/java/org/dspace/identifier/DOIIdentifierProvider.java b/dspace-api/src/main/java/org/dspace/identifier/DOIIdentifierProvider.java index 1e91297b71..85cb4a2edc 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/DOIIdentifierProvider.java +++ b/dspace-api/src/main/java/org/dspace/identifier/DOIIdentifierProvider.java @@ -34,7 +34,7 @@ import org.springframework.beans.factory.annotation.Required; * Provide service for DOIs using DataCite. * *

This class handles reservation, registration and deletion of DOIs using - * the direct API from {@link DataCite}. + * the direct API from DataCite. * Please pay attention that some members of DataCite offer special services * and want their customers to use special APIs. If you are unsure ask your * registration agency.

@@ -228,17 +228,17 @@ public class DOIIdentifierProvider /** * @param context + * The relevant DSpace Context. * @param dso DSpaceObject the DOI should be reserved for. Some metadata of - * this object will be send to the registration agency. + * this object will be send to the registration agency. * @param identifier DOI to register in a format that - * {@link org.dspace.identifier.service.DOIService#formatIdentifier(String)} accepts. + * {@link org.dspace.identifier.service.DOIService#formatIdentifier(String)} accepts. * @throws IdentifierException If the format of {@code identifier} was - * unrecognized or if it was impossible to - * reserve the DOI (registration agency denied - * for some reason, see logs). + * unrecognized or if it was impossible to + * reserve the DOI (registration agency denied + * for some reason, see logs). * @throws IllegalArgumentException If {@code identifier} is a DOI already - * registered for another DSpaceObject then - * {@code dso}. + * registered for another DSpaceObject then {@code dso}. * @see org.dspace.identifier.IdentifierProvider#reserve(Context, DSpaceObject, String) */ @Override @@ -694,12 +694,13 @@ public class DOIIdentifierProvider /** * Returns a DSpaceObject depending on its DOI. - * @param context the context + * @param context + * The relevant DSpace Context. * @param identifier The DOI in a format that is accepted by - * {@link org.dspace.identifier.service.DOIService#formatIdentifier(String)}. + * {@link org.dspace.identifier.service.DOIService#formatIdentifier(String)}. * @return Null if the DOI couldn't be found or the associated DSpaceObject. * @throws SQLException if database error - * @throws IdentifierException If {@code identifier} is null or an empty string. + * @throws DOIIdentifierException If {@code identifier} is null or an empty string. * @throws IllegalArgumentException If the identifier couldn't be recognized as DOI. */ public DSpaceObject getObjectByDOI(Context context, String identifier) @@ -728,8 +729,10 @@ public class DOIIdentifierProvider * Search the database for a DOI, using the type and id of an DSpaceObject. * * @param context - * @param dso DSpaceObject to find doi for. DOIs with status TO_BE_DELETED will be - * ignored. + * The relevant DSpace Context. + * @param dso + * DSpaceObject to find doi for. DOIs with status TO_BE_DELETED will be + * ignored. * @return The DOI as String or null if DOI was not found. * @throws SQLException if database error */ @@ -764,6 +767,7 @@ public class DOIIdentifierProvider * DOI is in a decent format, use DOI.formatIdentifier(String) if necessary. * * @param context + * The relevant DSpace Context. * @param dso The DSpaceObject the DOI should be loaded or created for. * @param doiIdentifier A DOI or null if a DOI should be generated. The generated DOI * can be found in the appropriate column for the TableRow. @@ -860,7 +864,9 @@ public class DOIIdentifierProvider /** * Loads a DOI out of the metadata of an DSpaceObject. * @param dso + * DSpace object to get DOI metadata from * @return The DOI or null if no DOI was found. + * @throws DOIIdentifierException if identifier error */ public String getDOIOutOfObject(DSpaceObject dso) throws DOIIdentifierException { @@ -886,10 +892,12 @@ public class DOIIdentifierProvider * Adds a DOI to the metadata of an item. * * @param context + * The relevant DSpace Context. * @param dso DSpaceObject the DOI should be added to. * @param doi The DOI that should be added as metadata. * @throws SQLException if database error * @throws AuthorizeException if authorization error + * @throws IdentifierException if identifier error */ protected void saveDOIToObject(Context context, DSpaceObject dso, String doi) throws SQLException, AuthorizeException, IdentifierException @@ -917,10 +925,12 @@ public class DOIIdentifierProvider * Removes a DOI out of the metadata of a DSpaceObject. * * @param context + * The relevant DSpace Context. * @param dso The DSpaceObject the DOI should be removed from. * @param doi The DOI to remove out of the metadata. * @throws AuthorizeException if authorization error * @throws SQLException if database error + * @throws IdentifierException if identifier error */ protected void removeDOIFromObject(Context context, DSpaceObject dso, String doi) throws AuthorizeException, SQLException, IdentifierException diff --git a/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java b/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java index c1aad0244b..c4ffefd85f 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java +++ b/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java @@ -654,6 +654,7 @@ public class EZIDIdentifierProvider * generation of EZID metadata for the minting of new identifiers. * * @param aCrosswalk + * map of metadata fields to EZID keys */ @Required public void setCrosswalk(Map aCrosswalk) @@ -670,6 +671,7 @@ public class EZIDIdentifierProvider * values to something acceptable to EZID. * * @param transformMap + * map of metadata fields to EZID transformation classes */ public void setCrosswalkTransform(Map transformMap) { @@ -698,7 +700,7 @@ public class EZIDIdentifierProvider /** * Method should never be used aside from the unit tests where we can cannot autowire this class. - * @param itemService + * @param itemService itemService instance */ protected void setItemService(ItemService itemService){ this.itemService = itemService; diff --git a/dspace-api/src/main/java/org/dspace/identifier/HandleIdentifierProvider.java b/dspace-api/src/main/java/org/dspace/identifier/HandleIdentifierProvider.java index 8f02b9c5ff..fb6743e5e5 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/HandleIdentifierProvider.java +++ b/dspace-api/src/main/java/org/dspace/identifier/HandleIdentifierProvider.java @@ -81,7 +81,7 @@ public class HandleIdentifierProvider extends IdentifierProvider { @Override public String register(Context context, DSpaceObject dso) { - try{ + try { String id = mint(context, dso); // move canonical to point the latest version @@ -92,7 +92,7 @@ public class HandleIdentifierProvider extends IdentifierProvider { } return id; - }catch (Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e); } @@ -100,14 +100,14 @@ public class HandleIdentifierProvider extends IdentifierProvider { @Override public void register(Context context, DSpaceObject dso, String identifier) { - try{ + try { handleService.createHandle(context, dso, identifier); if(dso instanceof Item) { Item item = (Item)dso; populateHandleMetadata(context, item, identifier); } - }catch (Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e); } @@ -116,9 +116,9 @@ public class HandleIdentifierProvider extends IdentifierProvider { @Override public void reserve(Context context, DSpaceObject dso, String identifier) { - try{ + try { handleService.createHandle(context, dso, identifier); - }catch(Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); } @@ -131,7 +131,6 @@ public class HandleIdentifierProvider extends IdentifierProvider { * @param context DSpace context * @param dso The DSpaceObject to create a handle for * @return The newly created handle - * @exception java.sql.SQLException If a database error occurs */ @Override public String mint(Context context, DSpaceObject dso) { @@ -140,9 +139,9 @@ public class HandleIdentifierProvider extends IdentifierProvider { return dso.getHandle(); } - try{ + try { return handleService.createHandle(context, dso); - }catch (Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); } @@ -154,7 +153,7 @@ public class HandleIdentifierProvider extends IdentifierProvider { try { return handleService.resolveToObject(context, identifier); - }catch (Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier), e); } // throw new IllegalStateException("Unsupported Handle Type " @@ -168,7 +167,7 @@ public class HandleIdentifierProvider extends IdentifierProvider { try { return handleService.findHandle(context, dso); - }catch(SQLException sqe){ + } catch (SQLException sqe) { throw new IdentifierNotResolvableException(sqe.getMessage(),sqe); } } @@ -180,9 +179,9 @@ public class HandleIdentifierProvider extends IdentifierProvider { @Override public void delete(Context context, DSpaceObject dso) throws IdentifierException { - try{ + try { handleService.unbindHandle(context, dso); - }catch(SQLException sqe) + } catch (SQLException sqe) { throw new IdentifierException(sqe.getMessage(),sqe); } diff --git a/dspace-api/src/main/java/org/dspace/identifier/IdentifierProvider.java b/dspace-api/src/main/java/org/dspace/identifier/IdentifierProvider.java index 9771e4f0f1..830875a182 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/IdentifierProvider.java +++ b/dspace-api/src/main/java/org/dspace/identifier/IdentifierProvider.java @@ -55,11 +55,9 @@ public abstract class IdentifierProvider { /** * Create and apply an identifier to a DSpaceObject. - * If you just mark an identifier for an asynchronous registration, please call - * {@link org.dspace.content.DSpaceObject#resetIdentifiersCache()} after its registration. If you register - * identifiers directly in this method the IdentifierService will call this method for you. * * @param context + * The relevant DSpace Context. * @param item object to be named. * @return existing identifier of {@code item} if it has one, else a new identifier. * @throws IdentifierException if identifier error @@ -70,6 +68,7 @@ public abstract class IdentifierProvider { * Create an identifier for a DSpaceObject. * * @param context + * The relevant DSpace Context. * @param dso object to be named. * @return existing identifier of {@code dso} if it has one, else a new identifier. * @throws IdentifierException if identifier error @@ -80,6 +79,7 @@ public abstract class IdentifierProvider { * Find the object named by a given identifier. * * @param context + * The relevant DSpace Context. * @param identifier to be resolved. * @param attributes additional information for resolving {@code identifier}. * @return the named object. @@ -92,6 +92,7 @@ public abstract class IdentifierProvider { * Return the identifier for a DSpaceObject. * * @param context + * The relevant DSpace Context. * @param object The object to be looked up. * @return identifier for {@code object}. * @throws IdentifierNotFoundException if identifier not found @@ -103,6 +104,7 @@ public abstract class IdentifierProvider { * Unbind this type of identifier(s) from an object. * * @param context + * The relevant DSpace Context. * @param dso object to lose its identity. * @throws IdentifierException if identifier error */ @@ -112,6 +114,7 @@ public abstract class IdentifierProvider { * Unbind the given identifier from an object. * * @param context + * The relevant DSpace Context. * @param dso object to be de-identified. * @param identifier to be removed. * @throws IdentifierException if identifier error @@ -122,6 +125,7 @@ public abstract class IdentifierProvider { * Set an object's identifier. * * @param context + * The relevant DSpace Context. * @param dso object to be identified. * @param identifier to be set on the object. * @throws IdentifierException if identifier error @@ -132,6 +136,7 @@ public abstract class IdentifierProvider { * Create a specific identifier and apply it to an object. * * @param context + * The relevant DSpace Context. * @param object to be identified. * @param identifier to be created. * @throws IdentifierException if identifier error diff --git a/dspace-api/src/main/java/org/dspace/identifier/IdentifierServiceImpl.java b/dspace-api/src/main/java/org/dspace/identifier/IdentifierServiceImpl.java index 3fc049f584..65b97f4c75 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/IdentifierServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/identifier/IdentifierServiceImpl.java @@ -48,16 +48,16 @@ public class IdentifierServiceImpl implements IdentifierService { } @Autowired - @Required - public void setProviders(List providers) - { - this.providers = providers; - - for(IdentifierProvider p : providers) - { - p.setParentService(this); - } - } + @Required + public void setProviders(List providers) + { + this.providers = providers; + + for (IdentifierProvider p : providers) + { + p.setParentService(this); + } + } /** * Reserves identifiers for the item @@ -65,7 +65,9 @@ public class IdentifierServiceImpl implements IdentifierService { * @param dso dspace object */ @Override - public void reserve(Context context, DSpaceObject dso) throws AuthorizeException, SQLException, IdentifierException { + public void reserve(Context context, DSpaceObject dso) + throws AuthorizeException, SQLException, IdentifierException + { for (IdentifierProvider service : providers) { String identifier = service.mint(context, dso); @@ -79,11 +81,13 @@ public class IdentifierServiceImpl implements IdentifierService { } @Override - public void reserve(Context context, DSpaceObject dso, String identifier) throws AuthorizeException, SQLException, IdentifierException { + public void reserve(Context context, DSpaceObject dso, String identifier) + throws AuthorizeException, SQLException, IdentifierException + { // Next resolve all other services for (IdentifierProvider service : providers) { - if(service.supports(identifier)) + if (service.supports(identifier)) { service.reserve(context, dso, identifier); } @@ -93,7 +97,9 @@ public class IdentifierServiceImpl implements IdentifierService { } @Override - public void register(Context context, DSpaceObject dso) throws AuthorizeException, SQLException, IdentifierException { + public void register(Context context, DSpaceObject dso) + throws AuthorizeException, SQLException, IdentifierException + { //We need to commit our context because one of the providers might require the handle created above // Next resolve all other services for (IdentifierProvider service : providers) @@ -105,8 +111,9 @@ public class IdentifierServiceImpl implements IdentifierService { } @Override - public void register(Context context, DSpaceObject object, String identifier) throws AuthorizeException, SQLException, IdentifierException { - + public void register(Context context, DSpaceObject object, String identifier) + throws AuthorizeException, SQLException, IdentifierException + { //We need to commit our context because one of the providers might require the handle created above // Next resolve all other services boolean registered = false; @@ -128,10 +135,11 @@ public class IdentifierServiceImpl implements IdentifierService { } @Override - public String lookup(Context context, DSpaceObject dso, Class identifier) { + public String lookup(Context context, DSpaceObject dso, Class identifier) + { for (IdentifierProvider service : providers) { - if(service.supports(identifier)) + if (service.supports(identifier)) { try{ String result = service.lookup(context, dso); @@ -223,10 +231,12 @@ public class IdentifierServiceImpl implements IdentifierService { } @Override - public DSpaceObject resolve(Context context, String identifier) throws IdentifierNotFoundException, IdentifierNotResolvableException{ + public DSpaceObject resolve(Context context, String identifier) + throws IdentifierNotFoundException, IdentifierNotResolvableException + { for (IdentifierProvider service : providers) { - if(service.supports(identifier)) + if (service.supports(identifier)) { try { DSpaceObject result = service.resolve(context, identifier); @@ -253,7 +263,9 @@ public class IdentifierServiceImpl implements IdentifierService { } @Override - public void delete(Context context, DSpaceObject dso) throws AuthorizeException, SQLException, IdentifierException { + public void delete(Context context, DSpaceObject dso) + throws AuthorizeException, SQLException, IdentifierException + { for (IdentifierProvider service : providers) { try @@ -266,12 +278,14 @@ public class IdentifierServiceImpl implements IdentifierService { } @Override - public void delete(Context context, DSpaceObject dso, String identifier) throws AuthorizeException, SQLException, IdentifierException { + public void delete(Context context, DSpaceObject dso, String identifier) + throws AuthorizeException, SQLException, IdentifierException + { for (IdentifierProvider service : providers) { try { - if(service.supports(identifier)) + if (service.supports(identifier)) { service.delete(context, dso, identifier); } diff --git a/dspace-api/src/main/java/org/dspace/identifier/VersionedHandleIdentifierProviderWithCanonicalHandles.java b/dspace-api/src/main/java/org/dspace/identifier/VersionedHandleIdentifierProviderWithCanonicalHandles.java index 68782cc2a2..1e912a80b7 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/VersionedHandleIdentifierProviderWithCanonicalHandles.java +++ b/dspace-api/src/main/java/org/dspace/identifier/VersionedHandleIdentifierProviderWithCanonicalHandles.java @@ -67,7 +67,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident @Override public boolean supports(String identifier) { - String prefix = handleService.getPrefix(); + String prefix = handleService.getPrefix(); String canonicalPrefix = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("handle.canonical.prefix"); if (identifier == null) { @@ -86,7 +86,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident //Check additional prefixes supported in the config file String[] additionalPrefixes = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("handle.additional.prefixes"); - for(String additionalPrefix: additionalPrefixes) { + for (String additionalPrefix: additionalPrefixes) { if (identifier.startsWith(additionalPrefix + "/")) { return true; } @@ -102,7 +102,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident String id = mint(context, dso); // move canonical to point the latest version - if(dso != null && dso.getType() == Constants.ITEM) + if (dso != null && dso.getType() == Constants.ITEM) { Item item = (Item)dso; VersionHistory history = null; @@ -111,7 +111,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident } catch (SQLException ex) { throw new RuntimeException("A problem with the database connection occured.", ex); } - if(history!=null) + if (history!=null) { String canonical = getCanonical(context, item); @@ -203,7 +203,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident // trying to restore the latest version the identifier in input doesn't have the for 1234/123.latestVersion // it is the canonical 1234/123 VersionHistory itemHistory = getHistory(context, identifier); - if(!identifier.matches(".*/.*\\.\\d+") && itemHistory!=null){ + if (!identifier.matches(".*/.*\\.\\d+") && itemHistory!=null) { int newVersionNumber = versionHistoryService.getLatestVersion(context, itemHistory).getVersionNumber()+1; String canonical = identifier; @@ -211,18 +211,18 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident restoreItAsVersion(context, dso, identifier, item, canonical, itemHistory); } // if identifier == 1234.5/100.4 reinstate the version 4 in the version table if absent - else if(identifier.matches(".*/.*\\.\\d+")) + else if (identifier.matches(".*/.*\\.\\d+")) { // if it is a version of an item is needed to put back the record // in the versionitem table String canonical = getCanonical(identifier); DSpaceObject canonicalItem = this.resolve(context, canonical); - if(canonicalItem==null){ + if (canonicalItem==null) { restoreItAsCanonical(context, dso, identifier, item, canonical); } - else{ + else { VersionHistory history = versionHistoryService.findByItem(context, (Item) canonicalItem); - if(history==null){ + if (history==null) { restoreItAsCanonical(context, dso, identifier, item, canonical); } else @@ -236,12 +236,12 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident { //A regular handle createNewIdentifier(context, dso, identifier); - if(dso instanceof Item) + if (dso instanceof Item) { modifyHandleMetadata(context, item, getCanonical(identifier)); } } - }catch (Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID(), e); } @@ -249,7 +249,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident protected VersionHistory getHistory(Context context, String identifier) throws SQLException { DSpaceObject item = this.resolve(context, identifier); - if(item!=null){ + if (item!=null) { VersionHistory history = versionHistoryService.findByItem(context, (Item) item); return history; } @@ -268,7 +268,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident // if restoring the lastest version: needed to move the canonical - if(latest.getVersionNumber() < versionNumber){ + if (latest.getVersionNumber() < versionNumber) { handleService.modifyHandleDSpaceObject(context, canonical, dso); } } @@ -292,7 +292,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident { try{ handleService.createHandle(context, dso, identifier); - }catch(Exception e){ + } catch(Exception e) { log.error(LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); } @@ -309,27 +309,27 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident @Override public String mint(Context context, DSpaceObject dso) { - if(dso.getHandle() != null) + if (dso.getHandle() != null) { return dso.getHandle(); } - try{ + try { String handleId = null; VersionHistory history = null; - if(dso instanceof Item) + if (dso instanceof Item) { history = versionHistoryService.findByItem(context, (Item) dso); } - if(history!=null) + if (history!=null) { handleId = makeIdentifierBasedOnHistory(context, dso, history); - }else{ + } else { handleId = createNewIdentifier(context, dso, null); } return handleId; - }catch (Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while attempting to create handle", "Item id: " + dso.getID()), e); throw new RuntimeException("Error while attempting to create identifier for Item id: " + dso.getID()); } @@ -339,9 +339,9 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident public DSpaceObject resolve(Context context, String identifier, String... attributes) { // We can do nothing with this, return null - try{ + try { return handleService.resolveToObject(context, identifier); - }catch (Exception e){ + } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while resolving handle to item", "handle: " + identifier), e); } return null; @@ -353,7 +353,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident try { return handleService.findHandle(context, dso); - }catch(SQLException sqe){ + } catch(SQLException sqe) { throw new IdentifierNotResolvableException(sqe.getMessage(),sqe); } } @@ -373,7 +373,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident // If it is the most current version occurs to move the canonical to the previous version VersionHistory history = versionHistoryService.findByItem(context, item); - if(history!=null && versionHistoryService.getLatestVersion(context, history).getItem().equals(item) + if (history!=null && versionHistoryService.getLatestVersion(context, history).getItem().equals(item) && versionService.getVersionsByHistory(context, history).size() > 1) { Item previous; @@ -437,10 +437,10 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident } protected String createNewIdentifier(Context context, DSpaceObject dso, String handleId) throws SQLException { - if(handleId == null) + if (handleId == null) { return handleService.createHandle(context, dso); - }else{ + } else { return handleService.createHandle(context, dso, handleId); } } @@ -467,7 +467,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident // add a new Identifier for previous item: 12345/100.1 String identifierPreviousItem=canonical + DOT + previous.getVersionNumber(); //Make sure that this hasn't happened already - if(handleService.resolveToObject(context, identifierPreviousItem) == null) + if (handleService.resolveToObject(context, identifierPreviousItem) == null) { handleService.createHandle(context, previous.getItem(), identifierPreviousItem, true); } @@ -476,10 +476,10 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident // add a new Identifier for this item: 12345/100.x String idNew = canonical + DOT + version.getVersionNumber(); //Make sure we don't have an old handle hanging around (if our previous version was deleted in the workspace) - if(handleService.resolveToObject(context, idNew) == null) + if (handleService.resolveToObject(context, idNew) == null) { handleService.createHandle(context, dso, idNew); - }else{ + } else { handleService.modifyHandleDSpaceObject(context, idNew, dso); } @@ -489,7 +489,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident protected String getCanonical(Context context, Item item) { String canonical = item.getHandle(); - if( canonical.matches(".*/.*\\.\\d+") && canonical.lastIndexOf(DOT)!=-1) + if ( canonical.matches(".*/.*\\.\\d+") && canonical.lastIndexOf(DOT)!=-1) { canonical = canonical.substring(0, canonical.lastIndexOf(DOT)); } @@ -500,7 +500,7 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident protected String getCanonical(String identifier) { String canonical = identifier; - if( canonical.matches(".*/.*\\.\\d+") && canonical.lastIndexOf(DOT)!=-1) + if ( canonical.matches(".*/.*\\.\\d+") && canonical.lastIndexOf(DOT)!=-1) { canonical = canonical.substring(0, canonical.lastIndexOf(DOT)); } @@ -510,9 +510,13 @@ public class VersionedHandleIdentifierProviderWithCanonicalHandles extends Ident /** * Remove all handles from an item's metadata and add the supplied handle instead. + * * @param context + * The relevant DSpace Context. * @param item + * which item to modify * @param handle + * which handle to add * @throws SQLException if database error * @throws AuthorizeException if authorization error */ diff --git a/dspace-api/src/main/java/org/dspace/identifier/doi/DOIConnector.java b/dspace-api/src/main/java/org/dspace/identifier/doi/DOIConnector.java index 286a24d8d8..b2d9fa97b2 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/doi/DOIConnector.java +++ b/dspace-api/src/main/java/org/dspace/identifier/doi/DOIConnector.java @@ -40,7 +40,9 @@ public interface DOIConnector { * to inactive.

* * @param context + * The relevant DSpace Context. * @param doi + * DOI string to "delete" * @throws DOIIdentifierException if DOI error */ public void deleteDOI(Context context, String doi) @@ -56,8 +58,11 @@ public interface DOIConnector { * DOIIdentifierException.DOI_ALREADY_EXISTS}. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to associate to the DOI * @param doi + * DOI string to reserve * @throws DOIIdentifierException if DOI error */ public void reserveDOI(Context context, DSpaceObject dso, String doi) @@ -74,8 +79,11 @@ public interface DOIConnector { * {@code DOIIdentifierException.RESERVE_FIRST}. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to associate to the DOI * @param doi + * DOI string to register * @throws DOIIdentifierException if DOI error */ public void registerDOI(Context context, DSpaceObject dso, String doi) @@ -88,8 +96,11 @@ public interface DOIConnector { * for the specified DSpace Object before it sends the metadata update. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object associated to the DOI * @param doi + * DOI string to update (metadata) * @throws DOIIdentifierException if DOI error */ public void updateMetadata(Context context, DSpaceObject dso, String doi) diff --git a/dspace-api/src/main/java/org/dspace/identifier/doi/DOIOrganiser.java b/dspace-api/src/main/java/org/dspace/identifier/doi/DOIOrganiser.java index 47b97e3cc1..00beedf11e 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/doi/DOIOrganiser.java +++ b/dspace-api/src/main/java/org/dspace/identifier/doi/DOIOrganiser.java @@ -730,6 +730,7 @@ public class DOIOrganiser { * @throws IllegalStateException If the identifier was a valid DOI that is * not stored in our database or if it is a handle that is not bound to an * DSpaceObject. + * @throws IdentifierException if identifier error */ public DOI resolveToDOI(String identifier) throws SQLException, IllegalArgumentException, IllegalStateException, IdentifierException diff --git a/dspace-api/src/main/java/org/dspace/identifier/doi/DataCiteConnector.java b/dspace-api/src/main/java/org/dspace/identifier/doi/DataCiteConnector.java index 959b6991d1..44202437f5 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/doi/DataCiteConnector.java +++ b/dspace-api/src/main/java/org/dspace/identifier/doi/DataCiteConnector.java @@ -747,9 +747,12 @@ implements DOIConnector } /** + * Internal method to send requests prepared by the caller to DataCite. * * @param req + * Extended version of the HttpRequest interface that provides convenience methods to access request properties such as request URI and method type. * @param doi + * DOI string to operate on * @return response from DataCite * @throws DOIIdentifierException if DOI error */ diff --git a/dspace-api/src/main/java/org/dspace/identifier/doi/package-info.java b/dspace-api/src/main/java/org/dspace/identifier/doi/package-info.java index defc49a4eb..e92170daf0 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/doi/package-info.java +++ b/dspace-api/src/main/java/org/dspace/identifier/doi/package-info.java @@ -17,6 +17,6 @@ * An operation returns an {@link org.dspace.identifier.ezid.EZIDResponse} which * gives easy access to EZID's status code and value, status of the underlying * HTTP request, and key/value pairs found in the response body (if any). - *

+ *

*/ package org.dspace.identifier.doi; diff --git a/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequest.java b/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequest.java index 589633358a..ce6cbb4f1b 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequest.java +++ b/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequest.java @@ -140,9 +140,12 @@ public class EZIDRequest /** * Fetch the metadata bound to an identifier. * + * @param name + * identifier name + * @return Decoded response data evoked by a request made to EZID. * @throws IdentifierException if the response is error or body malformed. * @throws IOException if the HTTP request fails. - * @throws URISyntaxException + * @throws URISyntaxException if host or authority is bad. */ public EZIDResponse lookup(String name) throws IdentifierException, IOException, URISyntaxException @@ -161,8 +164,13 @@ public class EZIDRequest * request path. Note: to "reserve" a given identifier, include "_status = * reserved" in {@code metadata}. * + * @param name + * identifier name * @param metadata ANVL-encoded key/value pairs. * @return Decoded response data evoked by a request made to EZID. + * @throws IdentifierException if the response is error or body malformed. + * @throws IOException if the HTTP request fails. + * @throws URISyntaxException if host or authority is bad. */ public EZIDResponse create(String name, Map metadata) throws IOException, IdentifierException, URISyntaxException @@ -186,6 +194,9 @@ public class EZIDRequest * * @param metadata ANVL-encoded key/value pairs. * @return Decoded response data evoked by a request made to EZID. + * @throws IdentifierException if the response is error or body malformed. + * @throws IOException if the HTTP request fails. + * @throws URISyntaxException if host or authority is bad. */ public EZIDResponse mint(Map metadata) throws IOException, IdentifierException, URISyntaxException @@ -207,9 +218,15 @@ public class EZIDRequest /** * Alter the metadata bound to an identifier. * - * @param metadata fields to be altered. Leave the value of a field's empty - * to delete the field. + * @param name + * identifier name + * @param metadata + * metadata fields to be altered. Leave the value of a field's empty + * to delete the field. * @return Decoded response data evoked by a request made to EZID. + * @throws IdentifierException if the response is error or body malformed. + * @throws IOException if the HTTP request fails. + * @throws URISyntaxException if host or authority is bad. */ public EZIDResponse modify(String name, Map metadata) throws IOException, IdentifierException, URISyntaxException @@ -230,6 +247,13 @@ public class EZIDRequest /** * Destroy a reserved identifier. Fails if ID was ever public. + * + * @param name + * identifier name + * @return Decoded response data evoked by a request made to EZID. + * @throws IdentifierException if the response is error or body malformed. + * @throws IOException if the HTTP request fails. + * @throws URISyntaxException if host or authority is bad. */ public EZIDResponse delete(String name) throws IOException, IdentifierException, URISyntaxException @@ -245,6 +269,13 @@ public class EZIDRequest /** * Remove a public identifier from view. + * + * @param name + * identifier name + * @return Decoded response data evoked by a request made to EZID. + * @throws IdentifierException if the response is error or body malformed. + * @throws IOException if the HTTP request fails. + * @throws URISyntaxException if host or authority is bad. */ public EZIDResponse withdraw(String name) throws IOException, IdentifierException, URISyntaxException @@ -257,7 +288,14 @@ public class EZIDRequest /** * Remove a public identifier from view, with a reason. * - * @param reason annotation for the item's unavailability. + * @param name + * identifier name + * @param reason + * annotation for the item's unavailability. + * @return Decoded response data evoked by a request made to EZID. + * @throws IdentifierException if the response is error or body malformed. + * @throws IOException if the HTTP request fails. + * @throws URISyntaxException if host or authority is bad. */ public EZIDResponse withdraw(String name, String reason) throws IOException, IdentifierException, URISyntaxException @@ -269,6 +307,9 @@ public class EZIDRequest /** * Create ANVL-formatted name/value pairs from a Map. + * + * @param raw + * */ private static String formatMetadata(Map raw) { diff --git a/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequestFactory.java b/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequestFactory.java index 19c0e98172..58e1701344 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequestFactory.java +++ b/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDRequestFactory.java @@ -39,7 +39,8 @@ public class EZIDRequestFactory * @param authority our DOI authority number. * @param username EZID user name. * @param password {@code username}'s password. - * @throws URISyntaxException + * @return a new EZID request with the given parameters + * @throws URISyntaxException if host or authority is bad. */ public EZIDRequest getInstance(String authority, String username, String password) throws URISyntaxException diff --git a/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDResponse.java b/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDResponse.java index 1f2af8d523..1c1e37ea54 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDResponse.java +++ b/dspace-api/src/main/java/org/dspace/identifier/ezid/EZIDResponse.java @@ -123,6 +123,8 @@ public class EZIDResponse /** * Value associated with the EZID status (identifier, error text, etc.). + * + * @return EZID status value */ public String getEZIDStatusValue() { diff --git a/dspace-api/src/main/java/org/dspace/identifier/ezid/Transform.java b/dspace-api/src/main/java/org/dspace/identifier/ezid/Transform.java index f57aee0e48..6970523825 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/ezid/Transform.java +++ b/dspace-api/src/main/java/org/dspace/identifier/ezid/Transform.java @@ -17,6 +17,11 @@ public interface Transform { /** * Convert the input form to the desired output form. + * @param from + * input form to transform from + * @return transformed output form + * @throws Exception + * A general exception */ public String transform(String from) throws Exception; diff --git a/dspace-api/src/main/java/org/dspace/identifier/service/IdentifierService.java b/dspace-api/src/main/java/org/dspace/identifier/service/IdentifierService.java index ad0d9d65bb..97b83f788b 100644 --- a/dspace-api/src/main/java/org/dspace/identifier/service/IdentifierService.java +++ b/dspace-api/src/main/java/org/dspace/identifier/service/IdentifierService.java @@ -32,6 +32,7 @@ public interface IdentifierService { * with a given Identifier type. * * @param context + * The relevant DSpace Context. * @param dso the object to be identified. * @param identifier instance of an Identifier of the required type. * @return the matching identifier, or the site identifier if the object @@ -44,6 +45,7 @@ public interface IdentifierService { * to lookup the provided DSpaceObject. * * @param context + * The relevant DSpace Context. * @param dso the object to be identified. * @return the matching identifiers, or the site identifier if the object * is a Site, or an empty array if no matching identifier is found. @@ -60,7 +62,10 @@ public interface IdentifierService { * TODO: Verify null is returned. * * @param context + * The relevant DSpace Context. * @param identifier + * instance of an Identifier of the required type. + * @return the DSpace object associated with the identifier * @throws IdentifierNotFoundException if identifier not found * @throws IdentifierNotResolvableException if identifier not resolvable */ @@ -71,7 +76,9 @@ public interface IdentifierService { * Reserves any identifiers necessary based on the capabilities of all providers in the service. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to be reserved * @throws AuthorizeException if authorization error * @throws SQLException if database error * @throws IdentifierException if identifier error @@ -85,8 +92,11 @@ public interface IdentifierService { * can process the same identifier. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to be reserved * @param identifier + * instance of an Identifier of the required type. * @throws AuthorizeException if authorization error * @throws SQLException if database error * @throws IdentifierException if identifier error @@ -96,7 +106,9 @@ public interface IdentifierService { /** * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to be registered * @throws AuthorizeException if authorization error * @throws SQLException if database error * @throws IdentifierException if identifier error @@ -111,8 +123,11 @@ public interface IdentifierService { * can process the same identifier. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to be registered * @param identifier + * instance of an Identifier of the required type. * @throws AuthorizeException if authorization error * @throws SQLException if database error * @throws IdentifierException if identifier error @@ -124,7 +139,9 @@ public interface IdentifierService { * all providers in no particular order. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to be deleted * @throws AuthorizeException if authorization error * @throws SQLException if database error * @throws IdentifierException if identifier error @@ -137,8 +154,11 @@ public interface IdentifierService { * can process the same identifier. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to be deleted * @param identifier + * instance of an Identifier of the required type. * @throws AuthorizeException if authorization error * @throws SQLException if database error * @throws IdentifierException if identifier error diff --git a/dspace-api/src/main/java/org/dspace/importer/external/datamodel/ImportRecord.java b/dspace-api/src/main/java/org/dspace/importer/external/datamodel/ImportRecord.java index 516b612104..e20c8b47e5 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/datamodel/ImportRecord.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/datamodel/ImportRecord.java @@ -24,6 +24,7 @@ public class ImportRecord { /** * Retrieve an unmodifiableList of MetadatumDTO + * * @return List of MetadatumDTO */ public List getValueList() { @@ -32,7 +33,9 @@ public class ImportRecord { /** * Create an ImportRecord instance initialized with a List of MetadatumDTO objects + * * @param valueList + * list of metadata values */ public ImportRecord(List valueList) { //don't want to alter the original list. Also now I can control the type of list @@ -51,7 +54,7 @@ public class ImportRecord { final StringBuilder sb = new StringBuilder(); sb.append("Record"); sb.append("{valueList="); - for(MetadatumDTO val:valueList){ + for (MetadatumDTO val:valueList) { sb.append("{"); sb.append(val.getSchema()); sb.append("; "); @@ -72,18 +75,18 @@ public class ImportRecord { /** * Return the MetadatumDTO's that are related to a given schema/element/qualifier pair/triplet - * @param schema - * @param element - * @param qualifier + * @param schema metadata field schema + * @param element metadata field element + * @param qualifier metadata field qualifier * @return the MetadatumDTO's that are related to a given schema/element/qualifier pair/triplet */ - public Collection getValue(String schema, String element, String qualifier){ - List values=new LinkedList(); - for(MetadatumDTO value:valueList){ - if(value.getSchema().equals(schema)&&value.getElement().equals(element)){ - if(qualifier==null&&value.getQualifier()==null){ + public Collection getValue(String schema, String element, String qualifier) { + List values = new LinkedList(); + for (MetadatumDTO value:valueList) { + if (value.getSchema().equals(schema)&&value.getElement().equals(element)) { + if (qualifier==null && value.getQualifier() == null) { values.add(value); - } else if (value.getQualifier()!=null&&value.getQualifier().equals(qualifier)) { + } else if (value.getQualifier() != null && value.getQualifier().equals(qualifier)) { values.add(value); } } @@ -95,7 +98,7 @@ public class ImportRecord { * Add a value to the valueList * @param value The MetadatumDTO to add to the valueList */ - public void addValue(MetadatumDTO value){ + public void addValue(MetadatumDTO value) { this.valueList.add(value); } } diff --git a/dspace-api/src/main/java/org/dspace/importer/external/datamodel/Query.java b/dspace-api/src/main/java/org/dspace/importer/external/datamodel/Query.java index 4266742f19..b5f242d8da 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/datamodel/Query.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/datamodel/Query.java @@ -36,8 +36,8 @@ public class Query { * @param key the key to store against * @param value the value to add to the collection at the key */ - public void addParameter(String key,Object value){ - parameters.put(key,value); + public void addParameter(String key, Object value) { + parameters.put(key, value); } /** @@ -49,26 +49,30 @@ public class Query { * @param key the key to store against * @param value the value to add to the collection at the key */ - protected void addSingletonParameter(String key,Object value){ + protected void addSingletonParameter(String key, Object value) { parameters.remove(key); - parameters.put(key,value); + parameters.put(key, value); } /** * Retrieve a parameter as a certain given class - * @param key the key to retrieve the parameter from - * @param clazz The classtype to retrieve. (If no parameter with that class is found, a null value is returned + * @param the type of parameter returned. + * @param key the key to retrieve the parameter from + * @param clazz the type to retrieve. (If no parameter with that class is found, a null value is returned.) + * @return the selected parameter, or null. */ - public T getParameterAsClass(String key, Class clazz){ + public T getParameterAsClass(String key, Class clazz) { Collection c=parameters.getCollection(key); - if(c==null||c.isEmpty()) return null; - else { - Object o=c.iterator().next(); - if(clazz.isAssignableFrom(o.getClass())) - return (T) o ; - else return null; + if (c==null || c.isEmpty()) { + return null; + } else { + Object o = c.iterator().next(); + if (clazz.isAssignableFrom(o.getClass())) { + return (T) o; + } else { + return null; + } } - } /** * Gets the collection mapped to the specified key. @@ -77,13 +81,13 @@ public class Query { * @param key the key used to retrieve the collection * @return the collection mapped to the key, null if no mapping */ - public Collection getParameter(String key){ + public Collection getParameter(String key) { return parameters.getCollection(key); } /** - * Set the parameters of this query object based on a given {@link org.apache.commons.collections.map.MultiValueMap} + * Set the parameters of this query object based on a given {@link org.apache.commons.collections.map.MultiValueMap} * @param parameters a {@link org.apache.commons.collections.map.MultiValueMap} to set to this Query object */ public void setParameters(MultiValueMap parameters) { diff --git a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/AbstractMetadataFieldMapping.java b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/AbstractMetadataFieldMapping.java index 72cd96806f..b9353d2e21 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/AbstractMetadataFieldMapping.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/AbstractMetadataFieldMapping.java @@ -39,7 +39,7 @@ public abstract class AbstractMetadataFieldMapping implements Metada /** * Set a map of metadataprocessors. This map is used to process metadata to make it more compliant for certain metadata fields - * @param metadataProcessorMap + * @param metadataProcessorMap the new map. */ public void setMetadataProcessorMap(Map metadataProcessorMap) { @@ -84,7 +84,7 @@ public abstract class AbstractMetadataFieldMapping implements Metada /** * Retrieve the metadataFieldMap set to this class - * @return Map> representing the metadataFieldMap + * @return a map representing the metadataFieldMap */ public Map> getMetadataFieldMap() { return metadataFieldMap; diff --git a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadataFieldConfig.java b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadataFieldConfig.java index 279dd3789f..39a153fa8a 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadataFieldConfig.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadataFieldConfig.java @@ -72,7 +72,7 @@ public class MetadataFieldConfig { /** * Create a MetadataFieldConfig based on a given MetadatumDTO * This MetadatumDTO object contains the schema, element and qualifier needed to initialize the MetadataFieldConfig - * @param value + * @param value the DTO. */ public MetadataFieldConfig(MetadatumDTO value) { this.schema = value.getSchema(); diff --git a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadatumDTO.java b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadatumDTO.java index d5fa961814..2e95c5740e 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadatumDTO.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/MetadatumDTO.java @@ -32,7 +32,7 @@ public class MetadatumDTO { /** * Retrieve the schema set to this MetadatumDTO. * Returns null of no schema is set - * @return schema + * @return metadata field schema */ public String getSchema() { return schema; @@ -40,7 +40,7 @@ public class MetadatumDTO { /** * Set the schema to this MetadatumDTO - * @param schema + * @param schema metadata field schema */ public void setSchema(String schema) { this.schema = schema; @@ -49,7 +49,7 @@ public class MetadatumDTO { /** * Retrieve the element set to this MetadatumDTO. * Returns null of no element is set - * @return element + * @return metadata field element */ public String getElement() { return element; @@ -57,7 +57,7 @@ public class MetadatumDTO { /** * Set the element to this MetadatumDTO - * @param element + * @param element metadata field element */ public void setElement(String element) { this.element = element; @@ -66,7 +66,7 @@ public class MetadatumDTO { /** * Retrieve the qualifier set to this MetadatumDTO. * Returns null of no qualifier is set - * @return qualifier + * @return metadata field qualifier */ public String getQualifier() { return qualifier; @@ -74,7 +74,7 @@ public class MetadatumDTO { /** * Set the qualifier to this MetadatumDTO - * @param qualifier + * @param qualifier metadata field qualifier */ public void setQualifier(String qualifier) { this.qualifier = qualifier; @@ -83,12 +83,16 @@ public class MetadatumDTO { /** * Retrieve the value set to this MetadatumDTO. * Returns null of no value is set - * @return value + * @return metadata field value */ public String getValue() { return value; } + /** + * Set the MetadatumDTO to this value. + * @param value metadata field value + */ public void setValue(String value) { this.value = value; } diff --git a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/CombinedMetadatumContributor.java b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/CombinedMetadatumContributor.java index 8987115f59..026e9453f6 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/CombinedMetadatumContributor.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/CombinedMetadatumContributor.java @@ -35,6 +35,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { } /** + * * * @param field {@link org.dspace.importer.external.metadatamapping.MetadataFieldConfig} used in mapping * @param metadatumContributors A list of MetadataContributor @@ -48,7 +49,8 @@ public class CombinedMetadatumContributor implements MetadataContributor { /** * Set the metadatafieldMapping used in the transforming of a record to actual metadata - * @param metadataFieldMapping + * + * @param metadataFieldMapping the new mapping. */ @Override public void setMetadataFieldMapping(MetadataFieldMapping> metadataFieldMapping) { @@ -63,6 +65,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { * a separate Metadatum object is created for each index of Metadatum returned from the calls to * MetadatumContributor.contributeMetadata(t) for each MetadatumContributor in the metadatumContributors list. * We assume that each contributor returns the same amount of Metadatum objects + * * @param t the object we are trying to translate * @return a collection of metadata composed by each MetadataContributor */ @@ -84,7 +87,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { for (LinkedList metadatums : metadatumLists) { value.append(metadatums.get(i).getValue()); - if(!metadatums.equals(metadatumLists.getLast())) { + if (!metadatums.equals(metadatumLists.getLast())) { value.append(separator); } } @@ -96,6 +99,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { /** * Return the MetadataFieldConfig used while retrieving MetadatumDTO + * * @return MetadataFieldConfig */ public MetadataFieldConfig getField() { @@ -104,6 +108,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { /** * Setting the MetadataFieldConfig + * * @param field MetadataFieldConfig used while retrieving MetadatumDTO */ public void setField(MetadataFieldConfig field) { @@ -112,6 +117,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { /** * Return the List of MetadataContributor objects set to this class + * * @return metadatumContributors, list of MetadataContributor */ public LinkedList getMetadatumContributors() { @@ -120,6 +126,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { /** * Set the List of MetadataContributor objects set to this class + * * @param metadatumContributors A list of MetadatumContributor classes */ public void setMetadatumContributors(LinkedList metadatumContributors) { @@ -128,6 +135,7 @@ public class CombinedMetadatumContributor implements MetadataContributor { /** * Return the separator used to differentiate between distinct values + * * @return the separator used to differentiate between distinct values */ public String getSeparator() { @@ -136,7 +144,9 @@ public class CombinedMetadatumContributor implements MetadataContributor { /** * Set the separator used to differentiate between distinct values + * * @param separator + * separator used to differentiate between distinct values */ public void setSeparator(String separator) { this.separator = separator; diff --git a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/SimpleXpathMetadatumContributor.java b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/SimpleXpathMetadatumContributor.java index e8d599a0bb..335ed4b075 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/SimpleXpathMetadatumContributor.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/metadatamapping/contributor/SimpleXpathMetadatumContributor.java @@ -32,7 +32,7 @@ public class SimpleXpathMetadatumContributor implements MetadataContributor prefixToNamespaceMapping + * @return a prefixToNamespaceMapping map */ public Map getPrefixToNamespaceMapping() { return prefixToNamespaceMapping; @@ -42,7 +42,7 @@ public class SimpleXpathMetadatumContributor implements MetadataContributor> metadataFieldMapping + * @return MetadataFieldMapping */ public MetadataFieldMapping> getMetadataFieldMapping() { return metadataFieldMapping; @@ -50,7 +50,7 @@ public class SimpleXpathMetadatumContributor implements MetadataContributor> metadataFieldMapping) { this.metadataFieldMapping = metadataFieldMapping; @@ -58,7 +58,7 @@ public class SimpleXpathMetadatumContributor implements MetadataContributor prefixToNamespaceMapping) { @@ -68,10 +68,13 @@ public class SimpleXpathMetadatumContributor implements MetadataContributor prefixToNamespaceMapping; /** - * Initialize SimpleXpathMetadatumContributor with a query, Map(prefixToNamespaceMapping) and MetadataFieldConfig(field) - * @param query String - * @param prefixToNamespaceMapping Map - * @param field MetadataFieldConfig + * Initialize SimpleXpathMetadatumContributor with a query, prefixToNamespaceMapping and MetadataFieldConfig + * @param query + * query string + * @param prefixToNamespaceMapping + * metadata prefix to namespace mapping + * @param field + * MetadataFieldConfig */ public SimpleXpathMetadatumContributor(String query, Map prefixToNamespaceMapping, MetadataFieldConfig field) { this.query = query; @@ -95,6 +98,7 @@ public class SimpleXpathMetadatumContributor implements MetadataContributor implements MetadataContributor private MetadataFieldMapping> metadataFieldMapping; - /* A list of all the dateFormats to attempt, these should be configured to have the most specific first and the more lenient at the back */ + /* A list of all the dateFormats to attempt. These should be configured to + have the most specific first and the more lenient at the back. */ private List dateFormatsToAttempt; public List getDateFormatsToAttempt() { return dateFormatsToAttempt; } + @Required public void setDateFormatsToAttempt(List dateFormatsToAttempt) { this.dateFormatsToAttempt = dateFormatsToAttempt; @@ -52,8 +54,8 @@ public class PubmedDateMetadatumContributor implements MetadataContributor private MetadataContributor year; /** - * Set the metadatafieldMapping used in the transforming of a record to actual metadata - * @param metadataFieldMapping + * Set the metadatafieldMapping used in the transforming of a record to actual metadata. + * @param metadataFieldMapping the new mapping. */ @Override public void setMetadataFieldMapping(MetadataFieldMapping> metadataFieldMapping) { @@ -200,4 +202,4 @@ public class PubmedDateMetadatumContributor implements MetadataContributor this.year = year; } -} \ No newline at end of file +} diff --git a/dspace-api/src/main/java/org/dspace/importer/external/pubmed/metadatamapping/contributor/PubmedLanguageMetadatumContributor.java b/dspace-api/src/main/java/org/dspace/importer/external/pubmed/metadatamapping/contributor/PubmedLanguageMetadatumContributor.java index 99f4b501df..1163e85842 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/pubmed/metadatamapping/contributor/PubmedLanguageMetadatumContributor.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/pubmed/metadatamapping/contributor/PubmedLanguageMetadatumContributor.java @@ -34,7 +34,7 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo * Initialize PubmedLanguageMetadatumContributor and create the iso3toiso2 mapping used in the transforming of language codes */ public PubmedLanguageMetadatumContributor() { - iso3toIso2=new HashMap<>(); + iso3toIso2 = new HashMap<>(); // Populate the languageMap with the mapping between iso3 and iso2 language codes for (Locale locale : Locale.getAvailableLocales()) { iso3toIso2.put(locale.getISO3Language(),locale.getLanguage()); @@ -43,8 +43,9 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo /** * Initialize the PubmedLanguageMetadatumContributor class using a {@link org.dspace.importer.external.metadatamapping.MetadataFieldConfig} and a language -{@link org.dspace.importer.external.metadatamapping.contributor.MetadataContributor} + * * @param field {@link org.dspace.importer.external.metadatamapping.MetadataFieldConfig} used in mapping - * @param language + * @param language the language. */ public PubmedLanguageMetadatumContributor(MetadataFieldConfig field, MetadataContributor language) { this(); @@ -54,7 +55,8 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo /** * Set the metadatafieldMapping used in the transforming of a record to actual metadata - * @param metadataFieldMapping + * + * @param metadataFieldMapping the new mapping. */ @Override public void setMetadataFieldMapping(MetadataFieldMapping> metadataFieldMapping) { @@ -63,12 +65,14 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo } /** + * + * * @param t A class to retrieve metadata from. * @return a collection of import records. Only the identifier of the found records may be put in the record. */ @Override public Collection contributeMetadata(T t) { - List values=new LinkedList(); + List values = new LinkedList(); try { LinkedList languageList = (LinkedList) language.contributeMetadata(t); @@ -86,6 +90,7 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo /** * Return the MetadataContributor used while retrieving MetadatumDTO + * * @return MetadataContributor */ public MetadataContributor getLanguage() { @@ -94,6 +99,7 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo /** * Setting the MetadataContributor + * * @param language MetadataContributor used while retrieving MetadatumDTO */ public void setLanguage(MetadataContributor language) { @@ -102,6 +108,7 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo /** * Return the MetadataFieldConfig used while retrieving MetadatumDTO + * * @return MetadataFieldConfig */ public MetadataFieldConfig getField() { @@ -110,9 +117,10 @@ public class PubmedLanguageMetadatumContributor implements MetadataContributo /** * Setting the MetadataFieldConfig + * * @param field MetadataFieldConfig used while retrieving MetadatumDTO */ public void setField(MetadataFieldConfig field) { this.field = field; } -} \ No newline at end of file +} diff --git a/dspace-api/src/main/java/org/dspace/importer/external/pubmed/service/PubmedImportMetadataSourceServiceImpl.java b/dspace-api/src/main/java/org/dspace/importer/external/pubmed/service/PubmedImportMetadataSourceServiceImpl.java index d99d5aa180..8311096d10 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/pubmed/service/PubmedImportMetadataSourceServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/pubmed/service/PubmedImportMetadataSourceServiceImpl.java @@ -32,7 +32,7 @@ import java.util.List; import java.util.concurrent.Callable; /** - * Implements a data source for querying pubmed central + * Implements a data source for querying PubMed Central * * @author Roeland Dillen (roeland at atmire dot com) */ @@ -41,67 +41,74 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat private WebTarget pubmedWebTarget; - /** Find the number of records matching a query; + /** + * Find the number of records matching a query; * * @param query a query string to base the search on. * @return the sum of the matching records over this import source - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ @Override public int getNbRecords(String query) throws MetadataSourceException { return retry(new GetNbRecords(query)); } - /** Find the number of records matching a query; + /** + * Find the number of records matching a query; * * @param query a query object to base the search on. * @return the sum of the matching records over this import source - * @throws MetadataSourceException - */ @Override + * @throws MetadataSourceException if the underlying methods throw any exception. + */ + @Override public int getNbRecords(Query query) throws MetadataSourceException { return retry(new GetNbRecords(query)); } - /** Find the number of records matching a string query. Supports pagination + /** + * Find the number of records matching a string query. Supports pagination * * @param query a query string to base the search on. * @param start offset to start at * @param count number of records to retrieve. * @return a set of records. Fully transformed. - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ @Override public Collection getRecords(String query, int start, int count) throws MetadataSourceException { return retry(new GetRecords(query, start, count)); } - /** Find records based on a object query. + /** + * Find records based on a object query. * * @param query a query object to base the search on. * @return a set of records. Fully transformed. - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ @Override public Collection getRecords(Query query) throws MetadataSourceException { return retry(new GetRecords(query)); } - /** Get a single record from the source. - * The first match will be returned + /** + * Get a single record from the source. + * * @param id identifier for the record - * @return a matching record - * @throws MetadataSourceException + * @return the first matching record + * @throws MetadataSourceException if the underlying methods throw any exception. */ @Override public ImportRecord getRecord(String id) throws MetadataSourceException { return retry(new GetRecord(id)); } - /** Get a single record from the source. - * The first match will be returned + /** + * Get a single record from the source. + * * @param query a query matching a single record - * @return a matching record - * @throws MetadataSourceException + * @return the first matching record + * @throws MetadataSourceException if the underlying methods throw any exception. */ @Override public ImportRecord getRecord(Query query) throws MetadataSourceException { @@ -110,6 +117,7 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat /** * The string that identifies this import implementation. Preferable a URI + * * @return the identifying uri */ @Override @@ -117,7 +125,9 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat return "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/"; } - /** Finds records based on an item + /** + * Finds records based on an item + * * @param item an item to base the search on * @return a collection of import records. Only the identifier of the found records may be put in the record. * @throws MetadataSourceException if the underlying methods throw any exception. @@ -127,11 +137,13 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat return retry(new FindMatchingRecords(item)); } - /** Finds records based on query object. + /** + * Finds records based on query object. * Delegates to one or more MetadataSource implementations based on the uri. Results will be aggregated. + * * @param query a query object to base the search on. * @return a collection of import records. Only the identifier of the found records may be put in the record. - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ @Override public Collection findMatchingRecords(Query query) throws MetadataSourceException { @@ -140,7 +152,8 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat /** * Initialize the class - * @throws Exception + * + * @throws Exception on generic exception */ @Override public void init() throws Exception { @@ -151,6 +164,7 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat /** * Return the baseAddress set to this object + * * @return The String object that represents the baseAddress of this object */ public String getBaseAddress() { @@ -159,6 +173,7 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat /** * Set the baseAddress to this object + * * @param baseAddress The String object that represents the baseAddress of this object */ public void setBaseAddress(String baseAddress) { @@ -278,6 +293,7 @@ public class PubmedImportMetadataSourceServiceImpl extends AbstractImportMetadat return records; } } + private List splitToRecords(String recordsSrc) { OMXMLParserWrapper records = OMXMLBuilderFactory.createOMBuilder(new StringReader(recordsSrc)); OMElement element = records.getDocumentElement(); diff --git a/dspace-api/src/main/java/org/dspace/importer/external/service/AbstractImportMetadataSourceService.java b/dspace-api/src/main/java/org/dspace/importer/external/service/AbstractImportMetadataSourceService.java index ecee6ffc4c..cc876b8d87 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/service/AbstractImportMetadataSourceService.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/service/AbstractImportMetadataSourceService.java @@ -40,8 +40,11 @@ public abstract class AbstractImportMetadataSourceService extends Ab } /** - * Set the {@link GenerateQueryService} used to create a {@link org.dspace.importer.external.datamodel.Query} for a DSpace {@link org.dspace.content.Item} - * @param generateQueryForItem + * Set the {@link GenerateQueryService} used to create a + * {@link org.dspace.importer.external.datamodel.Query} for a DSpace + * {@link org.dspace.content.Item}. + * + * @param generateQueryForItem the query generator to be used. */ @Autowired public void setGenerateQueryForItem(GenerateQueryService generateQueryForItem) { @@ -58,7 +61,7 @@ public abstract class AbstractImportMetadataSourceService extends Ab /** * Sets the MetadataFieldMapping to base the mapping of RecordType and - * @param metadataFieldMapping + * @param metadataFieldMapping the map to be used. */ @Required public void setMetadataFieldMapping( @@ -68,7 +71,7 @@ public abstract class AbstractImportMetadataSourceService extends Ab /** * Return an ImportRecord constructed from the results in a RecordType - * @param recordType The recordtype to retrieve the DCValueMapping from + * @param recordType The record type to retrieve the DCValueMapping from * @return An {@link ImportRecord}, This is based on the results retrieved from the recordTypeMapping */ public ImportRecord transformSourceRecords(RecordType recordType){ diff --git a/dspace-api/src/main/java/org/dspace/importer/external/service/ImportService.java b/dspace-api/src/main/java/org/dspace/importer/external/service/ImportService.java index 8cb6dca95c..7047c80d4f 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/service/ImportService.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/service/ImportService.java @@ -42,7 +42,7 @@ public class ImportService implements Destroyable { /** * Sets the importsources that will be used to delegate the retrieving and matching of records to * @param importSources A list of {@link MetadataSource} to set to this service - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ @Autowired(required = false) public void setImportSources(List importSources) throws MetadataSourceException { @@ -61,176 +61,176 @@ public class ImportService implements Destroyable { return Collections.unmodifiableMap(importSources); } - /** - * Utility method to find what import implementations match the imports uri. - * @param uri the identifier of the import implementation or * for all - * @return matching MetadataSource implementations - */ + /** + * Utility method to find what import implementations match the imports uri. + * @param uri the identifier of the import implementation or * for all + * @return matching MetadataSource implementations + */ protected Collection matchingImports(String uri) { if (ANY.equals(uri)) { return importSources.values(); } else { - if(importSources.containsKey(uri)) - return Collections.singletonList(importSources.get(uri)); - else - return Collections.emptyList(); - } + if(importSources.containsKey(uri)) + return Collections.singletonList(importSources.get(uri)); + else + return Collections.emptyList(); + } } - /** Finds records based on an item - * Delegates to one or more MetadataSource implementations based on the uri. Results will be aggregated. - * @param uri the identifier of the import implementation or * for all - * @param item an item to base the search on - * @return a collection of import records. Only the identifier of the found records may be put in the record. - * @throws MetadataSourceException if the underlying imports throw any exception. - */ + /** Finds records based on an item + * Delegates to one or more MetadataSource implementations based on the uri. Results will be aggregated. + * @param uri the identifier of the import implementation or * for all + * @param item an item to base the search on + * @return a collection of import records. Only the identifier of the found records may be put in the record. + * @throws MetadataSourceException if the underlying methods throw any exception. + */ public Collection findMatchingRecords(String uri, Item item) throws MetadataSourceException { - try { - List recordList = new LinkedList(); + try { + List recordList = new LinkedList(); - for (MetadataSource metadataSource : matchingImports(uri)) { - recordList.addAll(metadataSource.findMatchingRecords(item)); - } + for (MetadataSource metadataSource : matchingImports(uri)) { + recordList.addAll(metadataSource.findMatchingRecords(item)); + } - return recordList; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } + return recordList; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } - /** Finds records based on query object. - * Delegates to one or more MetadataSource implementations based on the uri. Results will be aggregated. - * @param uri the identifier of the import implementation or * for all - * @param query a query object to base the search on. The implementation decides how the query is interpreted. - * @return a collection of import records. Only the identifier of the found records may be put in the record. - * @throws MetadataSourceException - */ + /** Finds records based on query object. + * Delegates to one or more MetadataSource implementations based on the uri. Results will be aggregated. + * @param uri the identifier of the import implementation or * for all + * @param query a query object to base the search on. The implementation decides how the query is interpreted. + * @return a collection of import records. Only the identifier of the found records may be put in the record. + * @throws MetadataSourceException if the underlying methods throw any exception. + */ public Collection findMatchingRecords(String uri, Query query) throws MetadataSourceException { - try { - List recordList = new LinkedList(); - for (MetadataSource metadataSource : matchingImports(uri)) { - recordList.addAll(metadataSource.findMatchingRecords(query)); - } + try { + List recordList = new LinkedList(); + for (MetadataSource metadataSource : matchingImports(uri)) { + recordList.addAll(metadataSource.findMatchingRecords(query)); + } - return recordList; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } + return recordList; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } - /** Find the number of records matching a string query; - * - * @param uri the identifier of the import implementation or * for all - * @param query a query to base the search on - * @return the sum of the matching records over all import sources - * @throws MetadataSourceException - */ + /** Find the number of records matching a string query; + * + * @param uri the identifier of the import implementation or * for all + * @param query a query to base the search on + * @return the sum of the matching records over all import sources + * @throws MetadataSourceException if the underlying methods throw any exception. + */ public int getNbRecords(String uri, String query) throws MetadataSourceException { - try { - int total = 0; - for (MetadataSource MetadataSource : matchingImports(uri)) { - total += MetadataSource.getNbRecords(query); - } - return total; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } - /** Find the number of records matching a query; - * - * @param uri the identifier of the import implementation or * for all - * @param query a query object to base the search on The implementation decides how the query is interpreted. - * @return the sum of the matching records over all import sources - * @throws MetadataSourceException - */ - public int getNbRecords(String uri, Query query) throws MetadataSourceException { - try { - int total = 0; - for (MetadataSource MetadataSource : matchingImports(uri)) { - total += MetadataSource.getNbRecords(query); - } - return total; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } + try { + int total = 0; + for (MetadataSource MetadataSource : matchingImports(uri)) { + total += MetadataSource.getNbRecords(query); + } + return total; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } + /** Find the number of records matching a query; + * + * @param uri the identifier of the import implementation or * for all + * @param query a query object to base the search on The implementation decides how the query is interpreted. + * @return the sum of the matching records over all import sources + * @throws MetadataSourceException if the underlying methods throw any exception. + */ + public int getNbRecords(String uri, Query query) throws MetadataSourceException { + try { + int total = 0; + for (MetadataSource MetadataSource : matchingImports(uri)) { + total += MetadataSource.getNbRecords(query); + } + return total; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } - /** Find the number of records matching a string query. Supports pagination - * - * @param uri the identifier of the import implementation or * for all - * @param query a query object to base the search on. The implementation decides how the query is interpreted. - * @param start offset to start at - * @param count number of records to retrieve. - * @return a set of records. Fully transformed. - * @throws MetadataSourceException - */ + /** Find the number of records matching a string query. Supports pagination + * + * @param uri the identifier of the import implementation or * for all + * @param query a query object to base the search on. The implementation decides how the query is interpreted. + * @param start offset to start at + * @param count number of records to retrieve. + * @return a set of records. Fully transformed. + * @throws MetadataSourceException if the underlying methods throw any exception. + */ public Collection getRecords(String uri, String query, int start, int count) throws MetadataSourceException { - try { - List recordList = new LinkedList<>(); - for (MetadataSource metadataSource : matchingImports(uri)) { - recordList.addAll(metadataSource.getRecords(query, start, count)); - } - return recordList; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } + try { + List recordList = new LinkedList<>(); + for (MetadataSource metadataSource : matchingImports(uri)) { + recordList.addAll(metadataSource.getRecords(query, start, count)); + } + return recordList; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } - /** Find the number of records matching a object query. - * - * @param uri the identifier of the import implementation or * for all - * @param query a query object to base the search on. The implementation decides how the query is interpreted. - * @return a set of records. Fully transformed. - * @throws MetadataSourceException - */ + /** Find the number of records matching a object query. + * + * @param uri the identifier of the import implementation or * for all + * @param query a query object to base the search on. The implementation decides how the query is interpreted. + * @return a set of records. Fully transformed. + * @throws MetadataSourceException if the underlying methods throw any exception. + */ public Collection getRecords(String uri, Query query) throws MetadataSourceException { - try { - List recordList = new LinkedList<>(); - for (MetadataSource metadataSource : matchingImports(uri)) { - recordList.addAll(metadataSource.getRecords(query)); - } - return recordList; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } + try { + List recordList = new LinkedList<>(); + for (MetadataSource metadataSource : matchingImports(uri)) { + recordList.addAll(metadataSource.getRecords(query)); + } + return recordList; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } - /** Get a single record from a source. - * The first match will be returned - * @param uri uri the identifier of the import implementation or * for all - * @param id identifier for the record - * @return a matching record - * @throws MetadataSourceException - */ + /** Get a single record from a source. + * The first match will be returned + * @param uri uri the identifier of the import implementation or * for all + * @param id identifier for the record + * @return a matching record + * @throws MetadataSourceException if the underlying methods throw any exception. + */ public ImportRecord getRecord(String uri, String id) throws MetadataSourceException { - try { - for (MetadataSource metadataSource : matchingImports(uri)) { - if (metadataSource.getRecord(id) != null) return metadataSource.getRecord(id); - - } - return null; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } - /** Get a single record from the source. - * The first match will be returned - * @param uri uri the identifier of the import implementation or * for all - * @param query a query matching a single record - * @return a matching record - * @throws MetadataSourceException - */ + try { + for (MetadataSource metadataSource : matchingImports(uri)) { + if (metadataSource.getRecord(id) != null) return metadataSource.getRecord(id); + + } + return null; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } + /** Get a single record from the source. + * The first match will be returned + * @param uri uri the identifier of the import implementation or * for all + * @param query a query matching a single record + * @return a matching record + * @throws MetadataSourceException if the underlying methods throw any exception. + */ public ImportRecord getRecord(String uri, Query query) throws MetadataSourceException { - try { - for (MetadataSource metadataSource : matchingImports(uri)) { - if (metadataSource.getRecord(query) != null) return metadataSource.getRecord(query); - - } - return null; - } catch (Exception e) { - throw new MetadataSourceException(e); - } - } + try { + for (MetadataSource metadataSource : matchingImports(uri)) { + if (metadataSource.getRecord(query) != null) return metadataSource.getRecord(query); + + } + return null; + } catch (Exception e) { + throw new MetadataSourceException(e); + } + } /** Retrieve the importUrls that are set on the importSources . * @return a Collection of string, representing the configured importUrls diff --git a/dspace-api/src/main/java/org/dspace/importer/external/service/components/AbstractRemoteMetadataSource.java b/dspace-api/src/main/java/org/dspace/importer/external/service/components/AbstractRemoteMetadataSource.java index 5a35389810..b683255579 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/service/components/AbstractRemoteMetadataSource.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/service/components/AbstractRemoteMetadataSource.java @@ -61,6 +61,7 @@ public abstract class AbstractRemoteMetadataSource { /** * Return the warning message used for logging during exception catching + * * @return a "warning" String */ public String getWarning() { @@ -69,7 +70,9 @@ public abstract class AbstractRemoteMetadataSource { /** * Set the warning message used for logging + * * @param warning + * warning message */ public void setWarning(String warning) { this.warning = warning; @@ -77,6 +80,7 @@ public abstract class AbstractRemoteMetadataSource { /** * Return the number of retries that have currently been undertaken + * * @return the number of retries */ public int getRetry() { @@ -84,7 +88,8 @@ public abstract class AbstractRemoteMetadataSource { } /** * Return the number of max retries that can be undertaken before separate functionality kicks in - * @return the number of maximum retries + * + * @return maximum number of retries */ public int getMaxRetry() { return maxRetry; @@ -92,7 +97,9 @@ public abstract class AbstractRemoteMetadataSource { /** * Set the number of maximum retries before throwing on the exception + * * @param maxRetry + * maximum number of retries */ @Resource(name="maxRetry") public void setMaxRetry(int maxRetry) { @@ -101,6 +108,7 @@ public abstract class AbstractRemoteMetadataSource { /** * Retrieve the operationId + * * @return A randomly generated UUID. generated during the retry method */ public String getOperationId() { @@ -109,6 +117,7 @@ public abstract class AbstractRemoteMetadataSource { /** * Retrieve the last encountered exception + * * @return An Exception object, the last one encountered in the retry method */ public Exception getError() { @@ -117,7 +126,8 @@ public abstract class AbstractRemoteMetadataSource { /** * Set the last encountered error - * @param error + * + * @param error exception to set */ public void setError(Exception error) { this.error = error; @@ -187,6 +197,7 @@ public abstract class AbstractRemoteMetadataSource { /** * Handles a given exception or throws on a {@link org.dspace.importer.external.exception.MetadataSourceException} if no ExceptionHandler is set + * * @param retry The number of retries before the exception was thrown on * @param exception The exception to handle * @param operationId The id of the operation that threw the exception @@ -199,12 +210,14 @@ public abstract class AbstractRemoteMetadataSource { for (SourceExceptionHandler exceptionHandler : exceptionHandlers) { exceptionHandler.handle(this); } - }else{ + } else { throwSourceException(retry, exception, operationId); } } - /** Retrieve a list of SourceExceptionHandler objects that have an instanceof the exception configured to them. + /** + * Retrieve a list of SourceExceptionHandler objects that have an instanceof the exception configured to them. + * * @param exception The exception to base the retrieval of {@link org.dspace.importer.external.exception.SourceExceptionHandler} on * @return a list of {@link org.dspace.importer.external.exception.SourceExceptionHandler} objects */ @@ -217,11 +230,13 @@ public abstract class AbstractRemoteMetadataSource { return null; } - /** Throw a {@link MetadataSourceException} + /** + * Throw a {@link MetadataSourceException} + * * @param retry The number of retries before the exception was thrown on * @param exception The exception to throw * @param operationId The id of the operation that threw the exception - * @throws MetadataSourceException + * @throws MetadataSourceException if no ExceptionHandler is configured for the given exception */ protected void throwSourceException(int retry, Exception exception, String operationId) throws MetadataSourceException { throwSourceExceptionHook(); @@ -239,7 +254,7 @@ public abstract class AbstractRemoteMetadataSource { /** * Attempts to init a session * - * @throws Exception + * @throws Exception on generic exception */ public abstract void init() throws Exception; diff --git a/dspace-api/src/main/java/org/dspace/importer/external/service/components/Destroyable.java b/dspace-api/src/main/java/org/dspace/importer/external/service/components/Destroyable.java index 5bb54f8ff0..fbd6928f91 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/service/components/Destroyable.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/service/components/Destroyable.java @@ -15,7 +15,8 @@ public interface Destroyable { /** * Destroy the object - * @throws Exception + * + * @throws Exception on generic exception */ public void destroy() throws Exception; } diff --git a/dspace-api/src/main/java/org/dspace/importer/external/service/components/MetadataSource.java b/dspace-api/src/main/java/org/dspace/importer/external/service/components/MetadataSource.java index eae04dbe75..813cc1e043 100644 --- a/dspace-api/src/main/java/org/dspace/importer/external/service/components/MetadataSource.java +++ b/dspace-api/src/main/java/org/dspace/importer/external/service/components/MetadataSource.java @@ -23,14 +23,14 @@ public interface MetadataSource { * Gets the number of records matching a query * @param query the query in string format * @return the number of records matching the query - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ public int getNbRecords(String query) throws MetadataSourceException; /** * Gets the number of records matching a query * @param query the query object * @return the number of records matching the query - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ public int getNbRecords(Query query) throws MetadataSourceException; @@ -40,7 +40,7 @@ public interface MetadataSource { * @param start offset * @param count page size * @return a collection of fully transformed id's - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ public Collection getRecords(String query, int start, int count)throws MetadataSourceException; @@ -48,7 +48,7 @@ public interface MetadataSource { * * @param query a query object to base the search on. * @return a set of records. Fully transformed. - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ public Collection getRecords(Query query)throws MetadataSourceException; @@ -56,7 +56,7 @@ public interface MetadataSource { * The first match will be returned * @param id identifier for the record * @return a matching record - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ public ImportRecord getRecord(String id)throws MetadataSourceException; @@ -64,7 +64,7 @@ public interface MetadataSource { * The first match will be returned * @param query a query matching a single record * @return a matching record - * @throws MetadataSourceException + * @throws MetadataSourceException if the underlying methods throw any exception. */ public ImportRecord getRecord(Query query)throws MetadataSourceException; @@ -78,7 +78,7 @@ public interface MetadataSource { * Delegates to one or more MetadataSource implementations based on the uri. Results will be aggregated. * @param item an item to base the search on * @return a collection of import records. Only the identifier of the found records may be put in the record. - * @throws MetadataSourceException if the underlying imports throw any exception. + * @throws MetadataSourceException if the underlying methods throw any exception. */ public Collection findMatchingRecords(Item item) throws MetadataSourceException; @@ -86,7 +86,7 @@ public interface MetadataSource { * Delegates to one or more MetadataSource implementations based on the uri. Results will be aggregated. * @param query a query object to base the search on. * @return a collection of import records. Only the identifier of the found records may be put in the record. - * @throws MetadataSourceException + * @throws MetadataSourceException passed through. */ public Collection findMatchingRecords(Query query) throws MetadataSourceException; } diff --git a/dspace-api/src/main/java/org/dspace/license/CCLookup.java b/dspace-api/src/main/java/org/dspace/license/CCLookup.java index 2f90ed2f6c..be24e8844a 100644 --- a/dspace-api/src/main/java/org/dspace/license/CCLookup.java +++ b/dspace-api/src/main/java/org/dspace/license/CCLookup.java @@ -36,413 +36,416 @@ import org.jdom.input.SAXBuilder; /** - * A wrapper around Creative Commons REST web services. + * A wrapper around Creative Commons REST web services. * * @author Wendy Bossons */ public class CCLookup { - /** log4j logger */ - private static Logger log = Logger.getLogger(CCLookup.class); + /** log4j logger */ + private static Logger log = Logger.getLogger(CCLookup.class); - private String cc_root; - private String jurisdiction; - private List lcFilter = new ArrayList(); - - private Document license_doc = null; - private String rdfString = null; - private String errorMessage = null; - private boolean success = false; + private String cc_root; + private String jurisdiction; + private List lcFilter = new ArrayList(); + + private Document license_doc = null; + private String rdfString = null; + private String errorMessage = null; + private boolean success = false; - private SAXBuilder parser = new SAXBuilder(); - private List licenses = new ArrayList(); - private List licenseFields = new ArrayList(); - - protected CreativeCommonsService creativeCommonsService = LicenseServiceFactory.getInstance().getCreativeCommonsService(); - - /** - * Constructs a new instance with the default web services root. - * - */ - public CCLookup() { - super(); + private SAXBuilder parser = new SAXBuilder(); + private List licenses = new ArrayList(); + private List licenseFields = new ArrayList(); + + protected CreativeCommonsService creativeCommonsService = LicenseServiceFactory.getInstance().getCreativeCommonsService(); + + /** + * Constructs a new instance with the default web services root. + * + */ + public CCLookup() { + super(); - ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); + ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); - cc_root = configurationService.getProperty("cc.api.rooturl"); + cc_root = configurationService.getProperty("cc.api.rooturl"); - String jurisProp = configurationService.getProperty("cc.license.jurisdiction"); - jurisdiction = (jurisProp != null) ? jurisProp : ""; - - String[] filters = configurationService.getArrayProperty("cc.license.classfilter"); - if (filters != null) { - for (String name: filters) { - lcFilter.add(name.trim()); - } - } - } + String jurisProp = configurationService.getProperty("cc.license.jurisdiction"); + jurisdiction = (jurisProp != null) ? jurisProp : ""; + + String[] filters = configurationService.getArrayProperty("cc.license.classfilter"); + if (filters != null) { + for (String name: filters) { + lcFilter.add(name.trim()); + } + } + } - /** - * Returns the id for a particular CCLicense label. Returns an - * empty string if no match is found. - * - * @param class_label The CCLicense label to find. - * @return Returns a String containing the License class ID if the label - * is found; if not found, returns an empty string. - * - * @see CCLicense - * - */ - public String getLicenseId (String class_label) { - for (int i = 0; i < this.licenses.size(); i++) { - if ( ((CCLicense)this.licenses.get(i)).getLicenseName().equals(class_label)) { - return ( (CCLicense)this.licenses.get(i) ).getLicenseId(); - } - } + /** + * Returns the id for a particular CCLicense label. Returns an + * empty string if no match is found. + * + * @param class_label The CCLicense label to find. + * @return Returns a String containing the License class ID if the label + * is found; if not found, returns an empty string. + * + * @see CCLicense + * + */ + public String getLicenseId (String class_label) { + for (int i = 0; i < this.licenses.size(); i++) { + if ( ((CCLicense)this.licenses.get(i)).getLicenseName().equals(class_label)) { + return ( (CCLicense)this.licenses.get(i) ).getLicenseId(); + } + } - return ""; - } + return ""; + } - /** - * Queries the web service for the available licenses. - * - * @param language The language to request labels and description strings in. - * @return Returns a Map of CCLicense objects. - * - * @see Map - * @see CCLicense - * - */ - public Collection getLicenses(String language) { + /** + * Queries the web service for the available licenses. + * + * @param language The language to request labels and description strings in. + * @return Returns a Map of CCLicense objects. + * + * @see Map + * @see CCLicense + * + */ + public Collection getLicenses(String language) { - // create XPath expressions - try { - JDOMXPath xp_Licenses = new JDOMXPath("//licenses/license"); - JDOMXPath xp_LicenseID = new JDOMXPath("@id"); - URL classUrl = new URL(this.cc_root + "/?locale=" + language); - Document classDoc = this.parser.build(classUrl); - // extract the identifiers and labels using XPath - List results = xp_Licenses.selectNodes(classDoc); - // populate licenses container - this.licenses.clear(); - for (int i = 0; i < results.size(); i++) { - Element license = results.get(i); - // add if not filtered - String liD = ((Attribute)xp_LicenseID.selectSingleNode(license)).getValue(); - if (! lcFilter.contains(liD)) { - this.licenses.add(new CCLicense(liD, license.getText(), i)); - } - } - } catch (JaxenException jaxen_e) { - return null; - } catch (JDOMException jdom_e) { - return null; - } catch (IOException io_e) { - return null; - } catch (Exception e) { - // do nothing... but we should - return null; - } + // create XPath expressions + try { + JDOMXPath xp_Licenses = new JDOMXPath("//licenses/license"); + JDOMXPath xp_LicenseID = new JDOMXPath("@id"); + URL classUrl = new URL(this.cc_root + "/?locale=" + language); + Document classDoc = this.parser.build(classUrl); + // extract the identifiers and labels using XPath + List results = xp_Licenses.selectNodes(classDoc); + // populate licenses container + this.licenses.clear(); + for (int i = 0; i < results.size(); i++) { + Element license = results.get(i); + // add if not filtered + String liD = ((Attribute)xp_LicenseID.selectSingleNode(license)).getValue(); + if (! lcFilter.contains(liD)) { + this.licenses.add(new CCLicense(liD, license.getText(), i)); + } + } + } catch (JaxenException jaxen_e) { + return null; + } catch (JDOMException jdom_e) { + return null; + } catch (IOException io_e) { + return null; + } catch (Exception e) { + // do nothing... but we should + return null; + } - return licenses; - } + return licenses; + } - /** - * Queries the web service for a set of licenseFields for a particular license class. - * - * @param license A String specifying the CCLicense identifier to - * retrieve fields for. - * @return A Collection of LicenseField objects. - * - * @see CCLicense - * - */ - public Collection getLicenseFields(String license, String language) { + /** + * Queries the web service for a set of licenseFields for a particular license class. + * + * @param license + * A String specifying the CCLicense identifier to + * retrieve fields for. + * @param language + * the locale string + * @return A Collection of LicenseField objects. + * + * @see CCLicense + * + */ + public Collection getLicenseFields(String license, String language) { - JDOMXPath xp_LicenseField; - JDOMXPath xp_LicenseID; - JDOMXPath xp_FieldType; - JDOMXPath xp_Description; - JDOMXPath xp_Label; - JDOMXPath xp_Enum; + JDOMXPath xp_LicenseField; + JDOMXPath xp_LicenseID; + JDOMXPath xp_FieldType; + JDOMXPath xp_Description; + JDOMXPath xp_Label; + JDOMXPath xp_Enum; - Document fieldDoc; + Document fieldDoc; - URL classUrl; - List results = null; - List enumOptions = null; + URL classUrl; + List results = null; + List enumOptions = null; - // create XPath expressions - try { - xp_LicenseField = new JDOMXPath("//field"); - xp_LicenseID = new JDOMXPath("@id"); - xp_Description = new JDOMXPath("description"); - xp_Label = new JDOMXPath("label"); - xp_FieldType = new JDOMXPath("type"); - xp_Enum = new JDOMXPath("enum"); + // create XPath expressions + try { + xp_LicenseField = new JDOMXPath("//field"); + xp_LicenseID = new JDOMXPath("@id"); + xp_Description = new JDOMXPath("description"); + xp_Label = new JDOMXPath("label"); + xp_FieldType = new JDOMXPath("type"); + xp_Enum = new JDOMXPath("enum"); - } catch (JaxenException e) { - return null; - } + } catch (JaxenException e) { + return null; + } - // retrieve and parse the license class document - try { - classUrl = new URL(this.cc_root + "/license/" + license + "?locale=" + language); - } catch (Exception err) { - // do nothing... but we should - return null; - } + // retrieve and parse the license class document + try { + classUrl = new URL(this.cc_root + "/license/" + license + "?locale=" + language); + } catch (Exception err) { + // do nothing... but we should + return null; + } - // parse the licenses document - try { - fieldDoc = this.parser.build(classUrl); - } catch (JDOMException e) { - return null; - } catch (IOException e) { - return null; - } + // parse the licenses document + try { + fieldDoc = this.parser.build(classUrl); + } catch (JDOMException e) { + return null; + } catch (IOException e) { + return null; + } - // reset the field definition container - this.licenseFields.clear(); + // reset the field definition container + this.licenseFields.clear(); - // extract the identifiers and labels using XPath - try { - results = xp_LicenseField.selectNodes(fieldDoc); - } catch (JaxenException e) { - return null; - } + // extract the identifiers and labels using XPath + try { + results = xp_LicenseField.selectNodes(fieldDoc); + } catch (JaxenException e) { + return null; + } - for (int i=0; i < results.size(); i++) { - Element field = (Element)results.get(i); + for (int i=0; i < results.size(); i++) { + Element field = (Element)results.get(i); - try { - // create the field object - CCLicenseField cclicensefield = new CCLicenseField(((Attribute)xp_LicenseID.selectSingleNode(field)).getValue(), - ((Element)xp_Label.selectSingleNode(field)).getText() ); + try { + // create the field object + CCLicenseField cclicensefield = new CCLicenseField(((Attribute)xp_LicenseID.selectSingleNode(field)).getValue(), + ((Element)xp_Label.selectSingleNode(field)).getText() ); - // extract additional properties - cclicensefield.setDescription( ((Element)xp_Description.selectSingleNode(field)).getText() ); - cclicensefield.setType( ((Element)xp_FieldType.selectSingleNode(field)).getText() ); + // extract additional properties + cclicensefield.setDescription( ((Element)xp_Description.selectSingleNode(field)).getText() ); + cclicensefield.setType( ((Element)xp_FieldType.selectSingleNode(field)).getText() ); - enumOptions = xp_Enum.selectNodes(field); + enumOptions = xp_Enum.selectNodes(field); - for (int j = 0; j < enumOptions.size(); j++) { - String id = ((Attribute)xp_LicenseID.selectSingleNode(enumOptions.get(j))).getValue(); - String label =((Element)xp_Label.selectSingleNode(enumOptions.get(j))).getText(); + for (int j = 0; j < enumOptions.size(); j++) { + String id = ((Attribute)xp_LicenseID.selectSingleNode(enumOptions.get(j))).getValue(); + String label =((Element)xp_Label.selectSingleNode(enumOptions.get(j))).getText(); - cclicensefield.getEnum().put( id, label); + cclicensefield.getEnum().put( id, label); - } // for each enum option + } // for each enum option - this.licenseFields.add(cclicensefield); - } catch (JaxenException e) { - return null; - } - } + this.licenseFields.add(cclicensefield); + } catch (JaxenException e) { + return null; + } + } - return licenseFields; - } // licenseFields + return licenseFields; + } // licenseFields - /** - * Passes a set of "answers" to the web service and retrieves a license. - * - * @param licenseId The identifier of the license class being requested. - * @param answers A Map containing the answers to the license fields; - * each key is the identifier of a LicenseField, with the value - * containing the user-supplied answer. - * @param lang The language to request localized elements in. - * - * @throws IOException if IO error - * - * @see CCLicense - * @see Map - */ - public void issue(String licenseId, Map answers, String lang) - throws IOException{ + /** + * Passes a set of "answers" to the web service and retrieves a license. + * + * @param licenseId The identifier of the license class being requested. + * @param answers A Map containing the answers to the license fields; + * each key is the identifier of a LicenseField, with the value + * containing the user-supplied answer. + * @param lang The language to request localized elements in. + * + * @throws IOException if IO error + * + * @see CCLicense + * @see Map + */ + public void issue(String licenseId, Map answers, String lang) + throws IOException{ - // Determine the issue URL - String issueUrl = this.cc_root + "/license/" + licenseId + "/issue"; - // Assemble the "answers" document - String answer_doc = "\n" + lang + "\n" + "\n"; - Iterator keys = answers.keySet().iterator(); + // Determine the issue URL + String issueUrl = this.cc_root + "/license/" + licenseId + "/issue"; + // Assemble the "answers" document + String answer_doc = "\n" + lang + "\n" + "\n"; + Iterator keys = answers.keySet().iterator(); - try { - String current = (String)keys.next(); + try { + String current = (String)keys.next(); - while (true) { - answer_doc += "<" + current + ">" + (String)answers.get(current) + "\n"; - current = (String)keys.next(); - } + while (true) { + answer_doc += "<" + current + ">" + (String)answers.get(current) + "\n"; + current = (String)keys.next(); + } - } catch (NoSuchElementException e) { - // exception indicates we've iterated through the - // entire collection; just swallow and continue - } - // answer_doc += "\n"; FAILS with jurisdiction argument - answer_doc += "\n\n"; - String post_data; + } catch (NoSuchElementException e) { + // exception indicates we've iterated through the + // entire collection; just swallow and continue + } + // answer_doc += "\n"; FAILS with jurisdiction argument + answer_doc += "\n\n"; + String post_data; - try { - post_data = URLEncoder.encode("answers", "UTF-8") + "=" + URLEncoder.encode(answer_doc, "UTF-8"); - } catch (UnsupportedEncodingException e) { - return; - } + try { + post_data = URLEncoder.encode("answers", "UTF-8") + "=" + URLEncoder.encode(answer_doc, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return; + } - URL post_url; - try { - post_url = new URL(issueUrl); - } catch (MalformedURLException e) { - return; - } - URLConnection connection = post_url.openConnection(); - // this will not be needed after I'm done TODO: remove - connection.setDoOutput(true); - OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - writer.write(post_data); - writer.flush(); - // end TODO - try { - // parsing document from input stream - java.io.InputStream stream = connection.getInputStream(); - this.license_doc = this.parser.build(stream); - } catch (JDOMException jde) { + URL post_url; + try { + post_url = new URL(issueUrl); + } catch (MalformedURLException e) { + return; + } + URLConnection connection = post_url.openConnection(); + // this will not be needed after I'm done TODO: remove + connection.setDoOutput(true); + OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); + writer.write(post_data); + writer.flush(); + // end TODO + try { + // parsing document from input stream + java.io.InputStream stream = connection.getInputStream(); + this.license_doc = this.parser.build(stream); + } catch (JDOMException jde) { log.warn(jde.getMessage()); - } catch (Exception e) { - log.warn(e.getCause()); - } - return; - } // issue + } catch (Exception e) { + log.warn(e.getCause()); + } + return; + } // issue -/** - * Passes a set of "answers" to the web service and retrieves a license. - * - * @param licenseURI The uri of the license. - * - * Note: does not support localization in 1.5 -- not yet - * - * @throws IOException if IO error - * - * @see CCLicense - * @see Map - */ - public void issue(String licenseURI) - throws IOException{ + /** + * Passes a set of "answers" to the web service and retrieves a license. + * + * @param licenseURI The uri of the license. + * + * Note: does not support localization in 1.5 -- not yet + * + * @throws IOException if IO error + * + * @see CCLicense + * @see Map + */ + public void issue(String licenseURI) + throws IOException{ - // Determine the issue URL - // Example: http://api.creativecommons.org/rest/1.5/details? - // license-uri=http://creativecommons.org/licenses/by-nc-sa/3.0/ - String issueUrl = cc_root + "/details?license-uri=" + licenseURI; + // Determine the issue URL + // Example: http://api.creativecommons.org/rest/1.5/details? + // license-uri=http://creativecommons.org/licenses/by-nc-sa/3.0/ + String issueUrl = cc_root + "/details?license-uri=" + licenseURI; - URL request_url; - try { - request_url = new URL(issueUrl); - } catch (MalformedURLException e) { - return; - } - URLConnection connection = request_url.openConnection(); - // this will not be needed after I'm done TODO: remove - connection.setDoOutput(true); - try { - // parsing document from input stream - java.io.InputStream stream = connection.getInputStream(); - license_doc = this.parser.build(stream); - } catch (JDOMException jde) { - log.warn( jde.getMessage()); - } catch (Exception e) { - log.warn(e.getCause()); - } - return; - } // issue + URL request_url; + try { + request_url = new URL(issueUrl); + } catch (MalformedURLException e) { + return; + } + URLConnection connection = request_url.openConnection(); + // this will not be needed after I'm done TODO: remove + connection.setDoOutput(true); + try { + // parsing document from input stream + java.io.InputStream stream = connection.getInputStream(); + license_doc = this.parser.build(stream); + } catch (JDOMException jde) { + log.warn( jde.getMessage()); + } catch (Exception e) { + log.warn(e.getCause()); + } + return; + } // issue - /** - * Retrieves the URI for the license issued. - * - * @return A String containing the URI for the license issued. - */ - public String getLicenseUrl() { - String text = null; - try { - JDOMXPath xp_LicenseName = new JDOMXPath("//result/license-uri"); - text = ((Element)xp_LicenseName.selectSingleNode(this.license_doc)).getText(); - } - catch (Exception e) { - log.warn(e.getMessage()); - setSuccess(false); - text = "An error occurred getting the license - uri."; - } - finally - { - return text; - } - } // getLicenseUrl + /** + * Retrieves the URI for the license issued. + * + * @return A String containing the URI for the license issued. + */ + public String getLicenseUrl() { + String text = null; + try { + JDOMXPath xp_LicenseName = new JDOMXPath("//result/license-uri"); + text = ((Element)xp_LicenseName.selectSingleNode(this.license_doc)).getText(); + } + catch (Exception e) { + log.warn(e.getMessage()); + setSuccess(false); + text = "An error occurred getting the license - uri."; + } + finally + { + return text; + } + } // getLicenseUrl - /** - * Retrieves the human readable name for the license issued. - * - * @return A String containing the license name. - */ - public String getLicenseName() { - String text = null; - try { - JDOMXPath xp_LicenseName = new JDOMXPath("//result/license-name"); - text = ((Element)xp_LicenseName.selectSingleNode(this.license_doc)).getText(); - } - catch (Exception e) { - log.warn(e.getMessage()); - setSuccess(false); - text = "An error occurred on the license name."; - } - finally - { - return text; - } - } // getLicenseName + /** + * Retrieves the human readable name for the license issued. + * + * @return A String containing the license name. + */ + public String getLicenseName() { + String text = null; + try { + JDOMXPath xp_LicenseName = new JDOMXPath("//result/license-name"); + text = ((Element)xp_LicenseName.selectSingleNode(this.license_doc)).getText(); + } + catch (Exception e) { + log.warn(e.getMessage()); + setSuccess(false); + text = "An error occurred on the license name."; + } + finally + { + return text; + } + } // getLicenseName - public org.jdom.Document getLicenseDocument() { - return this.license_doc; - } + public org.jdom.Document getLicenseDocument() { + return this.license_doc; + } - public String getRdf() - throws IOException { - String result = ""; - try { - result = creativeCommonsService.fetchLicenseRDF(license_doc); - } catch (Exception e) { - log.warn("An error occurred getting the rdf . . ." + e.getMessage() ); - setSuccess(false); - } - return result; - } + public String getRdf() + throws IOException { + String result = ""; + try { + result = creativeCommonsService.fetchLicenseRDF(license_doc); + } catch (Exception e) { + log.warn("An error occurred getting the rdf . . ." + e.getMessage() ); + setSuccess(false); + } + return result; + } - public boolean isSuccess() { - setSuccess(false); - JDOMXPath xp_Success; - String text = null; - try { - xp_Success = new JDOMXPath("//message"); - text = ((Element)xp_Success.selectSingleNode(this.license_doc)).getText(); - setErrorMessage(text); - } - catch (Exception e) { - log.warn("There was an issue . . . " + text); - setSuccess(true); - } - return this.success; - } + public boolean isSuccess() { + setSuccess(false); + JDOMXPath xp_Success; + String text = null; + try { + xp_Success = new JDOMXPath("//message"); + text = ((Element)xp_Success.selectSingleNode(this.license_doc)).getText(); + setErrorMessage(text); + } + catch (Exception e) { + log.warn("There was an issue . . . " + text); + setSuccess(true); + } + return this.success; + } - private void setSuccess(boolean success) { - this.success = success; - } + private void setSuccess(boolean success) { + this.success = success; + } - public String getErrorMessage() { - return this.errorMessage; - } + public String getErrorMessage() { + return this.errorMessage; + } - private void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } + private void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } } diff --git a/dspace-api/src/main/java/org/dspace/license/CreativeCommonsServiceImpl.java b/dspace-api/src/main/java/org/dspace/license/CreativeCommonsServiceImpl.java index 88c1dac2c7..1eb258e492 100644 --- a/dspace-api/src/main/java/org/dspace/license/CreativeCommonsServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/license/CreativeCommonsServiceImpl.java @@ -86,7 +86,7 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi protected CreativeCommonsServiceImpl() { - + } @Override @@ -139,7 +139,7 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi @Override public void setLicenseRDF(Context context, Item item, String licenseRdf) - throws SQLException, IOException, + throws SQLException, IOException, AuthorizeException { Bundle bundle = getCcBundle(context, item); @@ -161,11 +161,11 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi BitstreamFormat bs_format; if (mimeType.equalsIgnoreCase("text/xml")) { - bs_format = bitstreamFormatService.findByShortDescription(context, "CC License"); + bs_format = bitstreamFormatService.findByShortDescription(context, "CC License"); } else if (mimeType.equalsIgnoreCase("text/rdf")) { bs_format = bitstreamFormatService.findByShortDescription(context, "RDF XML"); } else { - bs_format = bitstreamFormatService.findByShortDescription(context, "License"); + bs_format = bitstreamFormatService.findByShortDescription(context, "License"); } Bitstream bs = bitstreamService.create(context, bundle, licenseStm); @@ -243,15 +243,15 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi } @Override - public String getLicenseURL(Context context, Item item) throws SQLException, IOException, AuthorizeException { - String licenseUri = getCCField("uri").ccItemValue(item); - if (StringUtils.isNotBlank(licenseUri)) { - return licenseUri; - } - - // JSPUI backward compatibility see https://jira.duraspace.org/browse/DS-2604 - return getStringFromBitstream(context, item, BSN_LICENSE_URL); - } + public String getLicenseURL(Context context, Item item) throws SQLException, IOException, AuthorizeException { + String licenseUri = getCCField("uri").ccItemValue(item); + if (StringUtils.isNotBlank(licenseUri)) { + return licenseUri; + } + + // JSPUI backward compatibility see https://jira.duraspace.org/browse/DS-2604 + return getStringFromBitstream(context, item, BSN_LICENSE_URL); + } @Override public String fetchLicenseRDF(Document license) @@ -273,12 +273,32 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi return result.getBuffer().toString(); } - // The following two helper methods assume that the CC - // bitstreams are short and easily expressed as byte arrays in RAM - /** * This helper method takes some bytes and stores them as a bitstream for an * item, under the CC bundle, with the given bitstream name + * + * Note: This helper method assumes that the CC + * bitstreams are short and easily expressed as byte arrays in RAM + * + * @param context + * The relevant DSpace Context. + * @param item + * parent item + * @param bundle + * parent bundle + * @param bitstream_name + * bitstream name to set + * @param format + * bitstream format + * @param bytes + * bitstream data + * @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. */ protected void setBitstreamFromBytes(Context context, Item item, Bundle bundle, String bitstream_name, BitstreamFormat format, byte[] bytes) @@ -298,6 +318,24 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi /** * This helper method wraps a String around a byte array returned from the * bitstream method further down + * + * Note: This helper method assumes that the CC + * bitstreams are short and easily expressed as byte arrays in RAM + * + * @param context + * The relevant DSpace Context. + * @param item + * parent item + * @param bitstream_name + * bitstream name to set + * @return the bitstream as string + * @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. */ protected String getStringFromBitstream(Context context, Item item, String bitstream_name) throws SQLException, IOException, @@ -316,6 +354,19 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi /** * This helper method retrieves the bytes of a bitstream for an item under * the CC bundle, with the given bitstream name + * + * @param item + * parent item + * @param bitstream_name + * bitstream name to set + * @return the bitstream + * @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. */ protected Bitstream getBitstream(Item item, String bitstream_name) throws SQLException, IOException, AuthorizeException @@ -370,26 +421,28 @@ public class CreativeCommonsServiceImpl implements CreativeCommonsService, Initi @Override public LicenseMetadataValue getCCField(String fieldId) { - return new LicenseMetadataValue(configurationService.getProperty("cc.license." + fieldId)); + return new LicenseMetadataValue(configurationService.getProperty("cc.license." + fieldId)); } @Override - public void removeLicense(Context context, LicenseMetadataValue uriField, - LicenseMetadataValue nameField, Item item) throws AuthorizeException, IOException, SQLException { - // only remove any previous licenses - String licenseUri = uriField.ccItemValue(item); - if (licenseUri != null) { - uriField.removeItemValue(context, item, licenseUri); - if (configurationService.getBooleanProperty("cc.submit.setname")) - { - String licenseName = nameField.keyedItemValue(item, licenseUri); - nameField.removeItemValue(context, item, licenseName); - } - if (configurationService.getBooleanProperty("cc.submit.addbitstream")) - { - removeLicense(context, item); - } - } - } + public void removeLicense(Context context, LicenseMetadataValue uriField, + LicenseMetadataValue nameField, Item item) + throws AuthorizeException, IOException, SQLException + { + // only remove any previous licenses + String licenseUri = uriField.ccItemValue(item); + if (licenseUri != null) { + uriField.removeItemValue(context, item, licenseUri); + if (configurationService.getBooleanProperty("cc.submit.setname")) + { + String licenseName = nameField.keyedItemValue(item, licenseUri); + nameField.removeItemValue(context, item, licenseName); + } + if (configurationService.getBooleanProperty("cc.submit.addbitstream")) + { + removeLicense(context, item); + } + } + } } diff --git a/dspace-api/src/main/java/org/dspace/license/LicenseCleanup.java b/dspace-api/src/main/java/org/dspace/license/LicenseCleanup.java index 0f24ca5234..ffbd6f7872 100644 --- a/dspace-api/src/main/java/org/dspace/license/LicenseCleanup.java +++ b/dspace-api/src/main/java/org/dspace/license/LicenseCleanup.java @@ -56,12 +56,11 @@ public class LicenseCleanup static { - try { templates = TransformerFactory.newInstance().newTemplates( - new StreamSource(CreativeCommonsServiceImpl.class - .getResourceAsStream("LicenseCleanup.xsl"))); + new StreamSource(CreativeCommonsServiceImpl.class + .getResourceAsStream("LicenseCleanup.xsl"))); } catch (TransformerConfigurationException e) { @@ -71,7 +70,7 @@ public class LicenseCleanup } /** - * @param args + * @param args the command line arguments given * @throws SQLException if database error * @throws IOException if IO error * @throws AuthorizeException if authorization error @@ -116,9 +115,7 @@ public class LicenseCleanup props.put("I" + item.getID(), "done"); i++; - } - } finally { @@ -126,12 +123,15 @@ public class LicenseCleanup .store(new FileOutputStream(processed), "processed license files, remove to restart processing from scratch"); } - } /** * Process Item, correcting CC-License if encountered. + * + * @param context + * The relevant DSpace Context. * @param item + * The item to process * @throws SQLException if database error * @throws AuthorizeException if authorization error * @throws IOException if IO error @@ -161,8 +161,8 @@ public class LicenseCleanup try { templates.newTransformer().transform( - new StreamSource(new ByteArrayInputStream(license_rdf - .getBytes())), new StreamResult(result)); + new StreamSource(new ByteArrayInputStream(license_rdf.getBytes())), + new StreamResult(result)); } catch (TransformerException e) { @@ -186,7 +186,6 @@ public class LicenseCleanup bundleService.removeBitstream(context, bundle, bitstream); bundleService.update(context, bundle); - } static final int BUFF_SIZE = 100000; @@ -196,14 +195,16 @@ public class LicenseCleanup /** * Fast stream copy routine * + * @param context + * The relevant DSpace Context. * @param b the Bitstream to be copied. * @return copy of the content of {@code b}. * @throws IOException if IO error * @throws SQLException if database error * @throws AuthorizeException if authorization error */ - public static byte[] copy(Context context, Bitstream b) throws IOException, SQLException, - AuthorizeException + public static byte[] copy(Context context, Bitstream b) + throws IOException, SQLException, AuthorizeException { InputStream in = null; ByteArrayOutputStream out = null; diff --git a/dspace-api/src/main/java/org/dspace/license/LicenseMetadataValue.java b/dspace-api/src/main/java/org/dspace/license/LicenseMetadataValue.java index 4b6e35da48..afc3793aee 100644 --- a/dspace-api/src/main/java/org/dspace/license/LicenseMetadataValue.java +++ b/dspace-api/src/main/java/org/dspace/license/LicenseMetadataValue.java @@ -32,19 +32,19 @@ public class LicenseMetadataValue { private String[] params = new String[4]; - public LicenseMetadataValue(String fieldName) - { - if (fieldName != null && fieldName.length() > 0) - { - String[] fParams = fieldName.split("\\."); - for (int i = 0; i < fParams.length; i++) - { - params[i] = fParams[i]; - } - params[3] = Item.ANY; - } - itemService = ContentServiceFactory.getInstance().getItemService(); - } + public LicenseMetadataValue(String fieldName) + { + if (fieldName != null && fieldName.length() > 0) + { + String[] fParams = fieldName.split("\\."); + for (int i = 0; i < fParams.length; i++) + { + params[i] = fParams[i]; + } + params[3] = Item.ANY; + } + itemService = ContentServiceFactory.getInstance().getItemService(); + } /** * Returns first value that matches Creative Commons 'shibboleth', @@ -75,6 +75,13 @@ public class LicenseMetadataValue { * @param item - the item to read * @param key - the key for desired value * @return value - the value associated with key or null if no such value + * @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 String keyedItemValue(Item item, String key) throws AuthorizeException, IOException, SQLException @@ -82,7 +89,7 @@ public class LicenseMetadataValue { CCLookup ccLookup = new CCLookup(); ccLookup.issue(key); String matchValue = ccLookup.getLicenseName(); - List dcvalues = itemService.getMetadata(item, params[0], params[1], params[2], params[3]); + List dcvalues = itemService.getMetadata(item, params[0], params[1], params[2], params[3]); for (MetadataValue dcvalue : dcvalues) { if (dcvalue.getValue().equals(matchValue)) @@ -96,8 +103,17 @@ public class LicenseMetadataValue { /** * Removes the passed value from the set of values for the field in passed item. * + * @param context + * The relevant DSpace Context. * @param item - the item to update * @param value - the value to remove + * @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 removeItemValue(Context context, Item item, String value) throws AuthorizeException, IOException, SQLException @@ -121,8 +137,12 @@ public class LicenseMetadataValue { /** * Adds passed value to the set of values for the field in passed item. * + * @param context + * The relevant DSpace Context. * @param item - the item to update * @param value - the value to add in this field + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public void addItemValue(Context context, Item item, String value) throws SQLException { itemService.addMetadata(context, item, params[0], params[1], params[2], params[3], value); diff --git a/dspace-api/src/main/java/org/dspace/license/service/CreativeCommonsService.java b/dspace-api/src/main/java/org/dspace/license/service/CreativeCommonsService.java index e0c188f6a0..752201ff01 100644 --- a/dspace-api/src/main/java/org/dspace/license/service/CreativeCommonsService.java +++ b/dspace-api/src/main/java/org/dspace/license/service/CreativeCommonsService.java @@ -30,96 +30,146 @@ public interface CreativeCommonsService { /** * Simple accessor for enabling of CC + * + * @return is CC enabled? */ public boolean isEnabled(); /** setLicenseRDF - * - * CC Web Service method for setting the RDF bitstream - * - */ - public void setLicenseRDF(Context context, Item item, String licenseRdf) throws SQLException, IOException, AuthorizeException; + * + * CC Web Service method for setting the RDF bitstream + * + * @param context + * The relevant DSpace Context. + * @param item + * The item to set license on. + * @param licenseRdf + * license RDF string + * @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 setLicenseRDF(Context context, Item item, String licenseRdf) + throws SQLException, IOException, AuthorizeException; /** * Used by DSpaceMetsIngester * * @param context + * The relevant DSpace Context. * @param item + * The item to set license on. * @param licenseStm + * InputStream with the license text. * @param mimeType + * License text file MIME type ("text/xml", "text/rdf" or generic) * @throws SQLException if database error + * An exception that provides information on a database access error or other errors. * @throws IOException if IO error + * A general class of exceptions produced by failed or interrupted I/O operations. * @throws AuthorizeException if authorization error + * Exception indicating the current user of the context does not have permission + * to perform a particular action. * * * // PATCHED 12/01 FROM JIRA re: mimetypes for CCLicense and License RDF wjb */ public void setLicense(Context context, Item item, - InputStream licenseStm, String mimeType) - throws SQLException, IOException, AuthorizeException; + InputStream licenseStm, String mimeType) + throws SQLException, IOException, AuthorizeException; public void removeLicense(Context context, Item item) - throws SQLException, IOException, AuthorizeException; + throws SQLException, IOException, AuthorizeException; public boolean hasLicense(Context context, Item item) - throws SQLException, IOException; + throws SQLException, IOException; - public String getLicenseURL(Context context, Item item) throws SQLException, - IOException, AuthorizeException; + public String getLicenseURL(Context context, Item item) + throws SQLException, IOException, AuthorizeException; - public String getLicenseRDF(Context context, Item item) throws SQLException, - IOException, AuthorizeException; + public String getLicenseRDF(Context context, Item item) + throws SQLException, IOException, AuthorizeException; /** * Get Creative Commons license RDF, returning Bitstream object. + * + * @param item + * bitstream's parent item * @return bitstream or null. + * @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 Bitstream getLicenseRdfBitstream(Item item) throws SQLException, - IOException, AuthorizeException; + public Bitstream getLicenseRdfBitstream(Item item) + throws SQLException, IOException, AuthorizeException; /** * Get Creative Commons license Text, returning Bitstream object. * + * @param item + * bitstream's parent item * @return bitstream or null. - * @deprecated to make uniform JSPUI and XMLUI approach the bitstream with the license in the textual format it is no longer stored (see https://jira.duraspace.org/browse/DS-2604) + * @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. + * @deprecated to make uniform JSPUI and XMLUI approach the bitstream with the license in the textual format it is no longer stored (see https://jira.duraspace.org/browse/DS-2604) */ - public Bitstream getLicenseTextBitstream(Item item) throws SQLException, - IOException, AuthorizeException; + public Bitstream getLicenseTextBitstream(Item item) + throws SQLException, IOException, AuthorizeException; /** * Get a few license-specific properties. We expect these to be cached at * least per server run. + * + * @param fieldId name of the property. + * @return its value. */ - public LicenseMetadataValue getCCField(String fieldId); - /** - * Apply same transformation on the document to retrieve only the most - * relevant part of the document passed as parameter. If no transformation - * is needed then take in consideration to empty the CreativeCommons.xml - * - * @param license - * - an element that could be contains as part of your content - * the license rdf - * @return the document license in textual format after the transformation - */ + /** + * Apply same transformation on the document to retrieve only the most + * relevant part of the document passed as parameter. If no transformation + * is needed then take in consideration to empty the CreativeCommons.xml + * + * @param license + * - an element that could be contains as part of your content + * the license rdf + * @return the document license in textual format after the transformation + */ public String fetchLicenseRDF(Document license); - /** - * Remove license information, delete also the bitstream - * - * @param context - * - DSpace Context - * @param uriField - * - the metadata field for license uri - * @param nameField - * - the metadata field for license name - * @param item - * - the item - * @throws AuthorizeException - * @throws IOException - * @throws SQLException - */ - public void removeLicense(Context context, LicenseMetadataValue uriField, - LicenseMetadataValue nameField, Item item) throws AuthorizeException, IOException, SQLException; -} \ No newline at end of file + /** + * Remove license information, delete also the bitstream + * + * @param context + * - DSpace Context + * @param uriField + * - the metadata field for license uri + * @param nameField + * - the metadata field for license name + * @param item + * - the item + * @throws AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. + * @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. + */ + public void removeLicense(Context context, LicenseMetadataValue uriField, + LicenseMetadataValue nameField, Item item) + throws AuthorizeException, IOException, SQLException; +} diff --git a/dspace-api/src/main/java/org/dspace/rdf/RDFUtil.java b/dspace-api/src/main/java/org/dspace/rdf/RDFUtil.java index 5b79856fa3..55d82004bc 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/RDFUtil.java +++ b/dspace-api/src/main/java/org/dspace/rdf/RDFUtil.java @@ -89,6 +89,7 @@ public class RDFUtil { * the DSpace configuration. Close the model * ({@link com.hp.hpl.jena.rdf.model.Model#close() Model.close()}) as soon * as possible to free system resources. + * * @param identifier A URI representing the object you want to load data about. * @return A model containing the RDF data to the specified identifier or * null if no data could be found. @@ -105,12 +106,15 @@ public class RDFUtil { * Please note that URIs can be generated for DSpaceObjects of the * type SITE, COMMUNITY, COLLECTION or ITEM only. Currently dspace-rdf * doesn't support Bundles or Bitstreams as independent entity. + * * @param context DSpace Context. * @param dso DSpace Object you want to get an identifier for. * @return URI to identify the DSO or null if no URI could be generated. * This can happen f.e. if you use a URIGenerator that uses * persistent identifier like DOIs or Handles but there is no such * identifier assigned to the provided DSO. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static String generateIdentifier(Context context, DSpaceObject dso) throws SQLException @@ -125,15 +129,20 @@ public class RDFUtil { * Please note that URIs can be generated for DSpaceObjects of the * type SITE, COMMUNITY, COLLECTION or ITEM only. Currently dspace-rdf * doesn't support Bundles or Bitstreams as independent entity. + * * @param context DSpace Context. * @param type Type of the DSpaceObject you want to generate a URI for (e.g. * {@link org.dspace.core.Constants#ITEM Constants.ITEM}. * @param id UUID of the DSpaceObject you want to generate a URI for. * @param handle Handle of the DSpaceObject you want to generate a URI for. + * @param identifier identifiers of the object. + * * @return URI to identify the DSO or null if no URI could be generated. * This can happen f.e. if you use a URIGenerator that uses * persistent identifier like DOIs or Handles but there is no such * identifier assigned to the provided DSO. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static String generateIdentifier(Context context, int type, UUID id, String handle, List identifier) @@ -147,6 +156,7 @@ public class RDFUtil { * Please note that dspace-rdf doesn't support Bundles or Bitstreams as * independent entity. You can convert DSpaceObjects of type SITE, * COMMUNITY, COLLECTION or ITEM. + * * @param context Consider that the converted data will be stored in a * triple store, that is outside the range of the DSpace * authorization mechanism. Unless you are really sure what @@ -209,6 +219,7 @@ public class RDFUtil { * Please note that dspace-rdf doesn't support Bundles or Bitstreams as * independent entity. You can convert DSpaceObjects of type SITE, * COMMUNITY, COLLECTION or ITEM. + * * @param context Consider that the converted data will be stored in a * triple store, that is outside the range of the DSpace * authorization mechanism. Unless you are really sure what @@ -305,6 +316,7 @@ public class RDFUtil { * Does the same as {@link #isPublic(Context, DSpaceObject) * isPublic(Context, DSpaceObject)} but returns a boolean instead of throwing * exceptions. For those who don't want to deal with catching exceptions. + * * @param context Consider that the converted data will be stored in a * triple store, that is outside the range of the DSpace * authorization mechanism. Unless you are really sure what @@ -331,6 +343,7 @@ public class RDFUtil { /** * Deletes the data identified by the URI from the triple store. + * * @param uri URI to identify the named graph to delete. */ public static void delete(String uri) @@ -341,10 +354,13 @@ public class RDFUtil { /** * This is a shortcut to generate an RDF identifier for a DSpaceObject and * to delete the identified data from the named graph. + * * @param ctx + * The relevant DSpace Context. * @param type DSpaceObject type (e.g. {@link Constants#ITEM Constants.ITEM}). * @param id Id of the DspaceObject. * @param handle Handle of the DSpaceObject. + * @param identifiers list of identifiers * @throws SQLException if database error * @throws RDFMissingIdentifierException In case that no Identifier could be generated. */ diff --git a/dspace-api/src/main/java/org/dspace/rdf/RDFizer.java b/dspace-api/src/main/java/org/dspace/rdf/RDFizer.java index 7fa57e7ce7..f3be1a4b7f 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/RDFizer.java +++ b/dspace-api/src/main/java/org/dspace/rdf/RDFizer.java @@ -109,6 +109,7 @@ public class RDFizer { *

* * @param context + * The relevant DSpace Context. */ protected void overrideContext(Context context) { @@ -118,6 +119,7 @@ public class RDFizer { /** * Returns whether all converted data is printed to stdout. Turtle will be * used as serialization. + * * @return {@code true} if print all generated data is to be printed to stdout */ public boolean isStdout() { @@ -128,7 +130,9 @@ public class RDFizer { * Set this to true to print all generated data to stdout. The data will be * stored as well, unless {@code dryrun} is set true. Turtle will be used * as serialization. + * * @param stdout + * if {@code true}, print all data to standard output */ public void setStdout(boolean stdout) { this.stdout = stdout; @@ -137,6 +141,7 @@ public class RDFizer { /** * Returns whether verbose information is printed to System.err. Probably * this is helpful for CLI only. + * * @return {@code true} if verbose mode is on */ public boolean isVerbose() { @@ -146,7 +151,9 @@ public class RDFizer { /** * Set this to true to print verbose information to System.err. Probably * this is helpful for CLI only. + * * @param verbose + * print verbose information to stderr */ public void setVerbose(boolean verbose) { this.verbose = verbose; @@ -154,6 +161,7 @@ public class RDFizer { /** * Returns whether this is a dry run. Probably this is helpful for CLI only. + * * @return {@code true} if dry-run mode is on */ public boolean isDryrun() { @@ -163,7 +171,9 @@ public class RDFizer { /** * Set this true to prevent any changes on the triple store. Probably this * is helpful for CLI usage only. + * * @param dryrun + * test run without any changes to the triple store */ public void setDryrun(boolean dryrun) { this.dryrun = dryrun; @@ -176,7 +186,9 @@ public class RDFizer { public void deleteAll() { report("Sending delete command to the triple store."); - if (!this.dryrun) storage.deleteAll(); + if (!this.dryrun) { + storage.deleteAll(); + } report("Deleted all data from the triplestore."); } @@ -184,17 +196,24 @@ public class RDFizer { * Delete the data about the DSpaceObject from the triplestore. * All data about descendent Subcommunities, Collections and Items will be * deleted as well. + * + * @param dso + * DSpace object + * @param reset + * reset processed status (converted or deleted from the triplestore) + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public void delete(DSpaceObject dso, boolean reset) - throws SQLException + throws SQLException { if (dso.getType() != Constants.SITE - && dso.getType() != Constants.COMMUNITY - && dso.getType() != Constants.COLLECTION - && dso.getType() != Constants.ITEM) + && dso.getType() != Constants.COMMUNITY + && dso.getType() != Constants.COLLECTION + && dso.getType() != Constants.ITEM) { throw new IllegalArgumentException(contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso) - + " is currently not supported as independent entity."); + + " is currently not supported as independent entity."); } if (dso.getType() == Constants.SITE) @@ -205,19 +224,19 @@ public class RDFizer { Callback callback = new Callback() { @Override protected void callback(DSpaceObject dso) - throws SQLException + throws SQLException { String identifier = RDFUtil.generateIdentifier(context, dso); if (StringUtils.isEmpty(identifier)) { System.err.println("Cannot determine RDF URI for " - + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso) + " " + dso.getID() + "(handle " - + dso.getHandle() + ")" + ", skipping. Please " - + "delete it specifying the RDF URI."); + + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso) + " " + dso.getID() + "(handle " + + dso.getHandle() + ")" + ", skipping. Please " + + "delete it specifying the RDF URI."); log.error("Cannot detgermine RDF URI for " - + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso) + " " + dso.getID() + "(handle " - + dso.getHandle() + ")" + ", skipping deletion."); + + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso) + " " + dso.getID() + "(handle " + + dso.getHandle() + ")" + ", skipping deletion."); return; } @@ -234,9 +253,12 @@ public class RDFizer { /** * Converts and stores all DSpaceObjects that are readable for an anonymous * user. + * + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public void convertAll() - throws SQLException + throws SQLException { report("Starting conversion of all DSpaceItems, this may take a while..."); this.convert(contentServiceFactory.getSiteService().findSite(context), true); @@ -244,7 +266,7 @@ public class RDFizer { } protected void convert(DSpaceObject dso, boolean reset) - throws SQLException + throws SQLException { if (dso.getType() != Constants.SITE && dso.getType() != Constants.COMMUNITY @@ -258,7 +280,7 @@ public class RDFizer { Callback callback = new Callback() { @Override protected void callback(DSpaceObject dso) - throws SQLException + throws SQLException { Model converted = null; try @@ -320,7 +342,7 @@ public class RDFizer { } protected void dspaceDFS(DSpaceObject dso, Callback callback, boolean check, boolean reset) - throws SQLException + throws SQLException { if (dso.getType() != Constants.SITE && dso.getType() != Constants.COMMUNITY @@ -810,6 +832,6 @@ public class RDFizer { protected abstract class Callback { protected abstract void callback(DSpaceObject dso) - throws SQLException; + throws SQLException; } } diff --git a/dspace-api/src/main/java/org/dspace/rdf/conversion/ConverterPlugin.java b/dspace-api/src/main/java/org/dspace/rdf/conversion/ConverterPlugin.java index db1d0f8ff3..4cb7c608ab 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/conversion/ConverterPlugin.java +++ b/dspace-api/src/main/java/org/dspace/rdf/conversion/ConverterPlugin.java @@ -28,9 +28,14 @@ public interface ConverterPlugin { * before converting any data! * @param dso The DSpaceObject that should be converted. * @return A Jena Model containing the generated RDF. + * @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 Model convert(Context context, DSpaceObject dso) - throws SQLException, AuthorizeException; + throws SQLException, AuthorizeException; /** * Returns all type of DSpaceObjects that are supported by this plugin. diff --git a/dspace-api/src/main/java/org/dspace/rdf/conversion/DMRM.java b/dspace-api/src/main/java/org/dspace/rdf/conversion/DMRM.java index b953976f29..9a77b02d84 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/conversion/DMRM.java +++ b/dspace-api/src/main/java/org/dspace/rdf/conversion/DMRM.java @@ -26,6 +26,7 @@ public class DMRM { public static final String NS = "http://digital-repositories.org/ontologies/dspace-metadata-mapping/0.2.0#"; /**

The namespace of the vocabulary as a string

+ * @return Namespace URI * @see #NS */ public static String getURI() {return NS;} diff --git a/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java b/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java index 83c9d91cbe..155d63b9fe 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java +++ b/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java @@ -522,6 +522,8 @@ implements ConverterPlugin * As bitstreams currently don't get Persistent Identifier in DSpace, we have * to link them using a link to the repository. This link should work with * JSPUI and XMLUI (at least it does in DSpace 4.x). + * @param context + * The relevant DSpace Context. * @param bitstream Bitstream for which a URL should be generated. * @return The link to the URL or null if the Bistream is is a Community or * Collection logo. diff --git a/dspace-api/src/main/java/org/dspace/rdf/factory/RDFFactoryImpl.java b/dspace-api/src/main/java/org/dspace/rdf/factory/RDFFactoryImpl.java index 48e2372a5c..8fa5166fba 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/factory/RDFFactoryImpl.java +++ b/dspace-api/src/main/java/org/dspace/rdf/factory/RDFFactoryImpl.java @@ -22,7 +22,7 @@ public class RDFFactoryImpl extends RDFFactory { // we have several URIGenerators that use each other as fallback // following we have to instantiate all of them and cannot use autowiring - // by type here. So we use setters and properties in spring configuration + // by type here. So we use setters and properties in Spring configuration // instead. private static final Logger log = Logger.getLogger(RDFFactoryImpl.class); diff --git a/dspace-api/src/main/java/org/dspace/rdf/storage/DOIURIGenerator.java b/dspace-api/src/main/java/org/dspace/rdf/storage/DOIURIGenerator.java index e584b49dd3..3e855af0f3 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/storage/DOIURIGenerator.java +++ b/dspace-api/src/main/java/org/dspace/rdf/storage/DOIURIGenerator.java @@ -27,8 +27,7 @@ import org.springframework.beans.factory.annotation.Required; * * @author pbecker */ -public class DOIURIGenerator -implements URIGenerator +public class DOIURIGenerator implements URIGenerator { private static final Logger log = Logger.getLogger(DOIURIGenerator.class); @@ -43,11 +42,13 @@ implements URIGenerator protected DOIService doiService; @Override - public String generateIdentifier(Context context, int type, UUID id, String handle, List identifiers) throws SQLException { + public String generateIdentifier(Context context, int type, UUID id, String handle, List identifiers) + throws SQLException + { if (type != Constants.SITE - && type != Constants.COMMUNITY - && type != Constants.COLLECTION - && type != Constants.ITEM) + && type != Constants.COMMUNITY + && type != Constants.COLLECTION + && type != Constants.ITEM) { return null; } @@ -73,9 +74,16 @@ implements URIGenerator @Override public String generateIdentifier(Context context, DSpaceObject dso) - throws SQLException + throws SQLException { - return generateIdentifier(context, dso.getType(), dso.getID(), dso.getHandle(), ContentServiceFactory.getInstance().getDSpaceObjectService(dso).getIdentifiers(context, dso)); + return generateIdentifier( + context, + dso.getType(), + dso.getID(), + dso.getHandle(), + ContentServiceFactory.getInstance().getDSpaceObjectService(dso) + .getIdentifiers(context, dso) + ); } } diff --git a/dspace-api/src/main/java/org/dspace/rdf/storage/RDFStorage.java b/dspace-api/src/main/java/org/dspace/rdf/storage/RDFStorage.java index 0e18a2fcec..05a7fe6f71 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/storage/RDFStorage.java +++ b/dspace-api/src/main/java/org/dspace/rdf/storage/RDFStorage.java @@ -31,7 +31,7 @@ public interface RDFStorage { /** * Don't use this method directly, use * {@link org.dspace.rdf.RDFUtil#loadModel(String) RDFizer.loadModel(...)} instead. - * @param uri + * @param uri Identifier for this DSO * @return the model */ public Model load(String uri); diff --git a/dspace-api/src/main/java/org/dspace/rdf/storage/URIGenerator.java b/dspace-api/src/main/java/org/dspace/rdf/storage/URIGenerator.java index d659ade4af..fe9493bbf0 100644 --- a/dspace-api/src/main/java/org/dspace/rdf/storage/URIGenerator.java +++ b/dspace-api/src/main/java/org/dspace/rdf/storage/URIGenerator.java @@ -16,8 +16,7 @@ import org.dspace.core.Context; /** * Please use - * {@link org.dspace.rdf.RDFUtil#generateIdentifier(Context, DSpaceObject)} and - * {@link org.dspace.rdf.RDFUtil#generateGraphURI(Context, DSpaceObject)} to + * {@link org.dspace.rdf.RDFUtil#generateIdentifier(Context, DSpaceObject)} to * get URIs for RDF data. * Please note that URIs can be generated for DSpaceObjects of the * type SITE, COMMUNITY, COLLECTION or ITEM only. Currently dspace-rdf @@ -38,24 +37,32 @@ public interface URIGenerator { * type SITE, COMMUNITY, COLLECTION or ITEM only. Currently dspace-rdf * doesn't support Bundles or Bitstreams as independent entity. This method * should work even if the DSpaceObject does not exist anymore. - * @param context - * @param type - * @param id - * @param handle + * @param context DSpace Context. + * @param type Type of the DSpaceObject you want to generate a URI for (e.g. + * {@link org.dspace.core.Constants#ITEM Constants.ITEM}. + * @param id UUID of the DSpaceObject you want to generate a URI for. + * @param handle Handle of the DSpaceObject you want to generate a URI for. * @param identifiers + * list of identifiers * @return May return null, if no URI could be generated. * @see org.dspace.rdf.RDFUtil#generateIdentifier(Context, DSpaceObject) + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public String generateIdentifier(Context context, int type, UUID id, String handle, List identifiers) - throws SQLException; + throws SQLException; /** * Shortcut for {@code generateIdentifier(context, dso.getType(), dso.getID(), dso.getHandle())}. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to generate identifier for * @return May return null, if no URI could be generated. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public String generateIdentifier(Context context, DSpaceObject dso) - throws SQLException; + throws SQLException; } diff --git a/dspace-api/src/main/java/org/dspace/sort/OrderFormat.java b/dspace-api/src/main/java/org/dspace/sort/OrderFormat.java index cfce6542e0..01964b32c0 100644 --- a/dspace-api/src/main/java/org/dspace/sort/OrderFormat.java +++ b/dspace-api/src/main/java/org/dspace/sort/OrderFormat.java @@ -18,15 +18,15 @@ import org.dspace.core.factory.CoreServiceFactory; * Types can be defined or configured using the plugin manager: * * plugin.named.org.dspace.sort.OrderFormatDelegate= - * org.dspace.sort.OrderFormatTitleMarc21=title - * org.dspace.sort.OrderFormatAuthor=author + * org.dspace.sort.OrderFormatTitleMarc21=title + * org.dspace.sort.OrderFormatAuthor=author * * The following standard types have been defined by default, but can be reconfigured * via the plugin manager: * - * author = org.dspace.sort.OrderFormatAuthor - * title = org.dspace.sort.OrderFormatTitle - * text = org.dspace.sort.OrderFormatText + * author = org.dspace.sort.OrderFormatAuthor + * title = org.dspace.sort.OrderFormatTitle + * text = org.dspace.sort.OrderFormatText * * IMPORTANT - If you change any of the orderings, you need to rebuild the browse sort columns * (ie. run 'index-all', or 'dsrun org.dspace.browse.InitializeBrowse') @@ -36,14 +36,14 @@ import org.dspace.core.factory.CoreServiceFactory; */ public class OrderFormat { - public static final String AUTHOR = "author"; - public static final String TITLE = "title"; - public static final String TEXT = "text"; - public static final String DATE = "date"; + public static final String AUTHOR = "author"; + public static final String TITLE = "title"; + public static final String TEXT = "text"; + public static final String DATE = "date"; public static final String AUTHORITY = "authority"; - - // Array of all available order delegates - avoids excessive calls to plugin manager - private static final String[] delegates = CoreServiceFactory.getInstance().getPluginService().getAllPluginNames(OrderFormatDelegate.class); + + // Array of all available order delegates - avoids excessive calls to plugin manager + private static final String[] delegates = CoreServiceFactory.getInstance().getPluginService().getAllPluginNames(OrderFormatDelegate.class); private static final OrderFormatDelegate authorDelegate = new OrderFormatAuthor(); private static final OrderFormatDelegate titleDelegate = new OrderFormatTitle(); @@ -53,26 +53,39 @@ public class OrderFormat /** * Generate a sort string for the given DC metadata + * @param value + * metadata value + * @param language + * metadata language code + * @param type + * metadata type + * @return sort string + * + * @see OrderFormat#AUTHOR + * @see OrderFormat#TITLE + * @see OrderFormat#TEXT + * @see OrderFormat#DATE + * @see #AUTHORITY */ public static String makeSortString(String value, String language, String type) { - OrderFormatDelegate delegate = null; - + OrderFormatDelegate delegate = null; + // If there is no value, return null if (value == null) { return null; } - // If a named index has been supplied - if (type != null && type.length() > 0) - { - // Use a delegate if one is configured + // If a named index has been supplied + if (type != null && type.length() > 0) + { + // Use a delegate if one is configured delegate = OrderFormat.getDelegate(type); - if (delegate != null) - { - return delegate.makeSortString(value, language); - } + if (delegate != null) + { + return delegate.makeSortString(value, language); + } // No delegates found, so apply defaults if (type.equalsIgnoreCase(OrderFormat.AUTHOR) && authorDelegate != null) @@ -99,9 +112,9 @@ public class OrderFormat { return authorityDelegate.makeSortString(value, language); } - } + } - return value; + return value; } /** @@ -109,18 +122,18 @@ public class OrderFormat */ private static OrderFormatDelegate getDelegate(String name) { - if (name != null && name.length() > 0) - { - // Check the cached array of names to see if the delegate has been configured - for (int idx = 0; idx < delegates.length; idx++) - { - if (delegates[idx].equals(name)) - { - return (OrderFormatDelegate)CoreServiceFactory.getInstance().getPluginService().getNamedPlugin(OrderFormatDelegate.class, name); - } - } - } - - return null; + if (name != null && name.length() > 0) + { + // Check the cached array of names to see if the delegate has been configured + for (int idx = 0; idx < delegates.length; idx++) + { + if (delegates[idx].equals(name)) + { + return (OrderFormatDelegate)CoreServiceFactory.getInstance().getPluginService().getNamedPlugin(OrderFormatDelegate.class, name); + } + } + } + + return null; } } diff --git a/dspace-api/src/main/java/org/dspace/sort/OrderFormatDate.java b/dspace-api/src/main/java/org/dspace/sort/OrderFormatDate.java index c71ef78d4f..515ef84812 100644 --- a/dspace-api/src/main/java/org/dspace/sort/OrderFormatDate.java +++ b/dspace-api/src/main/java/org/dspace/sort/OrderFormatDate.java @@ -9,7 +9,7 @@ package org.dspace.sort; /** * Standard date ordering delegate implementation. The only "special" need is - * for treat with date with only "small" year < 4 digit + * to treat dates with less than 4-digit year. * * @author Andrea Bollini */ diff --git a/dspace-api/src/main/java/org/dspace/sort/OrderFormatDelegate.java b/dspace-api/src/main/java/org/dspace/sort/OrderFormatDelegate.java index b51ef037ad..bba8265fa4 100644 --- a/dspace-api/src/main/java/org/dspace/sort/OrderFormatDelegate.java +++ b/dspace-api/src/main/java/org/dspace/sort/OrderFormatDelegate.java @@ -19,8 +19,11 @@ public interface OrderFormatDelegate * given language. Language should be supplied with the ISO-6390-1 * or ISO-639-2 standards. For example "en" or "eng". * - * @param value the string value - * @param language the language to interpret in + * @param value + * the string value + * @param language + * the language to interpret in + * @return the sort string */ public String makeSortString(String value, String language); } diff --git a/dspace-api/src/main/java/org/dspace/sort/SortOption.java b/dspace-api/src/main/java/org/dspace/sort/SortOption.java index f61c8afefc..2c595e2b2b 100644 --- a/dspace-api/src/main/java/org/dspace/sort/SortOption.java +++ b/dspace-api/src/main/java/org/dspace/sort/SortOption.java @@ -29,20 +29,20 @@ public class SortOption public static final String ASCENDING = "ASC"; public static final String DESCENDING = "DESC"; - /** the sort configuration number */ - private int number; - - /** the name of the sort */ - private String name; - - /** the metadata field to sort on */ - private String metadata; - - /** the type of data we are sorting by */ - private String type; - - /** the metadata broken down into bits for convenience */ - private String[] mdBits; + /** the number of the sort option as given in the config file */ + private int number; + + /** the name of the sort */ + private String name; + + /** the metadata field to sort on */ + private String metadata; + + /** the type of data we are sorting by */ + private String type; + + /** the metadata broken down into bits for convenience */ + private String[] mdBits; /** should the sort option be visible for user selection */ private boolean visible; @@ -53,10 +53,10 @@ public class SortOption try { Set newSortOptionsSet = new TreeSet(new Comparator() { - @Override - public int compare(SortOption sortOption, SortOption sortOption1) { - return Integer.valueOf(sortOption.getNumber()).compareTo(Integer.valueOf(sortOption1.getNumber())); - } + @Override + public int compare(SortOption sortOption, SortOption sortOption1) { + return Integer.valueOf(sortOption.getNumber()).compareTo(Integer.valueOf(sortOption1.getNumber())); + } }); int idx = 1; String option; @@ -75,39 +75,45 @@ public class SortOption log.fatal("Unable to load SortOptions", se); } } - /** - * Construct a new SortOption object with the given parameters - * - * @param number - * @param name - * @param md - * @param type - * @throws SortException if sort error - */ - public SortOption(int number, String name, String md, String type) - throws SortException - { - this.name = name; - this.type = type; - this.metadata = md; - this.number = number; + /** + * Construct a new SortOption object with the given parameters + * + * @param number + * the number of the sort option as given in the config file + * @param name + * sort option name + * @param md + * the metadata field to sort on + * @param type + * the type of data we are sorting by + * @throws SortException if sort error + */ + public SortOption(int number, String name, String md, String type) + throws SortException + { + this.name = name; + this.type = type; + this.metadata = md; + this.number = number; this.visible = true; generateMdBits(); - } + } - /** - * Construct a new SortOption object using the definition from the configuration - * - * @param number - * @param definition - * @throws SortException if sort error - */ - public SortOption(int number, String definition) - throws SortException - { - this.number = number; - - String rx = "(\\w+):([\\w\\.\\*]+):(\\w+):?(\\w*)"; + /** + * Construct a new SortOption object using the definition from the configuration + * + * @param number + * the number of the sort option as given in the config file + * @param definition + * definition from the configuration + * @throws SortException if sort error + */ + public SortOption(int number, String definition) + throws SortException + { + this.number = number; + + String rx = "(\\w+):([\\w\\.\\*]+):(\\w+):?(\\w*)"; Pattern pattern = Pattern.compile(rx); Matcher matcher = pattern.matcher(definition); @@ -133,71 +139,71 @@ public class SortOption } generateMdBits(); - } + } /** - * @return Returns the metadata. - */ - public String getMetadata() - { - return metadata; - } + * @return Returns the metadata. + */ + public String getMetadata() + { + return metadata; + } - /** - * @param metadata The metadata to set. - */ - public void setMetadata(String metadata) - { - this.metadata = metadata; - } + /** + * @param metadata The metadata to set. + */ + public void setMetadata(String metadata) + { + this.metadata = metadata; + } - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } - /** - * @param name The name to set. - */ - public void setName(String name) - { - this.name = name; - } + /** + * @param name The name to set. + */ + public void setName(String name) + { + this.name = name; + } - /** - * @return Returns the type. - */ - public String getType() - { - return type; - } + /** + * @return Returns the type. + */ + public String getType() + { + return type; + } - /** - * @param type The type to set. - */ - public void setType(String type) - { - this.type = type; - } + /** + * @param type The type to set. + */ + public void setType(String type) + { + this.type = type; + } - /** - * @return Returns the number. - */ - public int getNumber() - { - return number; - } + /** + * @return Returns the sort option number (as given in the config file). + */ + public int getNumber() + { + return number; + } - /** - * @param number The number to set. - */ - public void setNumber(int number) - { - this.number = number; - } + /** + * @param number The number to set. + */ + public void setNumber(int number) + { + this.number = number; + } /** * Should this sort option be made visible in the UI @@ -209,29 +215,29 @@ public class SortOption } /** - * @return a 3 element array of the metadata bits - */ - public String[] getMdBits() + * @return a 3-element array of the metadata bits + */ + public String[] getMdBits() { - return (String[]) ArrayUtils.clone(mdBits); + return (String[]) ArrayUtils.clone(mdBits); } - /** - * Tell the class to generate the metadata bits - * - * @throws SortException if sort error - */ + /** + * Tell the class to generate the metadata bits + * + * @throws SortException if sort error + */ private void generateMdBits() - throws SortException + throws SortException { - try - { - mdBits = interpretField(metadata, null); - } - catch(IOException e) - { - throw new SortException(e); - } + try + { + mdBits = interpretField(metadata, null); + } + catch(IOException e) + { + throw new SortException(e); + } } /** @@ -240,59 +246,64 @@ public class SortOption * representation up by its delimiter (.), and stick it in an array, inserting * the value of the init parameter when there is no metadata field part. * - * @param mfield the string representation of the metadata - * @param init the default value of the array elements - * @return a three element array with schema, element and qualifier respectively + * @param mfield the string representation of the metadata + * @param init the default value of the array elements + * @return a 3-element array with schema, element and qualifier respectively + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public final String[] interpretField(String mfield, String init) - throws IOException + throws IOException { - StringTokenizer sta = new StringTokenizer(mfield, "."); - String[] field = {init, init, init}; - - int i = 0; - while (sta.hasMoreTokens()) - { - field[i++] = sta.nextToken(); - } - - // error checks to make sure we have at least a schema and qualifier for both - if (field[0] == null || field[1] == null) - { - throw new IOException("at least a schema and element be " + - "specified in configuration. You supplied: " + mfield); - } - - return field; + StringTokenizer sta = new StringTokenizer(mfield, "."); + String[] field = {init, init, init}; + + int i = 0; + while (sta.hasMoreTokens()) + { + field[i++] = sta.nextToken(); + } + + // error checks to make sure we have at least a schema and qualifier for both + if (field[0] == null || field[1] == null) + { + throw new IOException("at least a schema and element be " + + "specified in configuration. You supplied: " + mfield); + } + + return field; } /** * Is this a date field? + * @return true if is date */ public boolean isDate() { - if ("date".equals(type)) + if ("date".equals(type)) { return true; } - return false; + return false; } /** * Is the default sort option? + * @return true if is default sort option */ public boolean isDefault() { - if (number == 0) - { - return true; - } - return false; + if (number == 0) + { + return true; + } + return false; } /** * Return all the configured sort options. + * @return a set of the configured sort options * @throws SortException if sort error */ public static Set getSortOptions() throws SortException @@ -308,6 +319,8 @@ public class SortOption /** * Get the defined sort option by number (.1, .2, etc). * @param number + * the number of the sort option as given in the config file + * @return the configured sort option with given number * @throws SortException if sort error */ public static SortOption getSortOption(int number) throws SortException @@ -325,6 +338,7 @@ public class SortOption /** * Get the default sort option - initially, just the first one defined. + * @return the first configured sort option * @throws SortException if sort error */ public static SortOption getDefaultSortOption() throws SortException diff --git a/dspace-api/src/main/java/org/dspace/statistics/Dataset.java b/dspace-api/src/main/java/org/dspace/statistics/Dataset.java index b0478b097f..ab8b3a88b9 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/Dataset.java +++ b/dspace-api/src/main/java/org/dspace/statistics/Dataset.java @@ -183,7 +183,9 @@ public class Dataset { } /** - * Returns false if this dataset only contains zero's. + * Returns false if this dataset only contains zeroes. + * + * @return false if this dataset only contains zeroes. */ public boolean containsNonZeroValues(){ if (matrix != null) { diff --git a/dspace-api/src/main/java/org/dspace/statistics/SolrLoggerServiceImpl.java b/dspace-api/src/main/java/org/dspace/statistics/SolrLoggerServiceImpl.java index 55adc561e6..e12962371e 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/SolrLoggerServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/statistics/SolrLoggerServiceImpl.java @@ -72,7 +72,7 @@ import java.util.*; public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBean { private static final Logger log = Logger.getLogger(SolrLoggerServiceImpl.class); - + protected HttpSolrServer solr; public static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; @@ -93,18 +93,18 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea private ConfigurationService configurationService; public static enum StatisticsType { - VIEW ("view"), - SEARCH ("search"), - SEARCH_RESULT ("search_result"), + VIEW ("view"), + SEARCH ("search"), + SEARCH_RESULT ("search_result"), WORKFLOW("workflow"); - private final String text; + private final String text; StatisticsType(String text) { - this.text = text; - } - public String text() { return text; } - } + this.text = text; + } + public String text() { return text; } + } protected SolrLoggerServiceImpl() { @@ -118,7 +118,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea log.info("solr-statistics.spidersfile:" + configurationService.getProperty("solr-statistics.spidersfile")); log.info("solr-statistics.server:" + configurationService.getProperty("solr-statistics.server")); log.info("usage-statistics.dbfile:" + configurationService.getProperty("usage-statistics.dbfile")); - + HttpSolrServer server = null; if (configurationService.getProperty("solr-statistics.server") != null) @@ -149,7 +149,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea //Also add the core containing the current year ! statisticYearCores.add(server.getBaseURL().replace("http://", "").replace("https://", "")); } catch (Exception e) { - log.error(e.getMessage(), e); + log.error(e.getMessage(), e); } } solr = server; @@ -207,7 +207,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea { SolrInputDocument doc1 = getCommonSolrDoc(dspaceObject, request, currentUser); if (doc1 == null) return; - if(dspaceObject instanceof Bitstream) + if (dspaceObject instanceof Bitstream) { Bitstream bit = (Bitstream) dspaceObject; List bundles = bit.getBundles(); @@ -230,42 +230,42 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } catch (Exception e) { - log.error(e.getMessage(), e); + log.error(e.getMessage(), e); } } @Override - public void postView(DSpaceObject dspaceObject, - String ip, String userAgent, String xforwardedfor, EPerson currentUser) { - if (solr == null || locationService == null) { - return; - } + public void postView(DSpaceObject dspaceObject, + String ip, String userAgent, String xforwardedfor, EPerson currentUser) { + if (solr == null || locationService == null) { + return; + } - try { - SolrInputDocument doc1 = getCommonSolrDoc(dspaceObject, ip, userAgent, xforwardedfor, - currentUser); - if (doc1 == null) - return; - if (dspaceObject instanceof Bitstream) { - Bitstream bit = (Bitstream) dspaceObject; - List bundles = bit.getBundles(); - for (Bundle bundle : bundles) { - doc1.addField("bundleName", bundle.getName()); - } - } + try { + SolrInputDocument doc1 = getCommonSolrDoc(dspaceObject, ip, userAgent, xforwardedfor, + currentUser); + if (doc1 == null) + return; + if (dspaceObject instanceof Bitstream) { + Bitstream bit = (Bitstream) dspaceObject; + List bundles = bit.getBundles(); + for (Bundle bundle : bundles) { + doc1.addField("bundleName", bundle.getName()); + } + } - doc1.addField("statistics_type", StatisticsType.VIEW.text()); + doc1.addField("statistics_type", StatisticsType.VIEW.text()); - solr.add(doc1); - // commits are executed automatically using the solr autocommit - // solr.commit(false, false); + solr.add(doc1); + // commits are executed automatically using the solr autocommit + // solr.commit(false, false); - } catch (RuntimeException re) { - throw re; - } catch (Exception e) { - log.error(e.getMessage(), e); - } - } + } catch (RuntimeException re) { + throw re; + } catch (Exception e) { + log.error(e.getMessage(), e); + } + } /** @@ -279,7 +279,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea */ protected SolrInputDocument getCommonSolrDoc(DSpaceObject dspaceObject, HttpServletRequest request, EPerson currentUser) throws SQLException { boolean isSpiderBot = request != null && SpiderDetector.isSpider(request); - if(isSpiderBot && + if (isSpiderBot && !configurationService.getBooleanProperty("usage-statistics.logBots", true)) { return null; @@ -288,7 +288,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea SolrInputDocument doc1 = new SolrInputDocument(); // Save our basic info that we already have - if(request != null){ + if (request != null) { String ip = request.getRemoteAddr(); if (isUseProxies() && request.getHeader("X-Forwarded-For") != null) { @@ -307,7 +307,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea doc1.addField("ip", ip); //Also store the referrer - if(request.getHeader("referer") != null){ + if (request.getHeader("referer") != null) { doc1.addField("referrer", request.getHeader("referer")); } @@ -321,14 +321,14 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea log.info("Failed DNS Lookup for IP:" + ip); log.debug(e.getMessage(),e); } - if(request.getHeader("User-Agent") != null) - { - doc1.addField("userAgent", request.getHeader("User-Agent")); - } - doc1.addField("isBot",isSpiderBot); + if (request.getHeader("User-Agent") != null) + { + doc1.addField("userAgent", request.getHeader("User-Agent")); + } + doc1.addField("isBot",isSpiderBot); // Save the location information if valid, save the event without // location information if not valid - if(locationService != null) + if (locationService != null) { Location location = locationService.getLocation(ip); if (location != null @@ -356,7 +356,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } } - if(dspaceObject != null){ + if (dspaceObject != null) { doc1.addField("id", dspaceObject.getID()); doc1.addField("type", dspaceObject.getType()); storeParents(doc1, dspaceObject); @@ -373,7 +373,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea protected SolrInputDocument getCommonSolrDoc(DSpaceObject dspaceObject, String ip, String userAgent, String xforwardedfor, EPerson currentUser) throws SQLException { boolean isSpiderBot = SpiderDetector.isSpider(ip); - if(isSpiderBot && + if (isSpiderBot && !configurationService.getBooleanProperty("usage-statistics.logBots", true)) { return null; @@ -407,14 +407,14 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea log.info("Failed DNS Lookup for IP:" + ip); log.debug(e.getMessage(),e); } - if(userAgent != null) - { - doc1.addField("userAgent", userAgent); - } - doc1.addField("isBot",isSpiderBot); + if (userAgent != null) + { + doc1.addField("userAgent", userAgent); + } + doc1.addField("isBot",isSpiderBot); // Save the location information if valid, save the event without // location information if not valid - if(locationService != null) + if (locationService != null) { Location location = locationService.getLocation(ip); if (location != null @@ -442,7 +442,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } } - if(dspaceObject != null){ + if (dspaceObject != null) { doc1.addField("id", dspaceObject.getID()); doc1.addField("type", dspaceObject.getType()); storeParents(doc1, dspaceObject); @@ -470,30 +470,30 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea solrDoc.addField("query", query); } - if(resultObject != null){ + if (resultObject != null) { //We have a search result solrDoc.addField("statistics_type", StatisticsType.SEARCH_RESULT.text()); - }else{ + } else { solrDoc.addField("statistics_type", StatisticsType.SEARCH.text()); } //Store the scope - if(scope != null){ + if (scope != null) { solrDoc.addField("scopeId", scope.getID()); solrDoc.addField("scopeType", scope.getType()); } - if(rpp != -1){ + if (rpp != -1) { solrDoc.addField("rpp", rpp); } - if(sortBy != null){ + if (sortBy != null) { solrDoc.addField("sortBy", sortBy); - if(order != null){ + if (order != null) { solrDoc.addField("sortOrder", order); } } - if(page != -1){ + if (page != -1) { solrDoc.addField("page", page); } @@ -505,7 +505,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } catch (Exception e) { - log.error(e.getMessage(), e); + log.error(e.getMessage(), e); } } @@ -518,19 +518,19 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea solrDoc.addField("owningColl", usageWorkflowEvent.getScope().getID()); storeParents(solrDoc, usageWorkflowEvent.getScope()); - if(usageWorkflowEvent.getWorkflowStep() != null){ + if (usageWorkflowEvent.getWorkflowStep() != null) { solrDoc.addField("workflowStep", usageWorkflowEvent.getWorkflowStep()); } - if(usageWorkflowEvent.getOldState() != null){ + if (usageWorkflowEvent.getOldState() != null) { solrDoc.addField("previousWorkflowStep", usageWorkflowEvent.getOldState()); } - if(usageWorkflowEvent.getGroupOwners() != null){ + if (usageWorkflowEvent.getGroupOwners() != null) { for (int i = 0; i < usageWorkflowEvent.getGroupOwners().length; i++) { Group group = usageWorkflowEvent.getGroupOwners()[i]; solrDoc.addField("owner", "g" + group.getID()); } } - if(usageWorkflowEvent.getEpersonOwners() != null){ + if (usageWorkflowEvent.getEpersonOwners() != null) { for (int i = 0; i < usageWorkflowEvent.getEpersonOwners().length; i++) { EPerson ePerson = usageWorkflowEvent.getEpersonOwners()[i]; solrDoc.addField("owner", "e" + ePerson.getID()); @@ -540,11 +540,11 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea solrDoc.addField("workflowItemId", usageWorkflowEvent.getWorkflowItem().getID()); EPerson submitter = ((Item) usageWorkflowEvent.getObject()).getSubmitter(); - if(submitter != null){ + if (submitter != null) { solrDoc.addField("submitter", submitter.getID()); } solrDoc.addField("statistics_type", StatisticsType.WORKFLOW.text()); - if(usageWorkflowEvent.getActor() != null){ + if (usageWorkflowEvent.getActor() != null) { solrDoc.addField("actor", usageWorkflowEvent.getActor().getID()); } @@ -553,7 +553,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea catch (Exception e) { //Log the exception, no need to send it through, the workflow shouldn't crash because of this ! - log.error(e.getMessage(), e); + log.error(e.getMessage(), e); } } @@ -652,7 +652,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea Map params = new HashMap(); params.put("q", query); params.put("rows", "10"); - if(0 < statisticYearCores.size()){ + if (0 < statisticYearCores.size()) { params.put(ShardParams.SHARDS, StringUtils.join(statisticYearCores.iterator(), ',')); } MapSolrParams solrParams = new MapSolrParams(params); @@ -680,10 +680,16 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea /** * Override to manage pages of documents + * * @param docs + * a list of Solr documents + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws SolrServerException + * Exception from the Solr server to the solrj Java client. */ public void process(List docs) throws IOException, SolrServerException { - for(SolrDocument doc : docs){ + for (SolrDocument doc : docs) { process(doc); } } @@ -691,6 +697,11 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea /** * Override to manage individual documents * @param doc + * Solr document + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws SolrServerException + * Exception from the Solr server to the solrj Java client. */ public void process(SolrDocument doc) throws IOException, SolrServerException { @@ -702,12 +713,12 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea @Override public void markRobotsByIP() { - for(String ip : SpiderDetector.getSpiderIpAddresses()){ + for (String ip : SpiderDetector.getSpiderIpAddresses()) { try { /* Result Process to alter record to be identified as a bot */ - ResultProcessor processor = new ResultProcessor(){ + ResultProcessor processor = new ResultProcessor() { @Override public void process(SolrDocument doc) throws IOException, SolrServerException { doc.removeFields("isBot"); @@ -733,11 +744,11 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } @Override - public void markRobotByUserAgent(String agent){ + public void markRobotByUserAgent(String agent) { try { /* Result Process to alter record to be identified as a bot */ - ResultProcessor processor = new ResultProcessor(){ + ResultProcessor processor = new ResultProcessor() { @Override public void process(SolrDocument doc) throws IOException, SolrServerException { doc.removeFields("isBot"); @@ -779,7 +790,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea @Override public void deleteRobotsByIP() { - for(String ip : SpiderDetector.getSpiderIpAddresses()){ + for (String ip : SpiderDetector.getSpiderIpAddresses()) { deleteIP(ip); } } @@ -796,7 +807,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea final List docsToUpdate = new ArrayList(); - ResultProcessor processor = new ResultProcessor(){ + ResultProcessor processor = new ResultProcessor() { @Override public void process(List docs) throws IOException, SolrServerException { docsToUpdate.addAll(docs); @@ -967,10 +978,10 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea if (name != null && name.matches("^[0-9]{4}\\-[0-9]{2}.*")) { /* - * if("YEAR".equalsIgnoreCase(type)) return name.substring(0, 4); - * else if("MONTH".equalsIgnoreCase(type)) return name.substring(0, - * 7); else if("DAY".equalsIgnoreCase(type)) return - * name.substring(0, 10); else if("HOUR".equalsIgnoreCase(type)) + * if ("YEAR".equalsIgnoreCase(type)) return name.substring(0, 4); + * else if ("MONTH".equalsIgnoreCase(type)) return name.substring(0, + * 7); else if ("DAY".equalsIgnoreCase(type)) return + * name.substring(0, 10); else if ("HOUR".equalsIgnoreCase(type)) * return name.substring(11, 13); */ // Get our date @@ -1081,24 +1092,24 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea // not be influenced // Choose to filter by the Legacy spider IP list (may get too long to properly filter all IP's - if(configurationService.getBooleanProperty("solr-statistics.query.filter.spiderIp",false)) + if (configurationService.getBooleanProperty("solr-statistics.query.filter.spiderIp",false)) { solrQuery.addFilterQuery(getIgnoreSpiderIPs()); } // Choose to filter by isBot field, may be overriden in future // to allow views on stats based on bots. - if(configurationService.getBooleanProperty("solr-statistics.query.filter.isBot",true)) + if (configurationService.getBooleanProperty("solr-statistics.query.filter.isBot",true)) { solrQuery.addFilterQuery("-isBot:true"); } - if(sort != null){ + if (sort != null) { solrQuery.setSortField(sort, (ascending ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc)); } String[] bundles = configurationService.getArrayProperty("solr-statistics.query.filter.bundles"); - if(bundles != null && bundles.length > 0){ + if (bundles != null && bundles.length > 0) { /** * The code below creates a query that will allow only records which do not have a bundlename @@ -1110,7 +1121,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea for (int i = 0; i < bundles.length; i++) { String bundle = bundles[i].trim(); bundleQuery.append("-bundleName:").append(bundle); - if(i != bundles.length - 1){ + if (i != bundles.length - 1) { bundleQuery.append(" AND "); } } @@ -1244,7 +1255,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea log.info("Moving: " + totalRecords + " records into core " + coreName); List filesToUpload = new ArrayList(); - for(int i = 0; i < totalRecords; i+=10000){ + for (int i = 0; i < totalRecords; i+=10000) { String solrRequestUrl = solr.getBaseURL() + "/select"; solrRequestUrl = generateURL(solrRequestUrl, yearQueryParams); @@ -1264,7 +1275,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea //Upload the data in the csv files to our new solr core ContentStreamUpdateRequest contentStreamUpdateRequest = new ContentStreamUpdateRequest("/update/csv"); contentStreamUpdateRequest.setParam("stream.contentType", "text/plain;charset=utf-8"); - contentStreamUpdateRequest.setParam("skip", "_version_"); + contentStreamUpdateRequest.setParam("skip", "_version_"); contentStreamUpdateRequest.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true); contentStreamUpdateRequest.addFile(tempCsv, "text/plain;charset=utf-8"); @@ -1284,7 +1295,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } protected HttpSolrServer createCore(HttpSolrServer solr, String coreName) throws IOException, SolrServerException { - String solrDir = configurationService.getProperty("dspace.dir") + File.separator + "solr" +File.separator; + String solrDir = configurationService.getProperty("dspace.dir") + File.separator + "solr" + File.separator; String baseSolrUrl = solr.getBaseURL().replace("statistics", ""); CoreAdminRequest.Create create = new CoreAdminRequest.Create(); create.setCoreName(coreName); @@ -1315,7 +1326,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea File tempDirectory = new File(configurationService.getProperty("dspace.dir") + File.separator + "temp" + File.separator); tempDirectory.mkdirs(); List tempCsvFiles = new ArrayList(); - for(int i = 0; i < totalRecords; i+=10000){ + for (int i = 0; i < totalRecords; i+=10000) { Map params = new HashMap(); params.put(CommonParams.Q, "*:*"); params.put(CommonParams.FQ, "-bundleName:[* TO *] AND type:" + Constants.BITSTREAM); @@ -1337,7 +1348,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea //Attempt to find the bitstream id index ! int idIndex = 0; for (int j = 0; j < header.length; j++) { - if(header[j].equals("id")){ + if (header[j].equals("id")) { idIndex = j; } } @@ -1351,28 +1362,28 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea csvp.writeNext((String[]) ArrayUtils.add(header, "bundleName")); Map bitBundleCache = new HashMap<>(); //Loop over each line (skip the headers though)! - for (int j = 1; j < csvParsed.length; j++){ + for (int j = 1; j < csvParsed.length; j++) { String[] csvLine = csvParsed[j]; //Write the default line ! String bitstreamId = csvLine[idIndex]; //Attempt to retrieve our bundle name from the cache ! String bundleName = bitBundleCache.get(bitstreamId); - if(bundleName == null){ + if (bundleName == null) { //Nothing found retrieve the bitstream Bitstream bitstream = bitstreamService.findByIdOrLegacyId(context, bitstreamId); //Attempt to retrieve our bitstream ! - if (bitstream != null){ + if (bitstream != null) { List bundles = bitstream.getBundles(); - if(bundles != null && 0 < bundles.size()){ + if (bundles != null && 0 < bundles.size()) { Bundle bundle = bundles.get(0); bundleName = bundle.getName(); - }else{ + } else { //No bundle found, we are either a collection or a community logo, check for it ! DSpaceObject parentObject = bitstreamService.getParentObject(context, bitstream); - if(parentObject instanceof Collection){ + if (parentObject instanceof Collection) { bundleName = "LOGO-COLLECTION"; - }else - if(parentObject instanceof Community){ + } else + if (parentObject instanceof Community) { bundleName = "LOGO-COMMUNITY"; } @@ -1383,7 +1394,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } //Check if we don't have a bundlename //If we don't have one & we do not need to delete the deleted bitstreams ensure that a BITSTREAM_DELETED bundle name is given ! - if(bundleName == null && !removeDeletedBitstreams){ + if (bundleName == null && !removeDeletedBitstreams) { bundleName = "BITSTREAM_DELETED"; } } @@ -1441,7 +1452,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea long totalRecords = solr.query(query).getResults().getNumFound(); System.out.println("There are " + totalRecords + " usage events in SOLR for download/view."); - for(int i = 0; i < totalRecords; i+=10000){ + for (int i = 0; i < totalRecords; i+=10000) { solrParams.set(CommonParams.START, String.valueOf(i)); QueryResponse queryResponse = solr.query(solrParams); SolrDocumentList docs = queryResponse.getResults(); @@ -1462,9 +1473,9 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea } protected void addDocumentsToFile(Context context, SolrDocumentList docs, File exportOutput) throws SQLException, ParseException, IOException { - for(SolrDocument doc : docs) { + for (SolrDocument doc : docs) { String ip = doc.get("ip").toString(); - if(ip.equals("::1")) { + if (ip.equals("::1")) { ip = "127.0.0.1"; } @@ -1475,7 +1486,7 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea //20140527162409835,view_bitstream,1292,2014-05-27T16:24:09,anonymous,127.0.0.1 DSpaceObjectLegacySupportService dsoService = contentServiceFactory.getDSpaceLegacyObjectService(Integer.parseInt(type)); DSpaceObject dso = dsoService.findByIdOrLegacyId(context, id); - if(dso == null) { + if (dso == null) { log.debug("Document no longer exists in DB. type:" + type + " id:" + id); continue; } @@ -1514,9 +1525,9 @@ public class SolrLoggerServiceImpl implements SolrLoggerService, InitializingBea return result.toString(); } - protected void addAdditionalSolrYearCores(SolrQuery solrQuery){ + protected void addAdditionalSolrYearCores(SolrQuery solrQuery) { //Only add if needed - if(0 < statisticYearCores.size()){ + if (0 < statisticYearCores.size()) { //The shards are a comma separated list of the urls to the cores solrQuery.add(ShardParams.SHARDS, StringUtils.join(statisticYearCores.iterator(), ",")); } diff --git a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsBSAdapter.java b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsBSAdapter.java index 339aae2390..d74a779ce6 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsBSAdapter.java +++ b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsBSAdapter.java @@ -53,7 +53,8 @@ public class StatisticsBSAdapter { * @param visitType the type of visits we want, from the item, bitstream, total * @param item the item from which we need our visits * @return the number of visits - * @throws SolrServerException .... + * @throws SolrServerException + * Exception from the Solr server to the solrj Java client. */ public long getNumberOfVisits(int visitType, Item item) throws SolrServerException { switch (visitType){ diff --git a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsData.java b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsData.java index 638e37edb7..962f0dca77 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsData.java +++ b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsData.java @@ -42,7 +42,12 @@ public abstract class StatisticsData { solrLoggerService = StatisticsServiceFactory.getInstance().getSolrLoggerService(); } - /** Wrap an existing Dataset in an unconfigured query factory. */ + /** + * Wrap an existing Dataset in an unconfigured query factory. + * + * @param dataset + * statistics dataset + */ protected StatisticsData(Dataset dataset) { this.dataset = dataset; datasetgenerators = new ArrayList(2); @@ -50,37 +55,70 @@ public abstract class StatisticsData { solrLoggerService = StatisticsServiceFactory.getInstance().getSolrLoggerService(); } - /** Augment the list of facets (generators). */ + /** Augment the list of facets (generators). + * + * @param set + * generator of statistics datasets + */ public void addDatasetGenerator(DatasetGenerator set){ datasetgenerators.add(set); } - /** Augment the list of filters. */ + /** Augment the list of filters. + * + * @param filter + * statistics filter + */ public void addFilters(StatisticsFilter filter){ filters.add(filter); } - /** Return the current list of generators. */ + /** Return the current list of generators. + * + * @return list of dataset generators + */ public List getDatasetGenerators() { return datasetgenerators; } - /** Return the current list of filters. */ + /** Return the current list of filters. + * + * @return list of dataset filters + */ public List getFilters() { return filters; } - /** Return the existing query result if there is one. */ + /** Return the existing query result if there is one. + * + * @return dataset existing query result dataset + */ public Dataset getDataset() { return dataset; } - /** Jam an existing query result in. */ + /** Jam an existing query result in. + * + * @param dataset + * statistics dataset + */ public void setDataset(Dataset dataset) { this.dataset = dataset; } - /** Run the accumulated query and return its results. */ + /** Run the accumulated query and return its results. + * + * @param context + * The relevant DSpace Context. + * @return accumulated query results + * @throws SQLException + * An exception that provides information on a database access error or other errors. + * @throws SolrServerException + * Exception from the Solr server to the solrj Java client. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws ParseException if the dataset cannot be parsed + */ public abstract Dataset createDataset(Context context) throws SQLException, SolrServerException, IOException, ParseException; diff --git a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java index 20db4abb45..2307ebdc1b 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java +++ b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java @@ -73,21 +73,38 @@ public class StatisticsDataVisits extends StatisticsData super(); } - /** Construct an empty query concerning a given DSpaceObject. */ + /** + * Construct an empty query concerning a given DSpaceObject. + * + * @param dso + * the target DSpace object + */ public StatisticsDataVisits(DSpaceObject dso) { super(); this.currentDso = dso; } - /** Construct an unconfigured query around a given DSO and Dataset. */ + /** + * Construct an unconfigured query around a given DSO and Dataset. + * + * @param currentDso + * the target DSpace object + * @param dataset + * the target dataset + */ public StatisticsDataVisits(DSpaceObject currentDso, Dataset dataset) { super(dataset); this.currentDso = currentDso; } - /** Construct an unconfigured query around a given Dataset. */ + /** + * Construct an unconfigured query around a given Dataset. + * + * @param dataset + * the target dataset + */ public StatisticsDataVisits(Dataset dataset) { super(dataset); @@ -99,7 +116,7 @@ public class StatisticsDataVisits extends StatisticsData { // Check if we already have one. // If we do then give it back. - if(getDataset() != null) + if (getDataset() != null) { return getDataset(); } @@ -120,7 +137,7 @@ public class StatisticsDataVisits extends StatisticsData || (1 < getDatasetGenerators().size() && getDatasetGenerators() .get(1) instanceof DatasetTimeGenerator)) { - if(getDatasetGenerators().get(0) instanceof DatasetTimeGenerator) + if (getDatasetGenerators().get(0) instanceof DatasetTimeGenerator) { dateFacet = (DatasetTimeGenerator) getDatasetGenerators().get(0); } @@ -169,12 +186,12 @@ public class StatisticsDataVisits extends StatisticsData StatisticsFilter filter = getFilters().get(i); filterQuery += "(" + filter.toQuery() + ")"; - if(i != (getFilters().size() -1)) + if (i != (getFilters().size() -1)) { filterQuery += " AND "; } } - if(StringUtils.isNotBlank(filterQuery)){ + if (StringUtils.isNotBlank(filterQuery)) { filterQuery += " AND "; } //Only use the view type and make sure old data (where no view type is present) is also supported @@ -189,20 +206,20 @@ public class StatisticsDataVisits extends StatisticsData // Run over our queries. // First how many queries do we have ? - if(dateFacet != null){ + if (dateFacet != null) { // So do all the queries and THEN do the date facet for (int i = 0; i < datasetQueries.size(); i++) { DatasetQuery dataSetQuery = datasetQueries.get(i); - if(dataSetQuery.getQueries().size() != 1){ + if (dataSetQuery.getQueries().size() != 1) { // TODO: do this - }else{ + } else { String query = dataSetQuery.getQueries().get(0).getQuery(); - if(dataSetQuery.getMax() == -1){ + if (dataSetQuery.getMax() == -1) { // We are asking from our current query all the visits faceted by date ObjectCount[] results = solrLoggerService.queryFacetDate(query, filterQuery, dataSetQuery.getMax(), dateFacet.getDateType(), dateFacet.getStartDate(), dateFacet.getEndDate(), showTotal, context); dataset = new Dataset(1, results.length); // Now that we have our results put em in a matrix - for(int j = 0; j < results.length; j++){ + for (int j = 0; j < results.length; j++) { dataset.setColLabel(j, results[j].getValue()); dataset.addValueToMatrix(0, j, results[j].getCount()); } @@ -210,7 +227,7 @@ public class StatisticsDataVisits extends StatisticsData // Now add the column label dataset.setRowLabel(0, getResultName(dataSetQuery.getName(), dataSetQuery, context)); dataset.setRowLabelAttr(0, getAttributes(dataSetQuery.getName(), dataSetQuery, context)); - }else{ + } else { // We need to get the max objects and the next part of the query on them (next part beeing the datasettimequery ObjectCount[] maxObjectCounts = solrLoggerService.queryFacetField(query, filterQuery, dataSetQuery.getFacetField(), dataSetQuery.getMax(), false, null); for (int j = 0; j < maxObjectCounts.length; j++) { @@ -220,7 +237,7 @@ public class StatisticsDataVisits extends StatisticsData // Make sure we have a dataSet - if(dataset == null) + if (dataset == null) { dataset = new Dataset(maxObjectCounts.length, maxDateFacetCounts.length); } @@ -232,27 +249,27 @@ public class StatisticsDataVisits extends StatisticsData for (int k = 0; k < maxDateFacetCounts.length; k++) { ObjectCount objectCount = maxDateFacetCounts[k]; // No need to add this many times - if(j == 0) + if (j == 0) { dataset.setColLabel(k, objectCount.getValue()); } dataset.addValueToMatrix(j, k, objectCount.getCount()); } } - if(dataset != null && !(getDatasetGenerators().get(0) instanceof DatasetTimeGenerator)){ + if (dataset != null && !(getDatasetGenerators().get(0) instanceof DatasetTimeGenerator)) { dataset.flipRowCols(); } } } } - }else{ + } else { // We do NOT have a date facet so just do queries after each other /* for (int i = 0; i < datasetQueries.size(); i++) { DatasetQuery datasetQuery = datasetQueries.get(i); - if(datasetQuery.getQueries().size() != 1){ + if (datasetQuery.getQueries().size() != 1) { // TODO: do this - }else{ + } else { String query = datasetQuery.getQueries().get(0); // Loop over the queries & do em // ObjectCount[] topCounts = SolrLogger.queryFacetField(query, ); @@ -263,13 +280,13 @@ public class StatisticsDataVisits extends StatisticsData //Do the first query ObjectCount[] topCounts1 = null; -// if(firsDataset.getQueries().size() == 1){ +// if (firsDataset.getQueries().size() == 1) { topCounts1 = queryFacetField(firsDataset, firsDataset.getQueries().get(0).getQuery(), filterQuery); -// }else{ +// } else { // TODO: do this // } // Check if we have more queries that need to be done - if(datasetQueries.size() == 2){ + if (datasetQueries.size() == 2) { DatasetQuery secondDataSet = datasetQueries.get(1); // Now do the second one ObjectCount[] topCounts2 = queryFacetField(secondDataSet, secondDataSet.getQueries().get(0).getQuery(), filterQuery); @@ -285,12 +302,12 @@ public class StatisticsDataVisits extends StatisticsData facetQueries.add(facetQuery); } - for (int i = 0; i < topCounts1.length; i++){ + for (int i = 0; i < topCounts1.length; i++) { ObjectCount count1 = topCounts1[i]; ObjectCount[] currentResult = new ObjectCount[topCounts2.length]; // Make sure we have a dataSet - if(dataset == null) + if (dataset == null) { dataset = new Dataset(topCounts2.length, topCounts1.length); } @@ -299,7 +316,7 @@ public class StatisticsDataVisits extends StatisticsData String query = firsDataset.getFacetField() + ":" + ClientUtils.escapeQueryChars(count1.getValue()); // Check if we also have a type present (if so this should be put into the query) - if("id".equals(firsDataset.getFacetField()) && firsDataset.getQueries().get(0).getDsoType() != -1) + if ("id".equals(firsDataset.getFacetField()) && firsDataset.getQueries().get(0).getDsoType() != -1) { query += " AND type:" + firsDataset.getQueries().get(0).getDsoType(); } @@ -312,7 +329,7 @@ public class StatisticsDataVisits extends StatisticsData // TODO: dit vervangen door te displayen value for (int j = 0; j < topCounts2.length; j++) { ObjectCount count2 = topCounts2[j]; - if(i == 0) { + if (i == 0) { dataset.setRowLabel(j, getResultName(count2.getValue(), secondDataSet, context)); dataset.setRowLabelAttr(j, getAttributes(count2.getValue(), secondDataSet, context)); @@ -334,12 +351,12 @@ public class StatisticsDataVisits extends StatisticsData ObjectCount count2 = topCounts2[j]; String query = firsDataset.getFacetField() + ":" + count1.getValue(); // Check if we also have a type present (if so this should be put into the query - if("id".equals(firsDataset.getFacetField()) && firsDataset.getQueries().get(0).getDsoType() != -1) + if ("id".equals(firsDataset.getFacetField()) && firsDataset.getQueries().get(0).getDsoType() != -1) query += " AND type:" + firsDataset.getQueries().get(0).getDsoType(); query += " AND " + secondDataSet.getFacetField() + ":" + count2.getValue(); // Check if we also have a type present (if so this should be put into the query - if("id".equals(secondDataSet.getFacetField()) && secondDataSet.getQueries().get(0).getDsoType() != -1) + if ("id".equals(secondDataSet.getFacetField()) && secondDataSet.getQueries().get(0).getDsoType() != -1) query += " AND type:" + secondDataSet.getQueries().get(0).getDsoType(); long count = SolrLogger.queryFacetQuery(query, filterQuery); @@ -347,7 +364,7 @@ public class StatisticsDataVisits extends StatisticsData // TODO: the show total // No need to add this many times // TODO: dit vervangen door te displayen value - if(i == 0) { + if (i == 0) { dataset.setRowLabel(j, getResultName(count2.getValue(), secondDataSet, context)); dataset.setRowLabelAttr(j, getAttributes(count2.getValue(), secondDataSet, context)); @@ -360,7 +377,7 @@ public class StatisticsDataVisits extends StatisticsData // System.out.println("BOTH"); - } else{ + } else { // Make sure we have a dataSet dataset = new Dataset(1, topCounts1.length); for (int i = 0; i < topCounts1.length; i++) { @@ -372,10 +389,10 @@ public class StatisticsDataVisits extends StatisticsData } } - if(dataset != null){ + if (dataset != null) { dataset.setRowTitle("Dataset 1"); dataset.setColTitle("Dataset 2"); - }else + } else { dataset = new Dataset(0, 0); } @@ -383,24 +400,24 @@ public class StatisticsDataVisits extends StatisticsData } protected void processAxis(Context context, DatasetGenerator datasetGenerator, List queries) throws SQLException { - if(datasetGenerator instanceof DatasetDSpaceObjectGenerator){ + if (datasetGenerator instanceof DatasetDSpaceObjectGenerator) { DatasetDSpaceObjectGenerator dspaceObjAxis = (DatasetDSpaceObjectGenerator) datasetGenerator; // Get the types involved List dsoRepresentations = dspaceObjAxis.getDsoRepresentations(); - for (int i = 0; i < dsoRepresentations.size(); i++){ + for (int i = 0; i < dsoRepresentations.size(); i++) { DatasetQuery datasetQuery = new DatasetQuery(); Integer dsoType = dsoRepresentations.get(i).getType(); boolean separate = dsoRepresentations.get(i).getSeparate(); Integer dsoLength = dsoRepresentations.get(i).getNameLength(); // Check if our type is our current object - if(currentDso != null && dsoType == currentDso.getType()){ + if (currentDso != null && dsoType == currentDso.getType()) { Query query = new Query(); query.setDso(currentDso, currentDso.getType(), dsoLength); datasetQuery.addQuery(query); - }else{ + } else { // TODO: only do this for bitstreams from an item Query query = new Query(); - if(currentDso != null && separate && dsoType == Constants.BITSTREAM){ + if (currentDso != null && separate && dsoType == Constants.BITSTREAM) { // CURRENTLY THIS IS ONLY POSSIBLE FOR AN ITEM ! ! ! ! ! ! ! // We need to get the separate bitstreams from our item and make a query for each of them Item item = (Item) currentDso; @@ -408,7 +425,7 @@ public class StatisticsDataVisits extends StatisticsData Bundle bundle = item.getBundles().get(j); for (int k = 0; k < bundle.getBitstreams().size(); k++) { Bitstream bitstream = bundle.getBitstreams().get(k); - if(!bitstream.getFormat(context).isInternal()){ + if (!bitstream.getFormat(context).isInternal()) { // Add a separate query for each bitstream query.setDso(bitstream, bitstream.getType(), dsoLength); } @@ -421,7 +438,7 @@ public class StatisticsDataVisits extends StatisticsData query.setDsoLength(dsoLength); String title = ""; - switch(dsoType){ + switch (dsoType) { case Constants.BITSTREAM: title = "Files"; break; @@ -446,14 +463,14 @@ public class StatisticsDataVisits extends StatisticsData queries.add(datasetQuery); } - }else - if(datasetGenerator instanceof DatasetTypeGenerator){ + } else + if (datasetGenerator instanceof DatasetTypeGenerator) { DatasetTypeGenerator typeAxis = (DatasetTypeGenerator) datasetGenerator; DatasetQuery datasetQuery = new DatasetQuery(); // First make sure our query is in order Query query = new Query(); - if(currentDso != null) + if (currentDso != null) { query.setDso(currentDso, currentDso.getType()); } @@ -470,19 +487,27 @@ public class StatisticsDataVisits extends StatisticsData /** * Gets the name of the DSO (example for collection: ((Collection) dso).getname(); + * + * @param value + * UUID (or legacy record ID) of the DSO in question. + * @param datasetQuery + * FIXME: PLEASE DOCUMENT. + * @param context + * The relevant DSpace Context. * @return the name of the given DSO + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ protected String getResultName(String value, DatasetQuery datasetQuery, Context context) throws SQLException { - if("continent".equals(datasetQuery.getName())){ + if ("continent".equals(datasetQuery.getName())) { value = LocationUtils.getContinentName(value, context .getCurrentLocale()); - }else - if("countryCode".equals(datasetQuery.getName())){ + } else if ("countryCode".equals(datasetQuery.getName())) { value = LocationUtils.getCountryName(value, context .getCurrentLocale()); - }else{ + } else { Query query = datasetQuery.getQueries().get(0); //TODO: CHANGE & THROW AWAY THIS ENTIRE METHOD //Check if int @@ -490,7 +515,7 @@ public class StatisticsDataVisits extends StatisticsData int dsoLength = query.getDsoLength(); try { dsoId = UUID.fromString(value).toString(); - }catch(Exception e){ + } catch (Exception e) { try { //Legacy identifier support dsoId = String.valueOf(Integer.parseInt(value)); @@ -498,36 +523,36 @@ public class StatisticsDataVisits extends StatisticsData dsoId = null; } } - if(dsoId == null && query.getDso() != null && value == null) + if (dsoId == null && query.getDso() != null && value == null) { dsoId = query.getDso().getID().toString(); } - if(dsoId != null && query.getDsoType() != -1){ - switch(query.getDsoType()){ + if (dsoId != null && query.getDsoType() != -1) { + switch (query.getDsoType()) { case Constants.BITSTREAM: Bitstream bit = bitstreamService.findByIdOrLegacyId(context, dsoId); - if(bit == null) + if (bit == null) { break; } return value; case Constants.ITEM: Item item = itemService.findByIdOrLegacyId(context, dsoId); - if(item == null) + if (item == null) { break; } String name = "untitled"; List vals = itemService.getMetadata(item, "dc", "title", null, Item.ANY); - if(vals != null && 0 < vals.size()) + if (vals != null && 0 < vals.size()) { name = vals.get(0).getValue(); } - if(dsoLength != -1 && name.length() > dsoLength){ + if (dsoLength != -1 && name.length() > dsoLength) { //Cut it off at the first space int firstSpace = name.indexOf(' ', dsoLength); - if(firstSpace != -1){ + if (firstSpace != -1) { name = name.substring(0, firstSpace) + " ..."; } } @@ -536,16 +561,16 @@ public class StatisticsDataVisits extends StatisticsData case Constants.COLLECTION: Collection coll = collectionService.findByIdOrLegacyId(context, dsoId); - if(coll == null) + if (coll == null) { break; } name = coll.getName(); - if(dsoLength != -1 && name.length() > dsoLength){ + if (dsoLength != -1 && name.length() > dsoLength) { //Cut it off at the first space int firstSpace = name.indexOf(' ', dsoLength); - if(firstSpace != -1){ + if (firstSpace != -1) { name = name.substring(0, firstSpace) + " ..."; } } @@ -553,16 +578,16 @@ public class StatisticsDataVisits extends StatisticsData case Constants.COMMUNITY: Community comm = communityService.findByIdOrLegacyId(context, dsoId); - if(comm == null) + if (comm == null) { break; } name = comm.getName(); - if(dsoLength != -1 && name.length() > dsoLength){ + if (dsoLength != -1 && name.length() > dsoLength) { //Cut it off at the first space int firstSpace = name.indexOf(' ', dsoLength); - if(firstSpace != -1){ + if (firstSpace != -1) { name = name.substring(0, firstSpace) + " ..."; } } @@ -583,7 +608,7 @@ public class StatisticsDataVisits extends StatisticsData String dsoId; try { dsoId = UUID.fromString(value).toString(); - }catch(Exception e){ + }catch (Exception e) { try { //Legacy identifier support dsoId = String.valueOf(Integer.parseInt(value)); @@ -591,16 +616,16 @@ public class StatisticsDataVisits extends StatisticsData dsoId = null; } } - if(dsoId == null && query.getDso() != null && value == null) + if (dsoId == null && query.getDso() != null && value == null) { dsoId = query.getDso().getID().toString(); } - if(dsoId != null && query.dsoType != -1){ - switch(query.dsoType){ + if (dsoId != null && query.dsoType != -1) { + switch (query.dsoType) { case Constants.BITSTREAM: Bitstream bit = bitstreamService.findByIdOrLegacyId(context, dsoId); - if(bit == null) + if (bit == null) { break; } @@ -608,7 +633,7 @@ public class StatisticsDataVisits extends StatisticsData //Get our owning item Item owningItem = null; List bunds = bit.getBundles(); - if(0 < bunds.size() && 0 < bunds.get(0).getItems().size()) + if (0 < bunds.size() && 0 < bunds.get(0).getItems().size()) { owningItem = bunds.get(0).getItems().get(0); } @@ -657,7 +682,7 @@ public class StatisticsDataVisits extends StatisticsData case Constants.ITEM: Item item = itemService.findByIdOrLegacyId(context, dsoId); - if(item == null) + if (item == null) { break; } @@ -667,7 +692,7 @@ public class StatisticsDataVisits extends StatisticsData case Constants.COLLECTION: Collection coll = collectionService.findByIdOrLegacyId(context, dsoId); - if(coll == null) + if (coll == null) { break; } @@ -677,7 +702,7 @@ public class StatisticsDataVisits extends StatisticsData case Constants.COMMUNITY: Community comm = communityService.findByIdOrLegacyId(context, dsoId); - if(comm == null) + if (comm == null) { break; } @@ -717,7 +742,7 @@ public class StatisticsDataVisits extends StatisticsData this.max = max; } - public void addQuery(Query q){ + public void addQuery(Query q) { queries.add(q); } @@ -760,12 +785,12 @@ public class StatisticsDataVisits extends StatisticsData this.owningDso = owningDso; } - public void setDso(DSpaceObject dso, int dsoType){ + public void setDso(DSpaceObject dso, int dsoType) { this.dso = dso; this.dsoType = dsoType; } - public void setDso(DSpaceObject dso, int dsoType, int length){ + public void setDso(DSpaceObject dso, int dsoType, int length) { this.dsoType = dsoType; this.dso = dso; } @@ -784,7 +809,7 @@ public class StatisticsDataVisits extends StatisticsData this.dsoLength = dsoLength; } - public int getDsoType(){ + public int getDsoType() { return dsoType; } @@ -796,28 +821,28 @@ public class StatisticsDataVisits extends StatisticsData //Time to construct our query String query = ""; //Check (& add if needed) the dsoType - if(dsoType != -1) + if (dsoType != -1) { query += "type: " + dsoType; } //Check (& add if needed) the dsoId - if(dso != null) + if (dso != null) { query += (query.equals("") ? "" : " AND "); - if(dso instanceof DSpaceObjectLegacySupport){ + if (dso instanceof DSpaceObjectLegacySupport) { query += " (id:" + dso.getID() + " OR " + ((DSpaceObjectLegacySupport) dso).getLegacyId() + ")"; - }else{ + } else { query += "id:" + dso.getID(); } } - if(owningDso != null && currentDso != null){ + if (owningDso != null && currentDso != null) { query += (query.equals("") ? "" : " AND " ); String owningStr = ""; - switch(currentDso.getType()){ + switch (currentDso.getType()) { case Constants.ITEM: owningStr = "owningItem"; break; @@ -832,7 +857,7 @@ public class StatisticsDataVisits extends StatisticsData query += owningStr; } - if(query.equals("")) + if (query.equals("")) { query = "*:*"; } diff --git a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataWorkflow.java b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataWorkflow.java index 54479d9aa4..7986df7a31 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataWorkflow.java +++ b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataWorkflow.java @@ -149,10 +149,10 @@ public class StatisticsDataWorkflow extends StatisticsData { /** - * Retrieve the total counts for the facets (total count is same query but none of the filter queries + * Retrieve the total counts for the facets (total count is same query but none of the filter queries). * @param typeGenerator the type generator - * @return as a key the - * @throws org.apache.solr.client.solrj.SolrServerException + * @return counts for each facet by name. + * @throws org.apache.solr.client.solrj.SolrServerException passed through. */ protected Map getTotalFacetCounts(DatasetTypeGenerator typeGenerator) throws SolrServerException { ObjectCount[] objectCounts = solrLoggerService.queryFacetField(getQuery(), null, typeGenerator.getType(), -1, false, null); diff --git a/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsFilter.java b/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsFilter.java index ca23438287..848e7b3d86 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsFilter.java +++ b/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsFilter.java @@ -15,6 +15,8 @@ package org.dspace.statistics.content.filter; */ public interface StatisticsFilter { - /** Convert this filter's configuration to a query string fragment. */ + /** Convert this filter's configuration to a query string fragment. + * @return a query fragment. + */ public String toQuery(); } diff --git a/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsSolrDateFilter.java b/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsSolrDateFilter.java index 72067bea09..a8ded06e62 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsSolrDateFilter.java +++ b/dspace-api/src/main/java/org/dspace/statistics/content/filter/StatisticsSolrDateFilter.java @@ -29,45 +29,71 @@ public class StatisticsSolrDateFilter implements StatisticsFilter { public StatisticsSolrDateFilter() { } - /** Set the start date as a string expression. + /** + * Set the start date as a string expression. + * + * @param startStr + * statistics start date as a string + * * Must be paired with {@link #setEndStr(String)}. */ public void setStartStr(String startStr) { this.startStr = startStr; } - /** Set the end date as a string expression. + /** + * Set the end date as a string expression. + * + * @param endStr + * statistics end date as a string + * * Must be paired with {@link #setStartStr(String)}. */ public void setEndStr(String endStr) { this.endStr = endStr; } - /** Set the range granularity: DAY, MONTH, or YEAR. */ + /** + * Set the range granularity: DAY, MONTH, or YEAR. + * + * @param typeStr + * which granularity (case insensitive string: "day" / "month" / "year") + */ public void setTypeStr(String typeStr) { this.typeStr = typeStr; } - /** Set the start date as a Date object. + /** + * Set the start date as a Date object. + * + * @param startDate + * statistics start date object + * * Must be paired with {@link #setEndDate(Date)}. */ public void setStartDate(Date startDate) { this.startDate = (startDate == null ? null : new Date(startDate.getTime())); } - /** Set the end date as a Date object. + /** + * Set the end date as a Date object. + * + * @param endDate + * statistics end date object + * * Must be paired with {@link #setStartDate(Date)}. */ public void setEndDate(Date endDate) { this.endDate = (endDate == null ? null : new Date(endDate.getTime())); } - /** Convert the date range to a filter expression. + /** + * Convert the date range to a filter expression. * @return Solr date filter expression */ @Override public String toQuery() { - if(startDate == null || endDate == null){ + if (startDate == null || endDate == null) { // We have got strings instead of dates so calculate our dates out // of these strings Calendar startCal = Calendar.getInstance(); @@ -78,12 +104,12 @@ public class StatisticsSolrDateFilter implements StatisticsFilter { startCal.set(Calendar.HOUR_OF_DAY, 0); int dateType = -1; - if(typeStr.equalsIgnoreCase("day")) { + if (typeStr.equalsIgnoreCase("day")) { dateType = Calendar.DATE; - } else if(typeStr.equalsIgnoreCase("month")) { + } else if (typeStr.equalsIgnoreCase("month")) { dateType = Calendar.MONTH; startCal.set(Calendar.DATE, 1); - } else if(typeStr.equalsIgnoreCase("year")) { + } else if (typeStr.equalsIgnoreCase("year")) { startCal.clear(Calendar.MONTH); startCal.set(Calendar.DATE, 1); dateType = Calendar.YEAR; @@ -96,7 +122,7 @@ public class StatisticsSolrDateFilter implements StatisticsFilter { if (startDate == null) { - if(startStr.startsWith("+")) + if (startStr.startsWith("+")) { startStr = startStr.substring(startStr.indexOf('+') + 1); } @@ -107,7 +133,7 @@ public class StatisticsSolrDateFilter implements StatisticsFilter { if (endDate == null) { - if(endStr.startsWith("+")) + if (endStr.startsWith("+")) { endStr = endStr.substring(endStr.indexOf('+') + 1); } diff --git a/dspace-api/src/main/java/org/dspace/statistics/service/ElasticSearchLoggerService.java b/dspace-api/src/main/java/org/dspace/statistics/service/ElasticSearchLoggerService.java index 9e851cfeb8..c64e4566af 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/service/ElasticSearchLoggerService.java +++ b/dspace-api/src/main/java/org/dspace/statistics/service/ElasticSearchLoggerService.java @@ -20,10 +20,10 @@ import java.util.HashMap; /** * Service interface class for the Elastic Search logging. - * The implementation of this class is responsible for all business logic calls for the Elastic Search logging and is autowired by spring - * - * @deprecated As of DSpace 6.0, ElasticSearch statistics are replaced by Solr statistics - * @see org.dspace.statistics.service.SolrLoggerService#SolrLoggerService + * The implementation of this class is responsible for all business logic calls for the Elastic Search logging and is autowired by Spring. + * + * @deprecated As of DSpace 6.0, ElasticSearch statistics are replaced by Solr statistics. + * @see org.dspace.statistics.service.SolrLoggerService * * @author kevinvandevelde at atmire.com */ diff --git a/dspace-api/src/main/java/org/dspace/statistics/service/SolrLoggerService.java b/dspace-api/src/main/java/org/dspace/statistics/service/SolrLoggerService.java index 57e36e8319..2244fb3cd0 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/service/SolrLoggerService.java +++ b/dspace-api/src/main/java/org/dspace/statistics/service/SolrLoggerService.java @@ -66,7 +66,7 @@ public interface SolrLoggerService { * Method just used to log the parents. *
    *
  • Community log: owning comms.
  • - *
  • Collection log: owning comms & their comms.
  • + *
  • Collection log: owning comms and their comms.
  • *
  • Item log: owning colls/comms.
  • *
  • Bitstream log: owning item/colls/comms.
  • *
@@ -87,8 +87,10 @@ public interface SolrLoggerService { * Delete data from the index, as described by a query. * * @param query description of the records to be deleted. - * @throws java.io.IOException - * @throws org.apache.solr.client.solrj.SolrServerException + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws SolrServerException + * Exception from the Solr server to the solrj Java client. */ public void removeIndex(String query) throws IOException, SolrServerException; @@ -123,18 +125,22 @@ public interface SolrLoggerService { * Query used to get values grouped by the given facet field. * * @param query - * the query to be used + * the query to be used + * @param filterQuery + * filter query * @param facetField - * the facet field on which to group our values + * the facet field on which to group our values * @param max - * the max number of values given back (in case of 10 the top 10 - * will be given) + * the max number of values given back (in case of 10 the top 10 + * will be given) * @param showTotal - * a boolean determining whether the total amount should be given - * back as the last element of the array + * a boolean determining whether the total amount should be given + * back as the last element of the array + * @param facetQueries + * list of facet queries * @return an array containing our results * @throws SolrServerException - * ... + * Exception from the Solr server to the solrj Java client. */ public ObjectCount[] queryFacetField(String query, String filterQuery, String facetField, int max, boolean showTotal, @@ -144,24 +150,28 @@ public interface SolrLoggerService { * Query used to get values grouped by the date. * * @param query - * the query to be used + * the query to be used + * @param filterQuery + * filter query * @param max - * the max number of values given back (in case of 10 the top 10 - * will be given) + * the max number of values given back (in case of 10 the top 10 + * will be given) * @param dateType - * the type to be used (example: DAY, MONTH, YEAR) + * the type to be used (example: DAY, MONTH, YEAR) * @param dateStart - * the start date Format:(-3, -2, ..) the date is calculated - * relatively on today + * the start date Format:(-3, -2, ..) the date is calculated + * relatively on today * @param dateEnd - * the end date stop Format (-2, +1, ..) the date is calculated - * relatively on today + * the end date stop Format (-2, +1, ..) the date is calculated + * relatively on today * @param showTotal - * a boolean determining whether the total amount should be given - * back as the last element of the array + * a boolean determining whether the total amount should be given + * back as the last element of the array + * @param context + * The relevant DSpace Context. * @return and array containing our results * @throws SolrServerException - * ... + * Exception from the Solr server to the solrj Java client. */ public ObjectCount[] queryFacetDate(String query, String filterQuery, int max, String dateType, String dateStart, diff --git a/dspace-api/src/main/java/org/dspace/statistics/util/ApacheLogRobotsProcessor.java b/dspace-api/src/main/java/org/dspace/statistics/util/ApacheLogRobotsProcessor.java index 33c678be65..f80c2b5f1d 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/util/ApacheLogRobotsProcessor.java +++ b/dspace-api/src/main/java/org/dspace/statistics/util/ApacheLogRobotsProcessor.java @@ -31,7 +31,7 @@ public class ApacheLogRobotsProcessor { * Creates a file containing spiders based on an Apache logfile * by analyzing users of the robots.txt file * - * @param args + * @param args the command line arguments given * @throws Exception if error */ diff --git a/dspace-api/src/main/java/org/dspace/statistics/util/ClassicDSpaceLogConverter.java b/dspace-api/src/main/java/org/dspace/statistics/util/ClassicDSpaceLogConverter.java index 2815020e3a..b226b2e6fc 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/util/ClassicDSpaceLogConverter.java +++ b/dspace-api/src/main/java/org/dspace/statistics/util/ClassicDSpaceLogConverter.java @@ -278,7 +278,7 @@ public class ClassicDSpaceLogConverter { /** * Main method to execute the converter * - * @param args CLI args + * @param args the command line arguments given */ public static void main(String[] args) { @@ -286,12 +286,18 @@ public class ClassicDSpaceLogConverter { Options options = new Options(); - options.addOption("i", "in", true, "source file ('-' or omit for standard input)"); - options.addOption("o", "out", true, "destination file or directory ('-' or omit for standard output)"); - options.addOption("m", "multiple",false, "treat the input file as having a wildcard ending"); - options.addOption("n", "newformat",false, "process new format log lines (1.6+)"); - options.addOption("v", "verbose", false, "display verbose output (useful for debugging)"); - options.addOption("h", "help", false, "help"); + options.addOption("i", "in", true, + "source file ('-' or omit for standard input)"); + options.addOption("o", "out", true, + "destination file or directory ('-' or omit for standard output)"); + options.addOption("m", "multiple", false, + "treat the input file as having a wildcard ending"); + options.addOption("n", "newformat", false, + "process new format log lines (1.6+)"); + options.addOption("v", "verbose", false, + "display verbose output (useful for debugging)"); + options.addOption("h", "help", false, + "help"); // Parse the command line arguments CommandLine line; @@ -317,10 +323,11 @@ public class ClassicDSpaceLogConverter { // Create a copy of the converter Context context = new Context(); - context.turnOffAuthorisationSystem(); - ClassicDSpaceLogConverter converter = new ClassicDSpaceLogConverter(context, - line.hasOption('v'), - newEvents); + context.turnOffAuthorisationSystem(); + ClassicDSpaceLogConverter converter = new ClassicDSpaceLogConverter( + context, + line.hasOption('v'), + newEvents); // Set up the log analyser try @@ -353,18 +360,21 @@ public class ClassicDSpaceLogConverter { System.err.println(sample + " could not be used to find a directory of log files."); System.exit(1); } - else if (children.length <= 0) + else if (children.length <= 0) { System.err.println(sample + " matched no files."); + } else + { for (String in : children) { System.err.println(in); String out = line.getOptionValue('o') + - (dir.getAbsolutePath() + - System.getProperty("file.separator") + in).substring(line.getOptionValue('i').length()); + (dir.getAbsolutePath() + + System.getProperty("file.separator") + in).substring(line.getOptionValue('i').length()); converter.convert(dir.getAbsolutePath() + System.getProperty("file.separator") + in, out); } + } } else { diff --git a/dspace-api/src/main/java/org/dspace/statistics/util/DnsLookup.java b/dspace-api/src/main/java/org/dspace/statistics/util/DnsLookup.java index eb605b6b02..de941a3eb4 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/util/DnsLookup.java +++ b/dspace-api/src/main/java/org/dspace/statistics/util/DnsLookup.java @@ -55,6 +55,10 @@ public class DnsLookup { /** * Resolve a host name to an IPv4 address. + * + * @param hostname + * hostname to resolve to IP + * @return IPv4 address * @throws IOException from infrastructure or no resolution. */ public static String forward(String hostname) diff --git a/dspace-api/src/main/java/org/dspace/statistics/util/IPTable.java b/dspace-api/src/main/java/org/dspace/statistics/util/IPTable.java index ff2d8c5b7f..597932c893 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/util/IPTable.java +++ b/dspace-api/src/main/java/org/dspace/statistics/util/IPTable.java @@ -28,6 +28,9 @@ public class IPTable { * Can be full v4 IP, subnet or range string * * @param ip + * IP address(es) + * @throws IPFormatException + * Exception Class to deal with IPFormat errors. */ public void add(String ip) throws IPFormatException { @@ -116,6 +119,7 @@ public class IPTable { * @param ip the address to be tested * @return true if {@code ip} is within this table's limits * @throws IPFormatException + * Exception Class to deal with IPFormat errors. */ public boolean contains(String ip) throws IPFormatException { diff --git a/dspace-api/src/main/java/org/dspace/statistics/util/SpiderDetector.java b/dspace-api/src/main/java/org/dspace/statistics/util/SpiderDetector.java index e508d03618..1def91ffd8 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/util/SpiderDetector.java +++ b/dspace-api/src/main/java/org/dspace/statistics/util/SpiderDetector.java @@ -51,7 +51,7 @@ public class SpiderDetector { = Collections.synchronizedList(new ArrayList()); /** - * Utility method which reads lines from a file & returns them in a Set. + * Utility method which reads lines from a file and returns them in a Set. * * @param patternFile the location of our spider file * @return a vector full of patterns @@ -259,6 +259,7 @@ public class SpiderDetector { * Static Service Method for testing spiders against existing spider files. * * @param request + * Servlet's HTTP request object. * @return true|false if the request was detected to be from a spider. */ public static boolean isSpider(HttpServletRequest request) @@ -273,6 +274,7 @@ public class SpiderDetector { * Check individual IP is a spider. * * @param ip + * IP address to check * @return if is spider IP */ public static boolean isSpider(String ip) { diff --git a/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporter.java b/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporter.java index 237c54e048..bb0b3397d5 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporter.java +++ b/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporter.java @@ -410,7 +410,7 @@ public class StatisticsImporter } } System.out.println(" done!"); - } + } /** * Print the help message @@ -429,23 +429,29 @@ public class StatisticsImporter /** * Main method to run the statistics importer. * - * @param args The command line arguments + * @param args the command line arguments given * @throws Exception If something goes wrong */ - public static void main(String[] args) throws Exception + public static void main(String[] args) throws Exception { - CommandLineParser parser = new PosixParser(); + CommandLineParser parser = new PosixParser(); - Options options = new Options(); + Options options = new Options(); - options.addOption("i", "in", true, "the input file ('-' or omit for standard input)"); - options.addOption("l", "local", false, "developers tool - map external log file to local handles"); - options.addOption("m", "multiple", false, "treat the input file as having a wildcard ending"); - options.addOption("s", "skipdns", false, "skip performing reverse DNS lookups on IP addresses"); - options.addOption("v", "verbose", false, "display verbose output (useful for debugging)"); - options.addOption("h", "help", false, "help"); + options.addOption("i", "in", true, + "the input file ('-' or omit for standard input)"); + options.addOption("l", "local", false, + "developers tool - map external log file to local handles"); + options.addOption("m", "multiple", false, + "treat the input file as having a wildcard ending"); + options.addOption("s", "skipdns", false, + "skip performing reverse DNS lookups on IP addresses"); + options.addOption("v", "verbose", false, + "display verbose output (useful for debugging)"); + options.addOption("h", "help", false, + "help"); - CommandLine line = parser.parse(options, args); + CommandLine line = parser.parse(options, args); // Did the user ask to see the help? if (line.hasOption('h')) @@ -462,8 +468,8 @@ public class StatisticsImporter // (useful if using someone else's log file for testing) boolean local = line.hasOption('l'); - // We got all our parameters now get the rest - Context context = new Context(); + // We got all our parameters now get the rest + Context context = new Context(); // Verbose option boolean verbose = line.hasOption('v'); @@ -474,7 +480,7 @@ public class StatisticsImporter { System.out.println("Writing to solr server at: " + sserver); } - solr = new HttpSolrServer(sserver); + solr = new HttpSolrServer(sserver); String dbfile = ConfigurationManager.getProperty("usage-statistics", "dbfile"); try @@ -522,8 +528,8 @@ public class StatisticsImporter /** * Inner class to hold a cache of reverse lookups of IP addresses - * @param - * @param + * @param key type. + * @param value type. */ static class DNSCache extends LinkedHashMap { diff --git a/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporterElasticSearch.java b/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporterElasticSearch.java index 709adfcf3c..52969c9030 100644 --- a/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporterElasticSearch.java +++ b/dspace-api/src/main/java/org/dspace/statistics/util/StatisticsImporterElasticSearch.java @@ -358,7 +358,7 @@ public class StatisticsImporterElasticSearch { /** * Main method to run the statistics importer. * - * @param args The command line arguments + * @param args the command line arguments given * @throws Exception If something goes wrong */ public static void main(String[] args) throws Exception diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreMigrate.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreMigrate.java index 0d0754eccb..c1a60cf207 100644 --- a/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreMigrate.java +++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreMigrate.java @@ -29,8 +29,7 @@ public class BitStoreMigrate { /** * Migrates asset store. * - * @param argv - - * Command-line arguments + * @param argv the command line arguments given */ public static void main(String[] argv) { diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreService.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreService.java index bdcc622fe6..fdd2f75d5f 100644 --- a/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreService.java +++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/BitStoreService.java @@ -24,28 +24,30 @@ public interface BitStoreService /** * Initialize the asset store * + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ - public void init() throws IOException; + public void init() throws IOException; /** * Return an identifier unique to this asset store instance * * @return a unique ID */ - public String generateId(); - + public String generateId(); + /** * Retrieve the bits for bitstream * * @param bitstream - * - * @exception java.io.IOException - * If a problem occurs while retrieving the bits, or if no - * asset with ID exists in the store + * DSpace Bitstream object + * @throws java.io.IOException + * If a problem occurs while retrieving the bits, or if no + * asset with ID exists in the store * * @return The stream of bits */ - public InputStream get(Bitstream bitstream) throws IOException; + public InputStream get(Bitstream bitstream) throws IOException; /** * Store a stream of bits. @@ -56,37 +58,37 @@ public interface BitStoreService *

* * @param bitstream - * The bitstream object + * The bitstream object * @param inputStream - * The stream of bits - * @exception java.io.IOException - * If a problem occurs while storing the bits + * The stream of bits + * @throws java.io.IOException + * If a problem occurs while storing the bits */ - public void put(Bitstream bitstream, InputStream inputStream) throws IOException; + public void put(Bitstream bitstream, InputStream inputStream) throws IOException; /** * Obtain technical metadata about an asset in the asset store. * * @param bitstream - * The bitstream to describe + * The bitstream to describe * @param attrs - * A Map whose keys consist of desired metadata fields + * A Map whose keys consist of desired metadata fields * - * @exception java.io.IOException - * If a problem occurs while obtaining metadata + * @throws java.io.IOException + * If a problem occurs while obtaining metadata * @return attrs - * A Map with key/value pairs of desired metadata - * If file not found, then return null + * A Map with key/value pairs of desired metadata + * If file not found, then return null */ - public Map about(Bitstream bitstream, Map attrs) throws IOException; + public Map about(Bitstream bitstream, Map attrs) throws IOException; /** * Remove an asset from the asset store. * * @param bitstream - * The bitstream of the asset to delete - * @exception java.io.IOException - * If a problem occurs while removing the asset + * The bitstream of the asset to delete + * @throws java.io.IOException + * If a problem occurs while removing the asset */ - public void remove(Bitstream bitstream) throws IOException; + public void remove(Bitstream bitstream) throws IOException; } diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/BitstreamStorageServiceImpl.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/BitstreamStorageServiceImpl.java index f7bae8da27..a854bc08ff 100644 --- a/dspace-api/src/main/java/org/dspace/storage/bitstore/BitstreamStorageServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/BitstreamStorageServiceImpl.java @@ -141,7 +141,7 @@ public class BitstreamStorageServiceImpl implements BitstreamStorageService, Ini * @param bitstreamPath The relative path of the bitstream to be registered. * The path is relative to the path of ths assetstore. * @return The ID of the registered bitstream - * @exception SQLException + * @throws SQLException * If a problem occurs accessing the RDBMS * @throws IOException if IO error */ @@ -337,9 +337,16 @@ public class BitstreamStorageServiceImpl implements BitstreamStorageService, Ini /** * * @param context - * @param bitstream the bitstream to be cloned + * The relevant DSpace Context. + * @param bitstream + * the bitstream to be cloned * @return id of the clone bitstream. - * @throws SQLException if database error + * 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 Bitstream clone(Context context, Bitstream bitstream) throws SQLException, IOException, AuthorizeException { @@ -355,7 +362,16 @@ public class BitstreamStorageServiceImpl implements BitstreamStorageService, Ini /** * Migrates all assets off of one assetstore to another * @param assetstoreSource + * source assetstore * @param assetstoreDestination + * destination assetstore + * @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 migrate(Context context, Integer assetstoreSource, Integer assetstoreDestination, boolean deleteOld, Integer batchCommitSize) throws IOException, SQLException, AuthorizeException { //Find all the bitstreams on the old source, copy it to new destination, update store_number, save, remove old diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/Cleanup.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/Cleanup.java index a3634c7581..c62d6cb342 100644 --- a/dspace-api/src/main/java/org/dspace/storage/bitstore/Cleanup.java +++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/Cleanup.java @@ -31,8 +31,7 @@ public class Cleanup /** * Cleans up asset store. * - * @param argv - - * Command-line arguments + * @param argv the command line arguments given */ public static void main(String[] argv) { @@ -52,7 +51,7 @@ public class Cleanup options.addOption("h", "help", false, "Help"); try - { + { line = parser.parse(options, argv); } catch (ParseException e) @@ -72,10 +71,10 @@ public class Cleanup // Prune stage if (line.hasOption('l')) { - log.debug("option l used setting flag to leave db records"); + log.debug("option l used setting flag to leave db records"); deleteDbRecords = false; } - log.debug("leave db records = " + deleteDbRecords); + log.debug("leave db records = " + deleteDbRecords); StorageServiceFactory.getInstance().getBitstreamStorageService().cleanup(deleteDbRecords, line.hasOption('v')); System.exit(0); diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/DSBitStoreService.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/DSBitStoreService.java index 380b476e23..6d5e3fc166 100644 --- a/dspace-api/src/main/java/org/dspace/storage/bitstore/DSBitStoreService.java +++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/DSBitStoreService.java @@ -80,7 +80,7 @@ public class DSBitStoreService implements BitStoreService * * @param bitstream * The ID of the asset to retrieve - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while retrieving the bits * * @return The stream of bits, or null @@ -106,7 +106,7 @@ public class DSBitStoreService implements BitStoreService * * @param in * The stream of bits to store - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while storing the bits */ public void put(Bitstream bitstream, InputStream in) throws IOException @@ -156,7 +156,7 @@ public class DSBitStoreService implements BitStoreService * @param attrs * A Map whose keys consist of desired metadata fields * - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while obtaining metadata * @return attrs * A Map with key/value pairs of desired metadata @@ -209,7 +209,7 @@ public class DSBitStoreService implements BitStoreService * * @param bitstream * The asset to delete - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while removing the asset */ public void remove(Bitstream bitstream) throws IOException @@ -274,7 +274,7 @@ public class DSBitStoreService implements BitStoreService * * @return The corresponding file in the file system, or null * - * @exception IOException + * @throws IOException * If a problem occurs while determining the file */ protected File getFile(Bitstream bitstream) throws IOException diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java index fb3a5756c5..200f2ff1c8 100644 --- a/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java +++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java @@ -49,13 +49,13 @@ public class S3BitStoreService implements BitStoreService private String awsRegionName; /** container for all the assets */ - private String bucketName = null; + private String bucketName = null; /** (Optional) subfolder within bucket where objects are stored */ private String subfolder = null; - - /** S3 service */ - private AmazonS3 s3Service = null; + + /** S3 service */ + private AmazonS3 s3Service = null; public S3BitStoreService() { @@ -69,7 +69,7 @@ public class S3BitStoreService implements BitStoreService * - bucket name */ public void init() throws IOException { - if(StringUtils.isBlank(getAwsAccessKey()) || StringUtils.isBlank(getAwsSecretKey())) { + if (StringUtils.isBlank(getAwsAccessKey()) || StringUtils.isBlank(getAwsSecretKey())) { log.warn("Empty S3 access or secret"); } @@ -78,13 +78,13 @@ public class S3BitStoreService implements BitStoreService s3Service = new AmazonS3Client(awsCredentials); // bucket name - if(StringUtils.isEmpty(bucketName)) { + if (StringUtils.isEmpty(bucketName)) { bucketName = "dspace-asset-" + ConfigurationManager.getProperty("dspace.hostname"); log.warn("S3 BucketName is not configured, setting default: " + bucketName); } try { - if(! s3Service.doesBucketExist(bucketName)) { + if (! s3Service.doesBucketExist(bucketName)) { s3Service.createBucket(bucketName); log.info("Creating new S3 Bucket: " + bucketName); } @@ -96,7 +96,7 @@ public class S3BitStoreService implements BitStoreService } // region - if(StringUtils.isNotBlank(awsRegionName)) { + if (StringUtils.isNotBlank(awsRegionName)) { try { Regions regions = Regions.fromName(awsRegionName); Region region = Region.getRegion(regions); @@ -109,44 +109,44 @@ public class S3BitStoreService implements BitStoreService log.info("AWS S3 Assetstore ready to go! bucket:"+bucketName); } - + - - /** + + /** * Return an identifier unique to this asset store instance * * @return a unique ID */ - public String generateId() - { + public String generateId() + { return Utils.generateKey(); - } + } - /** + /** * Retrieve the bits for the asset with ID. If the asset does not * exist, returns null. * * @param bitstream * The ID of the asset to retrieve - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while retrieving the bits * * @return The stream of bits, or null */ - public InputStream get(Bitstream bitstream) throws IOException - { + public InputStream get(Bitstream bitstream) throws IOException + { String key = getFullKey(bitstream.getInternalId()); - try - { + try + { S3Object object = s3Service.getObject(new GetObjectRequest(bucketName, key)); - return (object != null) ? object.getObjectContent() : null; - } + return (object != null) ? object.getObjectContent() : null; + } catch (Exception e) - { + { log.error("get("+key+")", e); - throw new IOException(e); - } - } + throw new IOException(e); + } + } /** * Store a stream of bits. @@ -158,11 +158,11 @@ public class S3BitStoreService implements BitStoreService * * @param in * The stream of bits to store - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while storing the bits */ - public void put(Bitstream bitstream, InputStream in) throws IOException - { + public void put(Bitstream bitstream, InputStream in) throws IOException + { String key = getFullKey(bitstream.getInternalId()); //Copy istream to temp file, and send the file, with some metadata File scratchFile = File.createTempFile(bitstream.getInternalId(), "s3bs"); @@ -183,11 +183,11 @@ public class S3BitStoreService implements BitStoreService log.error("put(" + bitstream.getInternalId() +", is)", e); throw new IOException(e); } finally { - if(scratchFile.exists()) { + if (scratchFile.exists()) { scratchFile.delete(); } } - } + } /** * Obtain technical metadata about an asset in the asset store. @@ -200,14 +200,14 @@ public class S3BitStoreService implements BitStoreService * @param attrs * A Map whose keys consist of desired metadata fields * - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while obtaining metadata * @return attrs * A Map with key/value pairs of desired metadata * If file not found, then return null */ - public Map about(Bitstream bitstream, Map attrs) throws IOException - { + public Map about(Bitstream bitstream, Map attrs) throws IOException + { String key = getFullKey(bitstream.getInternalId()); try { ObjectMetadata objectMetadata = s3Service.getObjectMetadata(bucketName, key); @@ -226,7 +226,7 @@ public class S3BitStoreService implements BitStoreService return attrs; } } catch (AmazonS3Exception e) { - if(e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { + if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) { return null; } } catch (Exception e) { @@ -234,18 +234,18 @@ public class S3BitStoreService implements BitStoreService throw new IOException(e); } return null; - } + } /** * Remove an asset from the asset store. An irreversible operation. * * @param bitstream * The asset to delete - * @exception java.io.IOException + * @throws java.io.IOException * If a problem occurs while removing the asset */ - public void remove(Bitstream bitstream) throws IOException - { + public void remove(Bitstream bitstream) throws IOException + { String key = getFullKey(bitstream.getInternalId()); try { s3Service.deleteObject(bucketName, key); @@ -253,15 +253,16 @@ public class S3BitStoreService implements BitStoreService log.error("remove("+key+")", e); throw new IOException(e); } - } + } /** * Utility Method: Prefix the key with a subfolder, if this instance assets are stored within subfolder * @param id + * DSpace bitstream internal ID * @return full key prefixed with a subfolder, if applicable */ public String getFullKey(String id) { - if(StringUtils.isNotEmpty(subfolder)) { + if (StringUtils.isNotEmpty(subfolder)) { return subfolder + "/" + id; } else { return id; @@ -311,44 +312,45 @@ public class S3BitStoreService implements BitStoreService this.subfolder = subfolder; } - /** - * Contains a command-line testing tool. Expects arguments: - * -a accessKey -s secretKey -f assetFileName - * - * @param args - * Command line arguments - */ - public static void main(String[] args) throws Exception - { + /** + * Contains a command-line testing tool. Expects arguments: + * -a accessKey -s secretKey -f assetFileName + * + * @param args the command line arguments given + * @throws Exception + * generic exception + */ + public static void main(String[] args) throws Exception + { //TODO use proper CLI, or refactor to be a unit test. Can't mock this without keys though. - // parse command line - String assetFile = null; - String accessKey = null; - String secretKey = null; + // parse command line + String assetFile = null; + String accessKey = null; + String secretKey = null; - for (int i = 0; i < args.length; i+= 2) - { - if (args[i].startsWith("-a")) - { - accessKey = args[i+1]; - } - else if (args[i].startsWith("-s")) - { - secretKey = args[i+1]; - } - else if (args[i].startsWith("-f")) - { - assetFile = args[i+1]; - } - } + for (int i = 0; i < args.length; i+= 2) + { + if (args[i].startsWith("-a")) + { + accessKey = args[i+1]; + } + else if (args[i].startsWith("-s")) + { + secretKey = args[i+1]; + } + else if (args[i].startsWith("-f")) + { + assetFile = args[i+1]; + } + } - if (accessKey == null || secretKey == null ||assetFile == null) - { - System.out.println("Missing arguments - exiting"); - return; - } - S3BitStoreService store = new S3BitStoreService(); + if (accessKey == null || secretKey == null ||assetFile == null) + { + System.out.println("Missing arguments - exiting"); + return; + } + S3BitStoreService store = new S3BitStoreService(); AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); @@ -378,8 +380,8 @@ public class S3BitStoreService implements BitStoreService System.out.println("Metadata after put():"); while (iter.hasNext()) { - String key = (String)iter.next(); - System.out.println( key + ": " + (String)attrs.get(key) ); + String key = (String)iter.next(); + System.out.println( key + ": " + (String)attrs.get(key) ); } // Case 2: get metadata and compare System.out.print("about() file with ID " + id + ": "); @@ -391,8 +393,8 @@ public class S3BitStoreService implements BitStoreService System.out.println("Metadata after about():"); while (iter.hasNext()) { - String key = (String)iter.next(); - System.out.println( key + ": " + (String)attrs.get(key) ); + String key = (String)iter.next(); + System.out.println( key + ": " + (String)attrs.get(key) ); } // Case 3: retrieve asset and compare bits System.out.print("get() file with ID " + id + ": "); @@ -413,5 +415,5 @@ public class S3BitStoreService implements BitStoreService // should get nothing back now - will throw exception store.get(id); */ - } + } } diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/service/BitstreamStorageService.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/service/BitstreamStorageService.java index cc9709cf27..5258e1cc81 100644 --- a/dspace-api/src/main/java/org/dspace/storage/bitstore/service/BitstreamStorageService.java +++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/service/BitstreamStorageService.java @@ -66,21 +66,23 @@ public interface BitstreamStorageService { * true: * *
    - *
  • Neither bits nor RDBMS metadata entries have been stored. + *
  • Neither bits nor RDBMS metadata entries have been stored.
  • *
  • RDBMS metadata entries with the deleted flag set have been stored, - * but no bits. + * but no bits.
  • *
  • RDBMS metadata entries with the deleted flag set have been stored, - * and some or all of the bits have also been stored. + * and some or all of the bits have also been stored.
  • *
* * @param context - * The current context + * The current context + * @param bitstream + * The bitstream to store * @param is - * The stream of bits to store - * @exception java.io.IOException - * If a problem occurs while storing the bits - * @exception java.sql.SQLException - * If a problem occurs accessing the RDBMS + * The stream of bits to store + * @throws java.io.IOException + * If a problem occurs while storing the bits + * @throws java.sql.SQLException + * If a problem occurs accessing the RDBMS * * @return The ID of the stored bitstream */ @@ -88,31 +90,36 @@ public interface BitstreamStorageService { /** - * Register a bitstream already in storage. - * - * @param context - * The current context - * @param assetstore The assetstore number for the bitstream to be - * registered - * @param bitstreamPath The relative path of the bitstream to be registered. - * The path is relative to the path of ths assetstore. - * @return The ID of the registered bitstream - * @exception SQLException - * If a problem occurs accessing the RDBMS - * @throws IOException if IO error - */ - public UUID register(Context context, Bitstream bitstream, int assetstore, String bitstreamPath) + * Register a bitstream already in storage. + * + * @param context + * The current context + * @param bitstream + * The bitstream to register + * @param assetstore The assetstore number for the bitstream to be + * registered + * @param bitstreamPath The relative path of the bitstream to be registered. + * The path is relative to the path of ths assetstore. + * @return The ID of the registered bitstream + * @throws SQLException + * If a problem occurs accessing the RDBMS + * @throws IOException if IO error + * @throws AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. + */ + public UUID register(Context context, Bitstream bitstream, int assetstore, String bitstreamPath) throws SQLException, IOException, AuthorizeException; public Map computeChecksum(Context context, Bitstream bitstream) throws IOException; /** - * Does the internal_id column in the bitstream row indicate the bitstream - * is a registered file - * - * @param internalId the value of the internal_id column - * @return true if the bitstream is a registered file - */ + * Does the internal_id column in the bitstream row indicate the bitstream + * is a registered file + * + * @param internalId the value of the internal_id column + * @return true if the bitstream is a registered file + */ public boolean isRegisteredBitstream(String internalId); /** @@ -120,15 +127,14 @@ public interface BitstreamStorageService { * exist, or is marked deleted, returns null. * * @param context - * The current context + * The current context * @param bitstream - * The bitstream to retrieve - * @exception IOException - * If a problem occurs while retrieving the bits - * @exception SQLException - * If a problem occurs accessing the RDBMS - * + * The bitstream to retrieve * @return The stream of bits, or null + * @throws IOException + * If a problem occurs while retrieving the bits + * @throws SQLException + * If a problem occurs accessing the RDBMS */ public InputStream retrieve(Context context, Bitstream bitstream) throws SQLException, IOException; @@ -139,11 +145,16 @@ public interface BitstreamStorageService { * be undone. * * @param deleteDbRecords if true deletes the database records otherwise it - * only deletes the files and directories in the assetstore - * @exception IOException - * If a problem occurs while cleaning up - * @exception SQLException - * If a problem occurs accessing the RDBMS + * only deletes the files and directories in the assetstore + * @param verbose + * verbosity flag + * @throws IOException + * If a problem occurs while cleaning up + * @throws SQLException + * If a problem occurs accessing the RDBMS + * @throws AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ public void cleanup(boolean deleteDbRecords, boolean verbose) throws SQLException, IOException, AuthorizeException; @@ -152,6 +163,7 @@ public interface BitstreamStorageService { /** * Print out (log/out) a listing of the assetstores configured, and how many assets they contain * @param context + * The relevant DSpace Context. * @throws SQLException if database error */ public void printStores(Context context) throws SQLException; @@ -159,10 +171,22 @@ public interface BitstreamStorageService { /** * Migrate all the assets from assetstoreSource to assetstoreDestination * @param context + * The relevant DSpace Context. * @param assetstoreSource + * source assetstore * @param assetstoreDestination + * destination assetstore * @param deleteOld + * whether to delete files from the source assetstore after migration * @param batchCommitSize + * batch size + * @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 migrate(Context context, Integer assetstoreSource, Integer assetstoreDestination, boolean deleteOld, Integer batchCommitSize) throws IOException, SQLException, AuthorizeException; diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseConfigVO.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseConfigVO.java index 89177b99d2..f230e8f5d4 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseConfigVO.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseConfigVO.java @@ -10,7 +10,7 @@ package org.dspace.storage.rdbms; /** * Value object for the Database configuration, can be used to get the database configuration parameters. * The config parameters are retrieved by the implementation of the org.dspace.core.DBConnection object. - * This class should never be used to store configuration, it is just used to export & can be used for display purposes + * This class should never be used to store configuration, it is just used to export and can be used for display purposes * * @author kevinvandevelde at atmire.com */ diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseUtils.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseUtils.java index cf8195f6a0..5b3dbef448 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseUtils.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/DatabaseUtils.java @@ -76,7 +76,7 @@ public class DatabaseUtils /** * Commandline tools for managing database changes, etc. - * @param argv + * @param argv the command line arguments given */ public static void main(String[] argv) { @@ -98,7 +98,7 @@ public class DatabaseUtils Flyway flyway = setupFlyway(dataSource); // "test" = Test Database Connection - if(argv[0].equalsIgnoreCase("test")) + if (argv[0].equalsIgnoreCase("test")) { // Try to connect to the database System.out.println("\nAttempting to connect to database"); @@ -113,7 +113,7 @@ public class DatabaseUtils boolean issueFound = printDBIssues(connection); // If issues found, exit with an error status (even if connection succeeded). - if(issueFound) + if (issueFound) System.exit(1); else System.exit(0); @@ -127,7 +127,7 @@ public class DatabaseUtils System.exit(1); } } - else if(argv[0].equalsIgnoreCase("info") || argv[0].equalsIgnoreCase("status")) + else if (argv[0].equalsIgnoreCase("info") || argv[0].equalsIgnoreCase("status")) { try(Connection connection = dataSource.getConnection()) { @@ -140,7 +140,7 @@ public class DatabaseUtils // If Flyway is NOT yet initialized, also print the determined version information // NOTE: search is case sensitive, as flyway table name is ALWAYS lowercase, // See: http://flywaydb.org/documentation/faq.html#case-sensitive - if(!tableExists(connection, flyway.getTable(), true)) + if (!tableExists(connection, flyway.getTable(), true)) { System.out.println("\nNOTE: This database is NOT yet initialized for auto-migrations (via Flyway)."); // Determine which version of DSpace this looks like @@ -157,7 +157,7 @@ public class DatabaseUtils boolean issueFound = printDBIssues(connection); // If issues found, exit with an error status - if(issueFound) + if (issueFound) System.exit(1); else System.exit(0); @@ -169,7 +169,7 @@ public class DatabaseUtils System.exit(1); } } - else if(argv[0].equalsIgnoreCase("migrate")) + else if (argv[0].equalsIgnoreCase("migrate")) { try (Connection connection = dataSource.getConnection()) { @@ -178,9 +178,9 @@ public class DatabaseUtils // "migrate" allows for an OPTIONAL second argument: // - "ignored" = Also run any previously "ignored" migrations during the migration // - [version] = ONLY run migrations up to a specific DSpace version (ONLY FOR TESTING) - if(argv.length==2) + if (argv.length==2) { - if(argv[1].equalsIgnoreCase("ignored")) + if (argv[1].equalsIgnoreCase("ignored")) { System.out.println("Migrating database to latest version AND running previously \"Ignored\" migrations... (Check logs for details)"); // Update the database to latest version, but set "outOfOrder=true" @@ -232,7 +232,7 @@ public class DatabaseUtils } } // "repair" = Run Flyway repair script - else if(argv[0].equalsIgnoreCase("repair")) + else if (argv[0].equalsIgnoreCase("repair")) { try (Connection connection = dataSource.getConnection();) { @@ -250,7 +250,7 @@ public class DatabaseUtils } } // "validate" = Run Flyway validation to check for database errors/issues - else if(argv[0].equalsIgnoreCase("validate")) + else if (argv[0].equalsIgnoreCase("validate")) { try (Connection connection = dataSource.getConnection();) { @@ -268,10 +268,10 @@ public class DatabaseUtils } } // "clean" = Run Flyway clean script - else if(argv[0].equalsIgnoreCase("clean")) + else if (argv[0].equalsIgnoreCase("clean")) { // If clean is disabled, return immediately - if(flyway.isCleanDisabled()) + if (flyway.isCleanDisabled()) { System.out.println("\nWARNING: 'clean' command is currently disabled, as it is dangerous to run in Production scenarios!"); System.out.println("\nIn order to run a 'clean' you first must enable it in your DSpace config by specifying 'db.cleanDisabled=false'.\n"); @@ -284,10 +284,10 @@ public class DatabaseUtils // Not all Postgres user accounts will be able to run a 'clean', // as only 'superuser' accounts can remove the 'pgcrypto' extension. - if(dbType.equals(DBMS_POSTGRES)) + if (dbType.equals(DBMS_POSTGRES)) { // Check if database user has permissions suitable to run a clean - if(!PostgresUtils.checkCleanPermissions(connection)) + if (!PostgresUtils.checkCleanPermissions(connection)) { String username = connection.getMetaData().getUserName(); // Exit immediately, providing a descriptive error message @@ -304,11 +304,11 @@ public class DatabaseUtils System.out.println("\nDatabase URL: " + connection.getMetaData().getURL()); System.out.println("\nWARNING: ALL DATA AND TABLES IN YOUR DATABASE WILL BE PERMANENTLY DELETED.\n"); System.out.println("There is NO turning back from this action. Backup your DB before continuing."); - if(dbType.equals(DBMS_ORACLE)) + if (dbType.equals(DBMS_ORACLE)) { System.out.println("\nORACLE WARNING: your RECYCLEBIN will also be PURGED.\n"); } - else if(dbType.equals(DBMS_POSTGRES)) + else if (dbType.equals(DBMS_POSTGRES)) { System.out.println("\nPOSTGRES WARNING: the '" + PostgresUtils.PGCRYPTO + "' extension will be dropped if it is in the same schema as the DSpace database.\n"); } @@ -378,7 +378,7 @@ public class DatabaseUtils // For Postgres, report whether pgcrypto is installed // (If it isn't, we'll also write out warnings...see below) - if(dbType.equals(DBMS_POSTGRES)) + if (dbType.equals(DBMS_POSTGRES)) { boolean pgcryptoUpToDate = PostgresUtils.isPgcryptoUpToDate(); Double pgcryptoVersion = PostgresUtils.getPgcryptoInstalledVersion(connection); @@ -402,7 +402,7 @@ public class DatabaseUtils // For PostgreSQL databases, we need to check for the 'pgcrypto' extension. // If it is NOT properly installed, we'll need to warn the user, as DSpace will be unable to proceed. - if(dbType.equals(DBMS_POSTGRES)) + if (dbType.equals(DBMS_POSTGRES)) { // Get version of pgcrypto available in this postgres instance Double pgcryptoAvailable = PostgresUtils.getPgcryptoAvailableVersion(connection); @@ -411,13 +411,13 @@ public class DatabaseUtils String requirementsMsg = "\n** DSpace REQUIRES PostgreSQL >= " + PostgresUtils.POSTGRES_VERSION + " AND " + PostgresUtils.PGCRYPTO + " extension >= " + PostgresUtils.PGCRYPTO_VERSION + " **\n"; // Check if installed in PostgreSQL & a supported version - if(pgcryptoAvailable!=null && pgcryptoAvailable.compareTo(PostgresUtils.PGCRYPTO_VERSION)>=0) + if (pgcryptoAvailable!=null && pgcryptoAvailable.compareTo(PostgresUtils.PGCRYPTO_VERSION)>=0) { // We now know it's available in this Postgres. Let's see if it is installed in this database. Double pgcryptoInstalled = PostgresUtils.getPgcryptoInstalledVersion(connection); // Check if installed in database, but outdated version - if(pgcryptoInstalled!=null && pgcryptoInstalled.compareTo(PostgresUtils.PGCRYPTO_VERSION)<0) + if (pgcryptoInstalled!=null && pgcryptoInstalled.compareTo(PostgresUtils.PGCRYPTO_VERSION)<0) { System.out.println("\nWARNING: Required PostgreSQL '" + PostgresUtils.PGCRYPTO + "' extension is OUTDATED (installed version=" + pgcryptoInstalled + ", available version = " + pgcryptoAvailable + ")."); System.out.println(requirementsMsg); @@ -425,7 +425,7 @@ public class DatabaseUtils System.out.println("\n ALTER EXTENSION " + PostgresUtils.PGCRYPTO + " UPDATE TO '" + pgcryptoAvailable + "';\n"); issueFound = true; } - else if(pgcryptoInstalled==null) // If it's not installed in database + else if (pgcryptoInstalled==null) // If it's not installed in database { System.out.println("\nWARNING: Required PostgreSQL '" + PostgresUtils.PGCRYPTO + "' extension is NOT INSTALLED on this database."); System.out.println(requirementsMsg); @@ -435,7 +435,7 @@ public class DatabaseUtils } } // Check if installed in Postgres, but an unsupported version - else if(pgcryptoAvailable!=null && pgcryptoAvailable.compareTo(PostgresUtils.PGCRYPTO_VERSION)<0) + else if (pgcryptoAvailable!=null && pgcryptoAvailable.compareTo(PostgresUtils.PGCRYPTO_VERSION)<0) { System.out.println("\nWARNING: UNSUPPORTED version of PostgreSQL '" + PostgresUtils.PGCRYPTO + "' extension found (version=" + pgcryptoAvailable + ")."); System.out.println(requirementsMsg); @@ -443,7 +443,7 @@ public class DatabaseUtils System.out.println("The '" + PostgresUtils.PGCRYPTO + "' extension is often provided in the 'postgresql-contrib' package for your operating system."); issueFound = true; } - else if(pgcryptoAvailable==null) // If it's not installed in Postgres + else if (pgcryptoAvailable==null) // If it's not installed in Postgres { System.out.println("\nWARNING: PostgreSQL '" + PostgresUtils.PGCRYPTO + "' extension is NOT AVAILABLE. Please install it into this PostgreSQL instance."); System.out.println(requirementsMsg); @@ -490,7 +490,7 @@ public class DatabaseUtils // First, add location for custom SQL migrations, if any (based on DB Type) // e.g. [dspace.dir]/etc/[dbtype]/ // (We skip this for H2 as it's only used for unit testing) - if(!dbType.equals(DBMS_H2)) + if (!dbType.equals(DBMS_H2)) { scriptLocations.add("filesystem:" + config.getProperty("dspace.dir") + "/etc/" + dbType); @@ -610,7 +610,7 @@ public class DatabaseUtils // If a target version was specified, tell Flyway to ONLY migrate to that version // (i.e. all later migrations are left as "pending"). By default we always migrate to latest version. - if(!StringUtils.isBlank(targetVersion)) + if (!StringUtils.isBlank(targetVersion)) { flyway.setTargetAsString(targetVersion); } @@ -619,7 +619,7 @@ public class DatabaseUtils // If not, then this is the first time Flyway has run, and we need to initialize // NOTE: search is case sensitive, as flyway table name is ALWAYS lowercase, // See: http://flywaydb.org/documentation/faq.html#case-sensitive - if(!tableExists(connection, flyway.getTable(), true)) + if (!tableExists(connection, flyway.getTable(), true)) { // Try to determine our DSpace database version, so we know what to tell Flyway to do String dbVersion = determineDBVersion(connection); @@ -696,7 +696,7 @@ public class DatabaseUtils // If this is Oracle, the only way to entirely clean the database // is to also purge the "Recyclebin". See: // http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_9018.htm - if(dbType.equals(DBMS_ORACLE)) + if (dbType.equals(DBMS_ORACLE)) { PreparedStatement statement = null; try @@ -706,7 +706,7 @@ public class DatabaseUtils } finally { - if(statement!=null && !statement.isClosed()) + if (statement!=null && !statement.isClosed()) statement.close(); } } @@ -737,7 +737,7 @@ public class DatabaseUtils throws SQLException { // First, is this a "fresh_install"? Check for an "item" table. - if(!tableExists(connection, "Item")) + if (!tableExists(connection, "Item")) { // Item table doesn't exist. This database must be a fresh install return null; @@ -747,74 +747,74 @@ public class DatabaseUtils // for specific tables or columns that were newly created in each version. // Is this pre-DSpace 5.0 (with Metadata 4 All changes)? Look for the "resource_id" column in the "metadatavalue" table - if(tableColumnExists(connection, "metadatavalue", "resource_id")) + if (tableColumnExists(connection, "metadatavalue", "resource_id")) { return "5.0.2014.09.26"; // This version matches the version in the SQL migration for this feature } // Is this pre-DSpace 5.0 (with Helpdesk plugin)? Look for the "request_message" column in the "requestitem" table - if(tableColumnExists(connection, "requestitem", "request_message")) + if (tableColumnExists(connection, "requestitem", "request_message")) { return "5.0.2014.08.08"; // This version matches the version in the SQL migration for this feature } // Is this DSpace 4.x? Look for the "Webapp" table created in that version. - if(tableExists(connection, "Webapp")) + if (tableExists(connection, "Webapp")) { return "4.0"; } // Is this DSpace 3.x? Look for the "versionitem" table created in that version. - if(tableExists(connection, "versionitem")) + if (tableExists(connection, "versionitem")) { return "3.0"; } // Is this DSpace 1.8.x? Look for the "bitstream_order" column in the "bundle2bitstream" table - if(tableColumnExists(connection, "bundle2bitstream", "bitstream_order")) + if (tableColumnExists(connection, "bundle2bitstream", "bitstream_order")) { return "1.8"; } // Is this DSpace 1.7.x? Look for the "dctyperegistry_seq" to NOT exist (it was deleted in 1.7) // NOTE: DSPACE 1.7.x only differs from 1.6 in a deleted sequence. - if(!sequenceExists(connection, "dctyperegistry_seq")) + if (!sequenceExists(connection, "dctyperegistry_seq")) { return "1.7"; } // Is this DSpace 1.6.x? Look for the "harvested_collection" table created in that version. - if(tableExists(connection, "harvested_collection")) + if (tableExists(connection, "harvested_collection")) { return "1.6"; } // Is this DSpace 1.5.x? Look for the "collection_item_count" table created in that version. - if(tableExists(connection, "collection_item_count")) + if (tableExists(connection, "collection_item_count")) { return "1.5"; } // Is this DSpace 1.4.x? Look for the "Group2Group" table created in that version. - if(tableExists(connection, "Group2Group")) + if (tableExists(connection, "Group2Group")) { return "1.4"; } // Is this DSpace 1.3.x? Look for the "epersongroup2workspaceitem" table created in that version. - if(tableExists(connection, "epersongroup2workspaceitem")) + if (tableExists(connection, "epersongroup2workspaceitem")) { return "1.3"; } // Is this DSpace 1.2.x? Look for the "Community2Community" table created in that version. - if(tableExists(connection, "Community2Community")) + if (tableExists(connection, "Community2Community")) { return "1.2"; } // Is this DSpace 1.1.x? Look for the "Community" table created in that version. - if(tableExists(connection, "Community")) + if (tableExists(connection, "Community")) { return "1.1"; } @@ -865,7 +865,7 @@ public class DatabaseUtils DatabaseMetaData meta = connection.getMetaData(); // If this is not a case sensitive search - if(!caseSensitive) + if (!caseSensitive) { // Canonicalize everything to the proper case based on DB type schema = canonicalize(connection, schema); @@ -888,7 +888,7 @@ public class DatabaseUtils try { // ensure the ResultSet gets closed - if(results!=null && !results.isClosed()) + if (results!=null && !results.isClosed()) results.close(); } catch(SQLException e) @@ -946,7 +946,7 @@ public class DatabaseUtils try { // ensure the ResultSet gets closed - if(results!=null && !results.isClosed()) + if (results!=null && !results.isClosed()) results.close(); } catch(SQLException e) @@ -992,7 +992,7 @@ public class DatabaseUtils { case DBMS_POSTGRES: // Default schema in PostgreSQL is "public" - if(schema == null) + if (schema == null) { schema = "public"; } @@ -1027,14 +1027,14 @@ public class DatabaseUtils // Run the query, passing it our parameters statement = connection.prepareStatement(sequenceSQL); statement.setString(1, sequenceName); - if(schemaFilter) + if (schemaFilter) { statement.setString(2, schema); } results = statement.executeQuery(); // If results are non-zero, then this sequence exists! - if(results!=null && results.next() && results.getInt(1)>0) + if (results!=null && results.next() && results.getInt(1)>0) { exists = true; } @@ -1049,10 +1049,10 @@ public class DatabaseUtils try { // Ensure statement gets closed - if(statement!=null && !statement.isClosed()) + if (statement!=null && !statement.isClosed()) statement.close(); // Ensure ResultSet gets closed - if(results!=null && !results.isClosed()) + if (results!=null && !results.isClosed()) results.close(); } catch(SQLException e) @@ -1100,8 +1100,10 @@ public class DatabaseUtils * be used to limit queries in other methods (e.g. tableExists()). * * @param connection - * Current Database Connection + * Current Database Connection * @return Schema name as a string, or "null" if cannot be determined or unspecified + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static String getSchemaName(Connection connection) throws SQLException @@ -1120,17 +1122,17 @@ public class DatabaseUtils } // If we don't know our schema, let's try the schema in the DSpace configuration - if(StringUtils.isBlank(schema)) + if (StringUtils.isBlank(schema)) { schema = canonicalize(connection, DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("db.schema")); } // Still blank? Ok, we'll find a "sane" default based on the DB type - if(StringUtils.isBlank(schema)) + if (StringUtils.isBlank(schema)) { String dbType = getDbType(connection); - if(dbType.equals(DBMS_POSTGRES)) + if (dbType.equals(DBMS_POSTGRES)) { // For PostgreSQL, the default schema is named "public" // See: http://www.postgresql.org/docs/9.0/static/ddl-schemas.html @@ -1155,28 +1157,30 @@ public class DatabaseUtils * database defaults to storing identifiers in uppercase or lowercase. * * @param connection - * Current Database Connection + * Current Database Connection * @param dbIdentifier - * Identifier to canonicalize (may be a table name, column name, etc) + * Identifier to canonicalize (may be a table name, column name, etc) * @return The canonical name of the identifier. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static String canonicalize(Connection connection, String dbIdentifier) throws SQLException { // Avoid any null pointers - if(dbIdentifier==null) + if (dbIdentifier==null) return null; DatabaseMetaData meta = connection.getMetaData(); // Check how this database stores its identifiers, etc. // i.e. lowercase vs uppercase (by default we assume mixed case) - if(meta.storesLowerCaseIdentifiers()) + if (meta.storesLowerCaseIdentifiers()) { return StringUtils.lowerCase(dbIdentifier); } - else if(meta.storesUpperCaseIdentifiers()) + else if (meta.storesUpperCaseIdentifiers()) { return StringUtils.upperCase(dbIdentifier); } @@ -1204,12 +1208,12 @@ public class DatabaseUtils File reindexFlag = new File(reindexDiscoveryFilePath); // If we need to flag Discovery to reindex, we'll create a temporary file to do so. - if(reindex) + if (reindex) { try { //If our flag file doesn't exist, create it as writeable to all - if(!reindexFlag.exists()) + if (!reindexFlag.exists()) { reindexFlag.createNewFile(); reindexFlag.setWritable(true, false); @@ -1223,10 +1227,10 @@ public class DatabaseUtils else // Otherwise, Discovery doesn't need to reindex. Delete the temporary file if it exists { //If our flag file exists, delete it - if(reindexFlag.exists()) + if (reindexFlag.exists()) { boolean deleted = reindexFlag.delete(); - if(!deleted) + if (!deleted) log.error("Unable to delete Discovery reindex flag file " + reindexFlag.getAbsolutePath() + ". You may need to delete it manually."); } } @@ -1261,7 +1265,7 @@ public class DatabaseUtils public static synchronized void checkReindexDiscovery(IndexingService indexer) { // We only do something if the reindexDiscovery flag has been triggered - if(getReindexDiscovery()) + if (getReindexDiscovery()) { // Kick off a custom thread to perform the reindexing in Discovery // (See ReindexerThread nested class below) @@ -1298,7 +1302,7 @@ public class DatabaseUtils { // Make sure reindexDiscovery flag is still true // If multiple threads get here we only want to reindex ONCE - if(DatabaseUtils.getReindexDiscovery()) + if (DatabaseUtils.getReindexDiscovery()) { Context context = null; try @@ -1332,7 +1336,7 @@ public class DatabaseUtils DatabaseUtils.setReindexDiscovery(false); // Clean up our context, if it still exists - if(context!=null && context.isValid()) + if (context!=null && context.isValid()) context.abort(); } } @@ -1419,7 +1423,7 @@ public class DatabaseUtils { String flywayState = getCurrentFlywayState(connection); Matcher matcher = Pattern.compile("^([0-9]*\\.[0-9]*)(\\.)?.*").matcher(flywayState); - if(matcher.matches()) + if (matcher.matches()) { return Double.parseDouble(matcher.group(1)); } diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/PostgresUtils.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/PostgresUtils.java index 82f4141f17..f53f6f0795 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/PostgresUtils.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/PostgresUtils.java @@ -104,7 +104,7 @@ public class PostgresUtils *

* This requirement is only needed for PostgreSQL databases. * It doesn't matter what schema pgcrypto is installed in, as long as it exists. - * @return true if everything is installed & up-to-date. False otherwise. + * @return true if everything is installed and up-to-date. False otherwise. */ public static boolean isPgcryptoUpToDate() { diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/hibernate/postgres/DSpacePostgreSQL82Dialect.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/hibernate/postgres/DSpacePostgreSQL82Dialect.java index dfacf980c2..bf13f72779 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/hibernate/postgres/DSpacePostgreSQL82Dialect.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/hibernate/postgres/DSpacePostgreSQL82Dialect.java @@ -18,7 +18,7 @@ import java.sql.Types; /** * UUID's are not supported by default in hibernate due to differences in the database in order to fix this a custom sql dialect is needed. - * Source: https://forum.hibernate.org/viewtopic.php?f=1&t=1014157 + * Source: https://forum.hibernate.org/viewtopic.php?f=1&t=1014157 * * @author kevinvandevelde at atmire.com */ @@ -44,7 +44,8 @@ public class DSpacePostgreSQL82Dialect extends PostgreSQL82Dialect } /** - * Override is needed to properly support the CLOB on metadatavalue in postgres & oracle. + * Override is needed to properly support the CLOB on metadatavalue in Postgres and Oracle. + * * @param sqlCode {@linkplain java.sql.Types JDBC type-code} for the column mapped by this type. * @return Descriptor for the SQL/JDBC side of a value mapping. */ diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_3_9__Drop_constraint_for_DSpace_1_4_schema.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_3_9__Drop_constraint_for_DSpace_1_4_schema.java index 40c2aaf4fe..cba74cb9cf 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_3_9__Drop_constraint_for_DSpace_1_4_schema.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_3_9__Drop_constraint_for_DSpace_1_4_schema.java @@ -16,7 +16,7 @@ import org.flywaydb.core.api.migration.jdbc.JdbcMigration; /** * This class is in support of the "V1.4__Upgrade_to_DSpace_1.4_schema.sql" * It simply drops the database constraint associated with the "name" column - * of the "community" table. This is necessary for the upgrade from 1.3 -> 1.4 + * of the "community" table. This is necessary for the upgrade from 1.3 to 1.4 *

* This class was created because the names of database constraints differs based * on the type of database (Postgres vs. Oracle vs. H2). As such, it becomes difficult @@ -45,6 +45,11 @@ public class V1_3_9__Drop_constraint_for_DSpace_1_4_schema /** * Actually migrate the existing database * @param connection + * SQL Connection object + * @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. */ @Override public void migrate(Connection connection) diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_5_9__Drop_constraint_for_DSpace_1_6_schema.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_5_9__Drop_constraint_for_DSpace_1_6_schema.java index a3b03e550d..13ab900600 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_5_9__Drop_constraint_for_DSpace_1_6_schema.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V1_5_9__Drop_constraint_for_DSpace_1_6_schema.java @@ -16,7 +16,7 @@ import org.flywaydb.core.api.migration.jdbc.JdbcMigration; /** * This class is in support of the "V1.6__Upgrade_to_DSpace_1.6_schema.sql" * It simply drops a few database constraints. This is necessary for the upgrade - * from 1.5 -> 1.6 + * from 1.5 to 1.6 *

* This class was created because the names of database constraints differs based * on the type of database (Postgres vs. Oracle vs. H2). As such, it becomes difficult @@ -45,6 +45,11 @@ public class V1_5_9__Drop_constraint_for_DSpace_1_6_schema /** * Actually migrate the existing database * @param connection + * SQL Connection object + * @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. */ @Override public void migrate(Connection connection) diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V5_0_2014_09_25__DS_1582_Metadata_For_All_Objects_drop_constraint.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V5_0_2014_09_25__DS_1582_Metadata_For_All_Objects_drop_constraint.java index 447bc8e2c8..8d524b416f 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V5_0_2014_09_25__DS_1582_Metadata_For_All_Objects_drop_constraint.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/migration/V5_0_2014_09_25__DS_1582_Metadata_For_All_Objects_drop_constraint.java @@ -46,6 +46,11 @@ public class V5_0_2014_09_25__DS_1582_Metadata_For_All_Objects_drop_constraint /** * Actually migrate the existing database * @param connection + * SQL Connection object + * @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. */ @Override public void migrate(Connection connection) diff --git a/dspace-api/src/main/java/org/dspace/storage/rdbms/xmlworkflow/V5_0_2014_11_04__Enable_XMLWorkflow_Migration.java b/dspace-api/src/main/java/org/dspace/storage/rdbms/xmlworkflow/V5_0_2014_11_04__Enable_XMLWorkflow_Migration.java index 0022519e91..74da8f34c6 100644 --- a/dspace-api/src/main/java/org/dspace/storage/rdbms/xmlworkflow/V5_0_2014_11_04__Enable_XMLWorkflow_Migration.java +++ b/dspace-api/src/main/java/org/dspace/storage/rdbms/xmlworkflow/V5_0_2014_11_04__Enable_XMLWorkflow_Migration.java @@ -48,6 +48,11 @@ public class V5_0_2014_11_04__Enable_XMLWorkflow_Migration /** * Actually migrate the existing database * @param connection + * SQL Connection object + * @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. */ @Override public void migrate(Connection connection) diff --git a/dspace-api/src/main/java/org/dspace/submit/AbstractProcessingStep.java b/dspace-api/src/main/java/org/dspace/submit/AbstractProcessingStep.java index 2ac26474b5..e155768070 100644 --- a/dspace-api/src/main/java/org/dspace/submit/AbstractProcessingStep.java +++ b/dspace-api/src/main/java/org/dspace/submit/AbstractProcessingStep.java @@ -61,12 +61,12 @@ import org.dspace.services.factory.DSpaceServicesFactory; public abstract class AbstractProcessingStep { /*************************************************************************** - * Constant - Name of the "<-Previous" button + * Constant - Name of the "<-Previous" button **************************************************************************/ public static final String PREVIOUS_BUTTON = "submit_prev"; /*************************************************************************** - * Constant - Name of the "Next->" button + * Constant - Name of the "Next->" button **************************************************************************/ public static final String NEXT_BUTTON = "submit_next"; @@ -124,16 +124,25 @@ public abstract class AbstractProcessingStep * it should perform *all* of its processing in this method! * * @param context - * current DSpace context + * The relevant DSpace Context. * @param request - * current servlet request object + * Servlet's HTTP request object. * @param response - * current servlet response object + * Servlet's HTTP response object. * @param subInfo - * submission info object + * submission info object * @return Status or error flag which will be processed by - * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, - * no errors occurred!) + * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, + * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 abstract int doProcessing(Context context, HttpServletRequest request, HttpServletResponse response, @@ -192,8 +201,10 @@ public abstract class AbstractProcessingStep * doProcessing() method, so that it can be accessed later by whatever UI is * generated. * + * @param request + * Servlet's HTTP request object. * @param fieldName - * the name of the field which had an error + * the name of the field which had an error */ protected static final void addErrorField(HttpServletRequest request, String fieldName) { @@ -217,7 +228,7 @@ public abstract class AbstractProcessingStep * processing. * * @param request - * current servlet request object + * Servlet's HTTP request object. * */ protected static final void clearErrorFields(HttpServletRequest request) @@ -298,11 +309,13 @@ public abstract class AbstractProcessingStep * once! * * @param request - * The HTTP Request + * Servlet's HTTP request object. * @param subInfo - * The current submission information object + * The current submission information object * * @return the number of pages in this step + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ public abstract int getNumberOfPages(HttpServletRequest request, SubmissionInfo subInfo) throws ServletException; @@ -311,7 +324,7 @@ public abstract class AbstractProcessingStep * Find out which page a user is currently viewing * * @param request - * HTTP request + * Servlet's HTTP request object. * * @return current page */ @@ -363,9 +376,9 @@ public abstract class AbstractProcessingStep * Set which page a user is currently viewing * * @param request - * HTTP request + * Servlet's HTTP request object. * @param pageNumber - * new current page + * new current page */ public static final void setCurrentPage(HttpServletRequest request, int pageNumber) diff --git a/dspace-api/src/main/java/org/dspace/submit/lookup/ArXivFileDataLoader.java b/dspace-api/src/main/java/org/dspace/submit/lookup/ArXivFileDataLoader.java index 04949439f9..2a08ace18b 100644 --- a/dspace-api/src/main/java/org/dspace/submit/lookup/ArXivFileDataLoader.java +++ b/dspace-api/src/main/java/org/dspace/submit/lookup/ArXivFileDataLoader.java @@ -58,6 +58,7 @@ public class ArXivFileDataLoader extends FileDataLoader /** * @param filename + * Name of file to load ArXiv data from. */ public ArXivFileDataLoader(String filename) { @@ -65,9 +66,9 @@ public class ArXivFileDataLoader extends FileDataLoader } /* - * (non-Javadoc) - * - * @see gr.ekt.bte.core.DataLoader#getRecords() + * {@see gr.ekt.bte.core.DataLoader#getRecords()} + * + * @throws MalformedSourceException */ @Override public RecordSet getRecords() throws MalformedSourceException diff --git a/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiFileDataLoader.java b/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiFileDataLoader.java index 69fc9e9993..53f7a0c29d 100644 --- a/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiFileDataLoader.java +++ b/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiFileDataLoader.java @@ -56,6 +56,7 @@ public class CiNiiFileDataLoader extends FileDataLoader /** * @param filename + * Name of file to load CiNii data from. */ public CiNiiFileDataLoader(String filename) { @@ -63,9 +64,9 @@ public class CiNiiFileDataLoader extends FileDataLoader } /* - * (non-Javadoc) - * - * @see gr.ekt.bte.core.DataLoader#getRecords() + * {@see gr.ekt.bte.core.DataLoader#getRecords()} + * + * @throws MalformedSourceException */ @Override public RecordSet getRecords() throws MalformedSourceException diff --git a/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiService.java b/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiService.java index 7891667bc7..dec88fc01c 100644 --- a/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiService.java +++ b/dspace-api/src/main/java/org/dspace/submit/lookup/CiNiiService.java @@ -76,6 +76,15 @@ public class CiNiiService /** * Get metadata by searching CiNii RDF API with CiNii NAID * + * @param id + * CiNii NAID to search by + * @param appId + * registered application identifier for the API + * @return record metadata + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws HttpException + * Represents a XML/HTTP fault and provides access to the HTTP status code. */ protected Record search(String id, String appId) throws IOException, HttpException @@ -133,8 +142,23 @@ public class CiNiiService /** * Get CiNii NAIDs by searching CiNii OpenURL API with title, author and year * + * @param title + * record title + * @param author + * record author + * @param year + * record year + * @param maxResults + * maximun number of results returned + * @param appId + * registered application identifier for the API + * @return matching NAIDs + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws HttpException + * Represents a XML/HTTP fault and provides access to the HTTP status code. */ - protected List getCiNiiIDs(String title, String author, int year, + protected List getCiNiiIDs(String title, String author, int year, int maxResults, String appId) throws IOException, HttpException { diff --git a/dspace-api/src/main/java/org/dspace/submit/lookup/CrossRefFileDataLoader.java b/dspace-api/src/main/java/org/dspace/submit/lookup/CrossRefFileDataLoader.java index e561777117..2f176c04ab 100644 --- a/dspace-api/src/main/java/org/dspace/submit/lookup/CrossRefFileDataLoader.java +++ b/dspace-api/src/main/java/org/dspace/submit/lookup/CrossRefFileDataLoader.java @@ -46,14 +46,15 @@ public class CrossRefFileDataLoader extends FileDataLoader // intermediate fields /** - * - */ + * + */ public CrossRefFileDataLoader() { } /** * @param filename + * Name of file to load ArXiv data from. */ public CrossRefFileDataLoader(String filename) { diff --git a/dspace-api/src/main/java/org/dspace/submit/lookup/MapConverterModifier.java b/dspace-api/src/main/java/org/dspace/submit/lookup/MapConverterModifier.java index 55577f84cb..07e22e0c21 100644 --- a/dspace-api/src/main/java/org/dspace/submit/lookup/MapConverterModifier.java +++ b/dspace-api/src/main/java/org/dspace/submit/lookup/MapConverterModifier.java @@ -34,12 +34,12 @@ import gr.ekt.bte.core.Value; public class MapConverterModifier extends AbstractModifier { - protected String mappingFile; //The properties absolute filename - + protected String mappingFile; //The properties absolute filename + protected String converterNameFile; //The properties filename protected ConfigurationService configurationService; - + protected Map mapping; protected String defaultValue = ""; @@ -123,6 +123,7 @@ public class MapConverterModifier extends AbstractModifier } /** * @param name + * Name of file to load ArXiv data from. */ public MapConverterModifier(String name) { diff --git a/dspace-api/src/main/java/org/dspace/submit/lookup/PubmedFileDataLoader.java b/dspace-api/src/main/java/org/dspace/submit/lookup/PubmedFileDataLoader.java index d8a99fad38..fd617209c2 100644 --- a/dspace-api/src/main/java/org/dspace/submit/lookup/PubmedFileDataLoader.java +++ b/dspace-api/src/main/java/org/dspace/submit/lookup/PubmedFileDataLoader.java @@ -46,14 +46,15 @@ public class PubmedFileDataLoader extends FileDataLoader // intermediate fields /** - * - */ + * + */ public PubmedFileDataLoader() { } /** * @param filename + * Name of file to load CiNii data from. */ public PubmedFileDataLoader(String filename) { @@ -61,9 +62,9 @@ public class PubmedFileDataLoader extends FileDataLoader } /* - * (non-Javadoc) - * - * @see gr.ekt.bte.core.DataLoader#getRecords() + * {@see gr.ekt.bte.core.DataLoader#getRecords()} + * + * @throws MalformedSourceException */ @Override public RecordSet getRecords() throws MalformedSourceException diff --git a/dspace-api/src/main/java/org/dspace/submit/lookup/RemoveLastDotModifier.java b/dspace-api/src/main/java/org/dspace/submit/lookup/RemoveLastDotModifier.java index f29ca13754..7af9e9d115 100644 --- a/dspace-api/src/main/java/org/dspace/submit/lookup/RemoveLastDotModifier.java +++ b/dspace-api/src/main/java/org/dspace/submit/lookup/RemoveLastDotModifier.java @@ -32,6 +32,7 @@ public class RemoveLastDotModifier extends AbstractModifier /** * @param name + * modifier name */ public RemoveLastDotModifier(String name) { diff --git a/dspace-api/src/main/java/org/dspace/submit/step/CCLicenseStep.java b/dspace-api/src/main/java/org/dspace/submit/step/CCLicenseStep.java index ac2d05ced4..75f1237120 100644 --- a/dspace-api/src/main/java/org/dspace/submit/step/CCLicenseStep.java +++ b/dspace-api/src/main/java/org/dspace/submit/step/CCLicenseStep.java @@ -97,11 +97,11 @@ public class CCLicenseStep extends AbstractProcessingStep throws ServletException, IOException, SQLException, AuthorizeException,java.io.IOException { - HttpSession session = request.getSession(); + HttpSession session = request.getSession(); session.setAttribute("inProgress", "TRUE"); // check what submit button was pressed in User Interface String buttonPressed = Util.getSubmitButton(request, NEXT_BUTTON); - String choiceButton = Util.getSubmitButton(request, SELECT_CHANGE); + String choiceButton = Util.getSubmitButton(request, SELECT_CHANGE); Enumeration e = request.getParameterNames(); String isFieldRequired = "FALSE"; while (e.hasMoreElements()) @@ -109,21 +109,21 @@ public class CCLicenseStep extends AbstractProcessingStep String parameterName = (String) e.nextElement(); if (parameterName.equals("button_required")) { - isFieldRequired = "TRUE"; + isFieldRequired = "TRUE"; break; } } session.setAttribute("isFieldRequired", isFieldRequired); if (choiceButton.equals(SELECT_CHANGE)) { - Item item = subInfo.getSubmissionItem().getItem(); - LicenseMetadataValue uriField = creativeCommonsService.getCCField("uri"); - String licenseUri = uriField.ccItemValue(item); - if (licenseUri != null) - { + Item item = subInfo.getSubmissionItem().getItem(); + LicenseMetadataValue uriField = creativeCommonsService.getCCField("uri"); + String licenseUri = uriField.ccItemValue(item); + if (licenseUri != null) + { removeRequiredAttributes(session); } - return STATUS_COMPLETE; + return STATUS_COMPLETE; } else if (buttonPressed.startsWith(PROGRESS_BAR_PREFIX) || buttonPressed.equals(PREVIOUS_BUTTON)) { @@ -146,18 +146,26 @@ public class CCLicenseStep extends AbstractProcessingStep * Process the input from the CC license page using CC Web service * * @param context - * current DSpace context + * The relevant DSpace Context. * @param request - * current servlet request object + * Servlet's HTTP request object. * @param response - * current servlet response object + * Servlet's HTTP response object. * @param subInfo - * submission info object - * + * submission info object * * @return Status or error flag which will be processed by - * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, - * no errors occurred!) + * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, + * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ protected int processCC(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -165,74 +173,74 @@ public class CCLicenseStep extends AbstractProcessingStep AuthorizeException { HttpSession session = request.getSession(); - Map map = new HashMap(); - String licenseclass = (request.getParameter("licenseclass_chooser") != null) ? request.getParameter("licenseclass_chooser") : ""; - String jurisdiction = (configurationService.getProperty("cc.license.jurisdiction") != null) ? configurationService.getProperty("cc.license.jurisdiction") : ""; - if (licenseclass.equals("standard")) { - map.put("commercial", request.getParameter("commercial_chooser")); - map.put("derivatives", request.getParameter("derivatives_chooser")); - } else if (licenseclass.equals("recombo")) { - map.put("sampling", request.getParameter("sampling_chooser")); - } - map.put("jurisdiction", jurisdiction); - - LicenseMetadataValue uriField = creativeCommonsService.getCCField("uri"); - LicenseMetadataValue nameField = creativeCommonsService.getCCField("name"); + Map map = new HashMap(); + String licenseclass = (request.getParameter("licenseclass_chooser") != null) ? request.getParameter("licenseclass_chooser") : ""; + String jurisdiction = (configurationService.getProperty("cc.license.jurisdiction") != null) ? configurationService.getProperty("cc.license.jurisdiction") : ""; + if (licenseclass.equals("standard")) { + map.put("commercial", request.getParameter("commercial_chooser")); + map.put("derivatives", request.getParameter("derivatives_chooser")); + } else if (licenseclass.equals("recombo")) { + map.put("sampling", request.getParameter("sampling_chooser")); + } + map.put("jurisdiction", jurisdiction); + + LicenseMetadataValue uriField = creativeCommonsService.getCCField("uri"); + LicenseMetadataValue nameField = creativeCommonsService.getCCField("name"); - Item item = subInfo.getSubmissionItem().getItem(); - if ("webui.Submission.submit.CCLicenseStep.no_license".equals(licenseclass) || "xmlui.Submission.submit.CCLicenseStep.no_license".equals(licenseclass)) - { - creativeCommonsService.removeLicense(context, uriField, nameField, item); - - itemService.update(context, item); - context.dispatchEvents(); - removeRequiredAttributes(session); - - return STATUS_COMPLETE; - } else if (StringUtils.isBlank(licenseclass) || "webui.Submission.submit.CCLicenseStep.select_change".equals(licenseclass) || "xmlui.Submission.submit.CCLicenseStep.select_change".equals(licenseclass)) - { - removeRequiredAttributes(session); - return STATUS_COMPLETE; - } - - CCLookup ccLookup = new CCLookup(); - ccLookup.issue(licenseclass, map, configurationService.getProperty("cc.license.locale")); - - if (ccLookup.isSuccess()) - { - creativeCommonsService.removeLicense(context, uriField, nameField, item); - - uriField.addItemValue(context, item, ccLookup.getLicenseUrl()); - if (configurationService.getBooleanProperty("cc.submit.addbitstream")) { - creativeCommonsService.setLicenseRDF(context, item, ccLookup.getRdf()); - } - if (configurationService.getBooleanProperty("cc.submit.setname")) { - nameField.addItemValue(context, item, ccLookup.getLicenseName()); - } + Item item = subInfo.getSubmissionItem().getItem(); + if ("webui.Submission.submit.CCLicenseStep.no_license".equals(licenseclass) || "xmlui.Submission.submit.CCLicenseStep.no_license".equals(licenseclass)) + { + creativeCommonsService.removeLicense(context, uriField, nameField, item); - itemService.update(context, item); + itemService.update(context, item); context.dispatchEvents(); - removeRequiredAttributes(session); - session.removeAttribute("inProgress"); - } - else - { - request.getSession().setAttribute("ccError", ccLookup.getErrorMessage()); - String licenseUri = uriField.ccItemValue(item); - if (licenseUri != null) - { - uriField.removeItemValue(context, item, licenseUri); - } - return STATUS_LICENSE_REJECTED; - } - return STATUS_COMPLETE; + removeRequiredAttributes(session); + + return STATUS_COMPLETE; + } else if (StringUtils.isBlank(licenseclass) || "webui.Submission.submit.CCLicenseStep.select_change".equals(licenseclass) || "xmlui.Submission.submit.CCLicenseStep.select_change".equals(licenseclass)) + { + removeRequiredAttributes(session); + return STATUS_COMPLETE; + } + + CCLookup ccLookup = new CCLookup(); + ccLookup.issue(licenseclass, map, configurationService.getProperty("cc.license.locale")); + + if (ccLookup.isSuccess()) + { + creativeCommonsService.removeLicense(context, uriField, nameField, item); + + uriField.addItemValue(context, item, ccLookup.getLicenseUrl()); + if (configurationService.getBooleanProperty("cc.submit.addbitstream")) { + creativeCommonsService.setLicenseRDF(context, item, ccLookup.getRdf()); + } + if (configurationService.getBooleanProperty("cc.submit.setname")) { + nameField.addItemValue(context, item, ccLookup.getLicenseName()); + } + + itemService.update(context, item); + context.dispatchEvents(); + removeRequiredAttributes(session); + session.removeAttribute("inProgress"); + } + else + { + request.getSession().setAttribute("ccError", ccLookup.getErrorMessage()); + String licenseUri = uriField.ccItemValue(item); + if (licenseUri != null) + { + uriField.removeItemValue(context, item, licenseUri); + } + return STATUS_LICENSE_REJECTED; + } + return STATUS_COMPLETE; } - private void removeRequiredAttributes(HttpSession session) { - session.removeAttribute("ccError"); - session.removeAttribute("isFieldRequired"); - } + private void removeRequiredAttributes(HttpSession session) { + session.removeAttribute("ccError"); + session.removeAttribute("isFieldRequired"); + } /** @@ -261,7 +269,7 @@ public class CCLicenseStep extends AbstractProcessingStep public int getNumberOfPages(HttpServletRequest request, SubmissionInfo subInfo) throws ServletException { - return 1; + return 1; } } diff --git a/dspace-api/src/main/java/org/dspace/submit/step/DescribeStep.java b/dspace-api/src/main/java/org/dspace/submit/step/DescribeStep.java index 348acbd94a..a6b450b369 100644 --- a/dspace-api/src/main/java/org/dspace/submit/step/DescribeStep.java +++ b/dspace-api/src/main/java/org/dspace/submit/step/DescribeStep.java @@ -83,7 +83,12 @@ public class DescribeStep extends AbstractProcessingStep protected final MetadataAuthorityService metadataAuthorityService; - /** Constructor */ + /** + * Constructor + * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + */ public DescribeStep() throws ServletException { //load the DCInputsReader @@ -93,7 +98,6 @@ public class DescribeStep extends AbstractProcessingStep } - /** * Do any processing of the information input by the user, and/or perform * step processing (if no user interaction required) @@ -106,16 +110,25 @@ public class DescribeStep extends AbstractProcessingStep * it should perform *all* of its processing in this method! * * @param context - * current DSpace context + * The relevant DSpace Context. * @param request - * current servlet request object + * Servlet's HTTP request object. * @param response - * current servlet response object + * Servlet's HTTP response object. * @param subInfo - * submission info object + * submission info object * @return Status or error flag which will be processed by - * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, - * no errors occurred!) + * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, + * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 int doProcessing(Context context, HttpServletRequest request, @@ -123,7 +136,7 @@ public class DescribeStep extends AbstractProcessingStep throws ServletException, IOException, SQLException, AuthorizeException { - if(!request.getParameterNames().hasMoreElements()){ + if (!request.getParameterNames().hasMoreElements()){ //In case of an empty request do NOT just remove all metadata, just return to the submission page return STATUS_MORE_INPUT_REQUESTED; } @@ -151,7 +164,7 @@ public class DescribeStep extends AbstractProcessingStep // Fetch the document type (dc.type) String documentType = ""; - if( (itemService.getMetadataByMetadataString(item, "dc.type") != null) && (itemService.getMetadataByMetadataString(item, "dc.type").size() >0) ) + if ( (itemService.getMetadataByMetadataString(item, "dc.type") != null) && (itemService.getMetadataByMetadataString(item, "dc.type").size() >0) ) { documentType = itemService.getMetadataByMetadataString(item, "dc.type").get(0).getValue(); } @@ -161,29 +174,29 @@ public class DescribeStep extends AbstractProcessingStep for (int i = 0; i < inputs.length; i++) { - // Allow the clearing out of the metadata defined for other document types, provided it can change anytime - + // Allow the clearing out of the metadata defined for other document types, provided it can change anytime + if (!inputs[i] .isVisible(subInfo.isInWorkflow() ? DCInput.WORKFLOW_SCOPE : DCInput.SUBMISSION_SCOPE)) { continue; } - if (inputs[i].getInputType().equals("qualdrop_value")) - { - @SuppressWarnings("unchecked") // This cast is correct - List pairs = inputs[i].getPairs(); - for (int j = 0; j < pairs.size(); j += 2) - { - String qualifier = pairs.get(j+1); + if (inputs[i].getInputType().equals("qualdrop_value")) + { + @SuppressWarnings("unchecked") // This cast is correct + List pairs = inputs[i].getPairs(); + for (int j = 0; j < pairs.size(); j += 2) + { + String qualifier = pairs.get(j+1); itemService.clearMetadata(context, item, inputs[i].getSchema(), inputs[i].getElement(), qualifier, Item.ANY); - } - } - else - { - String qualifier = inputs[i].getQualifier(); + } + } + else + { + String qualifier = inputs[i].getQualifier(); itemService.clearMetadata(context, item, inputs[i].getSchema(), inputs[i].getElement(), qualifier, Item.ANY); - } + } } // Clear required-field errors first since missing authority @@ -196,10 +209,10 @@ public class DescribeStep extends AbstractProcessingStep boolean moreInput = false; for (int j = 0; j < inputs.length; j++) { - // Omit fields not allowed for this document type + // Omit fields not allowed for this document type if(!inputs[j].isAllowedFor(documentType)) { - continue; + continue; } if (!inputs[j] @@ -316,11 +329,11 @@ public class DescribeStep extends AbstractProcessingStep { for (int i = 0; i < inputs.length; i++) { - // Do not check the required attribute if it is not visible or not allowed for the document type - String scope = subInfo.isInWorkflow() ? DCInput.WORKFLOW_SCOPE : DCInput.SUBMISSION_SCOPE; + // Do not check the required attribute if it is not visible or not allowed for the document type + String scope = subInfo.isInWorkflow() ? DCInput.WORKFLOW_SCOPE : DCInput.SUBMISSION_SCOPE; if ( !( inputs[i].isVisible(scope) && inputs[i].isAllowedFor(documentType) ) ) { - continue; + continue; } String qualifier = inputs[i].getQualifier(); @@ -381,11 +394,13 @@ public class DescribeStep extends AbstractProcessingStep * once! * * @param request - * The HTTP Request + * The HTTP Request * @param subInfo - * The current submission information object + * The current submission information object * * @return the number of pages in this step + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ @Override public int getNumberOfPages(HttpServletRequest request, @@ -414,6 +429,8 @@ public class DescribeStep extends AbstractProcessingStep /** * * @return the current DCInputsReader + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ public static DCInputsReader getInputsReader() throws ServletException { @@ -436,8 +453,10 @@ public class DescribeStep extends AbstractProcessingStep /** * @param filename - * file to get the input reader for + * file to get the input reader for * @return the current DCInputsReader + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ public static DCInputsReader getInputsReader(String filename) throws ServletException { @@ -479,15 +498,15 @@ public class DescribeStep extends AbstractProcessingStep * field is "dc.contributor.author", the names in the request will be from * the fields as follows: * - * dc_contributor_author_last -> last name of first author - * dc_contributor_author_first -> first name(s) of first author - * dc_contributor_author_last_1 -> last name of second author - * dc_contributor_author_first_1 -> first name(s) of second author + * dc_contributor_author_last: last name of first author + * dc_contributor_author_first: first name(s) of first author + * dc_contributor_author_last_1: last name of second author + * dc_contributor_author_first_1: first name(s) of second author * * and so on. If the field is unqualified: * - * dc_contributor_last -> last name of first contributor - * dc_contributor_first -> first name(s) of first contributor + * dc_contributor_last: last name of first contributor + * dc_contributor_first: first name(s) of first contributor * * If the parameter "submit_dc_contributor_author_remove_n" is set, that * value is removed. @@ -500,18 +519,22 @@ public class DescribeStep extends AbstractProcessingStep * first name(s)", ordered as they appear in the list. These will replace * any existing values. * + * @param context + * The relevant DSpace Context. * @param request - * the request object + * the request object * @param item - * the item to update + * the item to update * @param schema - * the metadata schema + * the metadata schema * @param element - * the metadata element + * the metadata element * @param qualifier - * the metadata qualifier, or null if unqualified + * the metadata qualifier, or null if unqualified * @param repeated - * set to true if the field is repeatable on the form + * set to true if the field is repeatable on the form + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ protected void readNames(Context context, HttpServletRequest request, Item item, String schema, String element, String qualifier, boolean repeated) throws SQLException { @@ -665,22 +688,26 @@ public class DescribeStep extends AbstractProcessingStep * The values will be put in separate DCValues, ordered as they appear in * the list. These will replace any existing values. * + * @param context + * The relevant DSpace Context. * @param request - * the request object + * Servlet's HTTP request object. * @param item - * the item to update + * the item to update * @param schema - * the short schema name + * the short schema name * @param element - * the metadata element + * the metadata element * @param qualifier - * the metadata qualifier, or null if unqualified + * the metadata qualifier, or null if unqualified * @param repeated - * set to true if the field is repeatable on the form + * set to true if the field is repeatable on the form * @param lang - * language to set (ISO code) + * language to set (ISO code) * @param hasLanguageTag - * to check if the field has a language tag + * to check if the field has a language tag + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ protected void readText(Context context, HttpServletRequest request, Item item, String schema, String element, String qualifier, boolean repeated, String lang, boolean hasLanguageTag) @@ -811,16 +838,18 @@ public class DescribeStep extends AbstractProcessingStep * The granularity is determined by the values that are actually set. If the * year isn't set (or is invalid) * + * @param context + * The relevant DSpace Context. * @param request - * the request object + * the request object * @param item - * the item to update + * the item to update * @param schema - * the metadata schema + * the metadata schema * @param element - * the metadata element + * the metadata element * @param qualifier - * the metadata qualifier, or null if unqualified + * the metadata qualifier, or null if unqualified * @throws SQLException if database error */ protected void readDate(Context context, HttpServletRequest request, Item item, String schema, @@ -867,18 +896,22 @@ public class DescribeStep extends AbstractProcessingStep * first name(s)", ordered as they appear in the list. These will replace * any existing values. * + * @param context + * The relevant DSpace Context. * @param request - * the request object + * Servlet's HTTP request object. * @param item - * the item to update + * the item to update * @param schema - * the metadata schema + * the metadata schema * @param element - * the metadata element + * the metadata element * @param qualifier - * the metadata qualifier, or null if unqualified + * the metadata qualifier, or null if unqualified * @param repeated - * set to true if the field is repeatable on the form + * set to true if the field is repeatable on the form + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ protected void readSeriesNumbers(Context context, HttpServletRequest request, Item item, String schema, String element, String qualifier, boolean repeated) throws SQLException { @@ -955,12 +988,12 @@ public class DescribeStep extends AbstractProcessingStep * require multiple params, etc. a first name and last name). * * @param request - * the HTTP request containing the form information + * the HTTP request containing the form information * @param metadataField - * the metadata field which can store repeated values + * the metadata field which can store repeated values * @param param - * the repeated parameter on the page (used to fill out the - * metadataField) + * the repeated parameter on the page (used to fill out the + * metadataField) * * @return a List of Strings */ @@ -1034,12 +1067,12 @@ public class DescribeStep extends AbstractProcessingStep * properly identify their language tag * * @param request - * the HTTP request containing the form information + * the HTTP request containing the form information * @param metadataField - * the metadata field which can store repeated values + * the metadata field which can store repeated values * @param param - * the repeated parameter on the page (used to fill out the - * metadataField) + * the repeated parameter on the page (used to fill out the + * metadataField) * @return a TreeMap of Integer and Strings */ protected TreeMap getRepeatedParameterWithTheirIndices(HttpServletRequest request, @@ -1108,6 +1141,8 @@ public class DescribeStep extends AbstractProcessingStep * Return the HTML / DRI field name for the given input. * * @param input + * represents line in an imput form + * @return metadata field in the "schema_element_qualifier" format */ public static String getFieldName(DCInput input) { diff --git a/dspace-api/src/main/java/org/dspace/submit/step/InitialQuestionsStep.java b/dspace-api/src/main/java/org/dspace/submit/step/InitialQuestionsStep.java index 4ca4c6a8bf..9c7d7104da 100644 --- a/dspace-api/src/main/java/org/dspace/submit/step/InitialQuestionsStep.java +++ b/dspace-api/src/main/java/org/dspace/submit/step/InitialQuestionsStep.java @@ -93,6 +93,15 @@ public class InitialQuestionsStep extends AbstractProcessingStep * @return Status or error flag which will be processed by * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 int doProcessing(Context context, HttpServletRequest request, @@ -284,6 +293,15 @@ public class InitialQuestionsStep extends AbstractProcessingStep * if published before * @param multipleFiles * if there will be multiple files + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ protected void processVerifyPrune(Context context, HttpServletRequest request, HttpServletResponse response, diff --git a/dspace-api/src/main/java/org/dspace/submit/step/UploadStep.java b/dspace-api/src/main/java/org/dspace/submit/step/UploadStep.java index 8656b2ec4a..bf44663707 100644 --- a/dspace-api/src/main/java/org/dspace/submit/step/UploadStep.java +++ b/dspace-api/src/main/java/org/dspace/submit/step/UploadStep.java @@ -114,16 +114,25 @@ public class UploadStep extends AbstractProcessingStep * it should perform *all* of its processing in this method! * * @param context - * current DSpace context + * The relevant DSpace Context. * @param request - * current servlet request object + * Servlet's HTTP request object. * @param response - * current servlet response object + * Servlet's HTTP response object. * @param subInfo - * submission info object + * submission info object * @return Status or error flag which will be processed by - * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, - * no errors occurred!) + * doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned, + * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 int doProcessing(Context context, HttpServletRequest request, @@ -160,7 +169,7 @@ public class UploadStep extends AbstractProcessingStep // if user pressed jump-to button in process bar, // return success (so that jump will occur) if (buttonPressed.startsWith(PROGRESS_BAR_PREFIX) || - buttonPressed.startsWith(PREVIOUS_BUTTON)) + buttonPressed.startsWith(PREVIOUS_BUTTON)) { // check if a file is required to be uploaded if (fileRequired && !itemService.hasUploadedFiles(item)) @@ -350,9 +359,9 @@ public class UploadStep extends AbstractProcessingStep List bundles = itemService.getBundles(item, "ORIGINAL"); if (bundles.size() > 0) { - bundles.get(0).setPrimaryBitstreamID(bitstreamService.find(context, Util.getUUIDParameter(request, + bundles.get(0).setPrimaryBitstreamID(bitstreamService.find(context, Util.getUUIDParameter(request, "primary_bitstream_id"))); - bundleService.update(context, bundles.get(0)); + bundleService.update(context, bundles.get(0)); } } @@ -388,11 +397,12 @@ public class UploadStep extends AbstractProcessingStep * once! * * @param request - * The HTTP Request + * Servlet's HTTP request object. * @param subInfo - * The current submission information object - * + * The current submission information object * @return the number of pages in this step + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ @Override public int getNumberOfPages(HttpServletRequest request, @@ -413,14 +423,21 @@ public class UploadStep extends AbstractProcessingStep * Remove a file from an item * * @param context - * current DSpace context + * The relevant DSpace Context. * @param item - * Item where file should be removed from + * Item where file should be removed from * @param bitstreamID - * The id of bitstream representing the file to remove + * The id of bitstream representing the file to remove * @return Status or error flag which will be processed by - * UI-related code! (if STATUS_COMPLETE or 0 is returned, - * no errors occurred!) + * UI-related code! (if STATUS_COMPLETE or 0 is returned, + * no errors occurred!) + * @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. */ protected int processRemoveFile(Context context, Item item, UUID bitstreamID) throws IOException, SQLException, AuthorizeException @@ -468,17 +485,25 @@ public class UploadStep extends AbstractProcessingStep * Process the upload of a new file! * * @param context - * current DSpace context + * The relevant DSpace Context. * @param request - * current servlet request object + * Servlet's HTTP request object. * @param response - * current servlet response object + * Servlet's HTTP response object. * @param subInfo - * submission info object - * + * submission info object * @return Status or error flag which will be processed by - * UI-related code! (if STATUS_COMPLETE or 0 is returned, - * no errors occurred!) + * UI-related code! (if STATUS_COMPLETE or 0 is returned, + * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 int processUploadFile(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -664,6 +689,15 @@ public class UploadStep extends AbstractProcessingStep * @return Status or error flag which will be processed by * UI-related code! (if STATUS_COMPLETE or 0 is returned, * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ protected int processSaveFileFormat(Context context, HttpServletRequest request, HttpServletResponse response, @@ -703,17 +737,25 @@ public class UploadStep extends AbstractProcessingStep * Process input from the "change file description" page * * @param context - * current DSpace context + * The relevant DSpace Context. * @param request - * current servlet request object + * Servlet's HTTP request object. * @param response - * current servlet response object + * Servlet's HTTP response object. * @param subInfo - * submission info object - * + * submission info object * @return Status or error flag which will be processed by - * UI-related code! (if STATUS_COMPLETE or 0 is returned, - * no errors occurred!) + * UI-related code! (if STATUS_COMPLETE or 0 is returned, + * no errors occurred!) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ protected int processSaveFileDescription(Context context, HttpServletRequest request, HttpServletResponse response, diff --git a/dspace-api/src/main/java/org/dspace/usage/UsageSearchEvent.java b/dspace-api/src/main/java/org/dspace/usage/UsageSearchEvent.java index 30b99d72aa..efc9143f9b 100644 --- a/dspace-api/src/main/java/org/dspace/usage/UsageSearchEvent.java +++ b/dspace-api/src/main/java/org/dspace/usage/UsageSearchEvent.java @@ -15,7 +15,7 @@ import java.util.List; /** * Extends the standard usage event to contain search information - * search information includes the query(s) used & the scope + * search information includes the query/queries used and the scope * * @author Kevin Van de Velde (kevin at atmire dot com) * @author Ben Bosman (ben at atmire dot com) diff --git a/dspace-api/src/main/java/org/dspace/util/SolrImportExport.java b/dspace-api/src/main/java/org/dspace/util/SolrImportExport.java index 8fab3b9f39..bf85973a24 100644 --- a/dspace-api/src/main/java/org/dspace/util/SolrImportExport.java +++ b/dspace-api/src/main/java/org/dspace/util/SolrImportExport.java @@ -42,697 +42,702 @@ import java.util.*; public class SolrImportExport { - private static final ThreadLocal SOLR_DATE_FORMAT; - private static final ThreadLocal SOLR_DATE_FORMAT_NO_MS; - private static final ThreadLocal EXPORT_DATE_FORMAT; + private static final ThreadLocal SOLR_DATE_FORMAT; + private static final ThreadLocal SOLR_DATE_FORMAT_NO_MS; + private static final ThreadLocal EXPORT_DATE_FORMAT; - static - { - SOLR_DATE_FORMAT = new ThreadLocal(){ - @Override - protected DateFormat initialValue() { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return simpleDateFormat; - } - }; - SOLR_DATE_FORMAT_NO_MS = new ThreadLocal(){ - @Override - protected DateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - } - }; - EXPORT_DATE_FORMAT = new ThreadLocal() { - @Override - protected DateFormat initialValue() { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM"); - simpleDateFormat.setTimeZone(TimeZone.getDefault()); - return simpleDateFormat; - } - }; - } + static + { + SOLR_DATE_FORMAT = new ThreadLocal() { + @Override + protected DateFormat initialValue() { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + return simpleDateFormat; + } + }; + SOLR_DATE_FORMAT_NO_MS = new ThreadLocal() { + @Override + protected DateFormat initialValue() { + return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + } + }; + EXPORT_DATE_FORMAT = new ThreadLocal() { + @Override + protected DateFormat initialValue() { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM"); + simpleDateFormat.setTimeZone(TimeZone.getDefault()); + return simpleDateFormat; + } + }; + } - private static final String ACTION_OPTION = "a"; - private static final String CLEAR_OPTION = "c"; - private static final String DIRECTORY_OPTION = "d"; - private static final String HELP_OPTION = "h"; - private static final String INDEX_NAME_OPTION = "i"; - private static final String KEEP_OPTION = "k"; - private static final String LAST_OPTION = "l"; + private static final String ACTION_OPTION = "a"; + private static final String CLEAR_OPTION = "c"; + private static final String DIRECTORY_OPTION = "d"; + private static final String HELP_OPTION = "h"; + private static final String INDEX_NAME_OPTION = "i"; + private static final String KEEP_OPTION = "k"; + private static final String LAST_OPTION = "l"; - public static final int ROWS_PER_FILE = 10_000; + public static final int ROWS_PER_FILE = 10_000; - private static final Logger log = Logger.getLogger(SolrImportExport.class); + private static final Logger log = Logger.getLogger(SolrImportExport.class); - /** - * Entry point for command-line invocation - * @param args command-line arguments; see help for description - * @throws ParseException if the command-line arguments cannot be parsed - */ - public static void main(String[] args) throws ParseException - { - CommandLineParser parser = new PosixParser(); - Options options = makeOptions(); + /** + * Entry point for command-line invocation + * @param args command-line arguments; see help for description + * @throws ParseException if the command-line arguments cannot be parsed + */ + public static void main(String[] args) throws ParseException + { + CommandLineParser parser = new PosixParser(); + Options options = makeOptions(); - try - { - CommandLine line = parser.parse(options, args); - if (line.hasOption(HELP_OPTION)) - { - printHelpAndExit(options, 0); - } + try + { + CommandLine line = parser.parse(options, args); + if (line.hasOption(HELP_OPTION)) + { + printHelpAndExit(options, 0); + } - if (!line.hasOption(INDEX_NAME_OPTION)) - { - System.err.println("This command requires the index-name option but none was present."); - printHelpAndExit(options, 1); - } - String[] indexNames = line.getOptionValues(INDEX_NAME_OPTION); + if (!line.hasOption(INDEX_NAME_OPTION)) + { + System.err.println("This command requires the index-name option but none was present."); + printHelpAndExit(options, 1); + } + String[] indexNames = line.getOptionValues(INDEX_NAME_OPTION); - String directoryName = makeDirectoryName(line.getOptionValue(DIRECTORY_OPTION)); + String directoryName = makeDirectoryName(line.getOptionValue(DIRECTORY_OPTION)); - String action = line.getOptionValue(ACTION_OPTION, "export"); - if ("import".equals(action)) - { - for (String indexName : indexNames) - { - File importDir = new File(directoryName); - if (!importDir.exists() || !importDir.canRead()) - { - System.err.println("Import directory " + directoryName - + " doesn't exist or is not readable by the current user. Not importing index " - + indexName); - continue; // skip this index - } - try - { - String solrUrl = makeSolrUrl(indexName); - boolean clear = line.hasOption(CLEAR_OPTION); - importIndex(indexName, importDir, solrUrl, clear, clear); - } - catch (IOException | SolrServerException | SolrImportExportException e) - { - System.err.println("Problem encountered while trying to import index " + indexName + "."); - e.printStackTrace(System.err); - } - } - } - else if ("export".equals(action)) - { - for (String indexName : indexNames) - { - String lastValue = line.getOptionValue(LAST_OPTION); - File exportDir = new File(directoryName); - if (exportDir.exists() && !exportDir.canWrite()) - { - System.err.println("Export directory " + directoryName - + " is not writable by the current user. Not exporting index " - + indexName); - continue; - } + String action = line.getOptionValue(ACTION_OPTION, "export"); + if ("import".equals(action)) + { + for (String indexName : indexNames) + { + File importDir = new File(directoryName); + if (!importDir.exists() || !importDir.canRead()) + { + System.err.println("Import directory " + directoryName + + " doesn't exist or is not readable by the current user. Not importing index " + + indexName); + continue; // skip this index + } + try + { + String solrUrl = makeSolrUrl(indexName); + boolean clear = line.hasOption(CLEAR_OPTION); + importIndex(indexName, importDir, solrUrl, clear, clear); + } + catch (IOException | SolrServerException | SolrImportExportException e) + { + System.err.println("Problem encountered while trying to import index " + indexName + "."); + e.printStackTrace(System.err); + } + } + } + else if ("export".equals(action)) + { + for (String indexName : indexNames) + { + String lastValue = line.getOptionValue(LAST_OPTION); + File exportDir = new File(directoryName); + if (exportDir.exists() && !exportDir.canWrite()) + { + System.err.println("Export directory " + directoryName + + " is not writable by the current user. Not exporting index " + + indexName); + continue; + } - if (!exportDir.exists()) - { - boolean created = exportDir.mkdirs(); - if (!created) - { - System.err.println("Export directory " + directoryName - + " could not be created. Not exporting index " + indexName); - } - continue; - } + if (!exportDir.exists()) + { + boolean created = exportDir.mkdirs(); + if (!created) + { + System.err.println("Export directory " + directoryName + + " could not be created. Not exporting index " + indexName); + } + continue; + } - try - { - String solrUrl = makeSolrUrl(indexName); - String timeField = makeTimeField(indexName); - exportIndex(indexName, exportDir, solrUrl, timeField, lastValue); - } - catch (SolrServerException | IOException | SolrImportExportException e) - { - System.err.println("Problem encountered while trying to export index " + indexName + "."); - e.printStackTrace(System.err); - } - } - } - else if ("reindex".equals(action)) - { - for (String indexName : indexNames) - { - try { - boolean keepExport = line.hasOption(KEEP_OPTION); - reindex(indexName, directoryName, keepExport); - } catch (IOException | SolrServerException | SolrImportExportException e) { - e.printStackTrace(); - } - } - } - else - { - System.err.println("Unknown action " + action + "; must be import, export or reindex."); - printHelpAndExit(options, 1); - } - } - catch (ParseException e) - { - System.err.println("Cannot read command options"); - printHelpAndExit(options, 1); - } - } + try + { + String solrUrl = makeSolrUrl(indexName); + String timeField = makeTimeField(indexName); + exportIndex(indexName, exportDir, solrUrl, timeField, lastValue); + } + catch (SolrServerException | IOException | SolrImportExportException e) + { + System.err.println("Problem encountered while trying to export index " + indexName + "."); + e.printStackTrace(System.err); + } + } + } + else if ("reindex".equals(action)) + { + for (String indexName : indexNames) + { + try { + boolean keepExport = line.hasOption(KEEP_OPTION); + reindex(indexName, directoryName, keepExport); + } catch (IOException | SolrServerException | SolrImportExportException e) { + e.printStackTrace(); + } + } + } + else + { + System.err.println("Unknown action " + action + "; must be import, export or reindex."); + printHelpAndExit(options, 1); + } + } + catch (ParseException e) + { + System.err.println("Cannot read command options"); + printHelpAndExit(options, 1); + } + } - private static Options makeOptions() { - Options options = new Options(); - options.addOption(ACTION_OPTION, "action", true, "The action to perform: import, export or reindex. Default: export."); - options.addOption(CLEAR_OPTION, "clear", false, "When importing, also clear the index first. Ignored when action is export or reindex."); - options.addOption(DIRECTORY_OPTION, "directory", true, - "The absolute path for the directory to use for import or export. If omitted, [dspace]/solr-export is used."); - options.addOption(HELP_OPTION, "help", false, "Get help on options for this command."); - options.addOption(INDEX_NAME_OPTION, "index-name", true, - "The names of the indexes to process. At least one is required. Available indexes are: authority, statistics."); - options.addOption(KEEP_OPTION, "keep", false, "When reindexing, keep the contents of the data export directory." + - " By default, the contents of this directory will be deleted once the reindex has finished." + - " Ignored when action is export or import."); - options.addOption(LAST_OPTION, "last", true, "When exporting, export records from the last [timeperiod] only." + - " This can be one of: 'd' (beginning of yesterday through to now);" + - " 'm' (beginning of the previous month through to end of the previous month);" + - " a number, in which case the last [number] of days are exported, through to now (use 0 for today's data)." + - " Date calculation is done in UTC. If omitted, all documents are exported."); - return options; - } + private static Options makeOptions() { + Options options = new Options(); + options.addOption(ACTION_OPTION, "action", true, + "The action to perform: import, export or reindex. Default: export."); + options.addOption(CLEAR_OPTION, "clear", false, + "When importing, also clear the index first. Ignored when action is export or reindex."); + options.addOption(DIRECTORY_OPTION, "directory", true, + "The absolute path for the directory to use for import or export. If omitted, [dspace]/solr-export is used."); + options.addOption(HELP_OPTION, "help", false, + "Get help on options for this command."); + options.addOption(INDEX_NAME_OPTION, "index-name", true, + "The names of the indexes to process. At least one is required. Available indexes are: authority, statistics."); + options.addOption(KEEP_OPTION, "keep", false, + "When reindexing, keep the contents of the data export directory." + + " By default, the contents of this directory will be deleted once the reindex has finished." + + " Ignored when action is export or import."); + options.addOption(LAST_OPTION, "last", true, + "When exporting, export records from the last [timeperiod] only." + + " This can be one of: 'd' (beginning of yesterday through to now);" + + " 'm' (beginning of the previous month through to end of the previous month);" + + " a number, in which case the last [number] of days are exported, through to now (use 0 for today's data)." + + " Date calculation is done in UTC. If omitted, all documents are exported."); + return options; + } - /** - * Reindexes the specified core - * - * @param indexName the name of the core to reindex - * @param exportDirName the name of the directory to use for export. If this directory doesn't exist, it will be created. - * @param keepExport whether to keep the contents of the exportDir after the reindex. If keepExport is false and the - * export directory was created by this method, the export directory will be deleted at the end of the reimport. - */ - private static void reindex(String indexName, String exportDirName, boolean keepExport) - throws IOException, SolrServerException, SolrImportExportException { - String tempIndexName = indexName + "-temp"; + /** + * Reindexes the specified core + * + * @param indexName the name of the core to reindex + * @param exportDirName the name of the directory to use for export. If this directory doesn't exist, it will be created. + * @param keepExport whether to keep the contents of the exportDir after the reindex. If keepExport is false and the + * export directory was created by this method, the export directory will be deleted at the end of the reimport. + */ + private static void reindex(String indexName, String exportDirName, boolean keepExport) + throws IOException, SolrServerException, SolrImportExportException { + String tempIndexName = indexName + "-temp"; - String origSolrUrl = makeSolrUrl(indexName); - String baseSolrUrl = StringUtils.substringBeforeLast(origSolrUrl, "/"); // need to get non-core solr URL - String tempSolrUrl = baseSolrUrl + "/" + tempIndexName; + String origSolrUrl = makeSolrUrl(indexName); + String baseSolrUrl = StringUtils.substringBeforeLast(origSolrUrl, "/"); // need to get non-core solr URL + String tempSolrUrl = baseSolrUrl + "/" + tempIndexName; - String solrInstanceDir = ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr" + File.separator + indexName; - // the [dspace]/solr/[indexName]/conf directory needs to be available on the local machine for this to work - // -- we need access to the schema.xml and solrconfig.xml file, plus files referenced from there - // if this directory can't be found, output an error message and skip this index - File solrInstance = new File(solrInstanceDir); - if (!solrInstance.exists() || !solrInstance.canRead() || !solrInstance.isDirectory()) - { - throw new SolrImportExportException("Directory " + solrInstanceDir + "/conf/ doesn't exist or isn't readable." + - " The reindexing process requires the Solr configuration directory for this index to be present on the local machine" + - " even if Solr is running on a different host. Not reindexing index " + indexName); - } + String solrInstanceDir = ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr" + File.separator + indexName; + // the [dspace]/solr/[indexName]/conf directory needs to be available on the local machine for this to work + // -- we need access to the schema.xml and solrconfig.xml file, plus files referenced from there + // if this directory can't be found, output an error message and skip this index + File solrInstance = new File(solrInstanceDir); + if (!solrInstance.exists() || !solrInstance.canRead() || !solrInstance.isDirectory()) + { + throw new SolrImportExportException("Directory " + solrInstanceDir + "/conf/ doesn't exist or isn't readable." + + " The reindexing process requires the Solr configuration directory for this index to be present on the local machine" + + " even if Solr is running on a different host. Not reindexing index " + indexName); + } - String timeField = makeTimeField(indexName); + String timeField = makeTimeField(indexName); - // Ensure the export directory exists and is writable - File exportDir = new File(exportDirName); - boolean createdExportDir = exportDir.mkdirs(); - if (!createdExportDir && !exportDir.exists()) - { - throw new SolrImportExportException("Could not create export directory " + exportDirName); - } - if (!exportDir.canWrite()) - { - throw new SolrImportExportException("Can't write to export directory " + exportDirName); - } + // Ensure the export directory exists and is writable + File exportDir = new File(exportDirName); + boolean createdExportDir = exportDir.mkdirs(); + if (!createdExportDir && !exportDir.exists()) + { + throw new SolrImportExportException("Could not create export directory " + exportDirName); + } + if (!exportDir.canWrite()) + { + throw new SolrImportExportException("Can't write to export directory " + exportDirName); + } - try - { - HttpSolrServer adminSolr = new HttpSolrServer(baseSolrUrl); + try + { + HttpSolrServer adminSolr = new HttpSolrServer(baseSolrUrl); - // try to find out size of core and compare with free space in export directory - CoreAdminResponse status = CoreAdminRequest.getStatus(indexName, adminSolr); - Object coreSizeObj = status.getCoreStatus(indexName).get("sizeInBytes"); - long coreSize = coreSizeObj != null ? Long.valueOf(coreSizeObj.toString()) : -1; - long usableExportSpace = exportDir.getUsableSpace(); - if (coreSize >= 0 && usableExportSpace < coreSize) - { - System.err.println("Not enough space in export directory " + exportDirName - + "; need at least as much space as the index (" - + FileUtils.byteCountToDisplaySize(coreSize) - + ") but usable space in export directory is only " - + FileUtils.byteCountToDisplaySize(usableExportSpace) - + ". Not continuing with reindex, please use the " + DIRECTORY_OPTION - + " option to specify an alternative export directy with sufficient space."); - return; - } + // try to find out size of core and compare with free space in export directory + CoreAdminResponse status = CoreAdminRequest.getStatus(indexName, adminSolr); + Object coreSizeObj = status.getCoreStatus(indexName).get("sizeInBytes"); + long coreSize = coreSizeObj != null ? Long.valueOf(coreSizeObj.toString()) : -1; + long usableExportSpace = exportDir.getUsableSpace(); + if (coreSize >= 0 && usableExportSpace < coreSize) + { + System.err.println("Not enough space in export directory " + exportDirName + + "; need at least as much space as the index (" + + FileUtils.byteCountToDisplaySize(coreSize) + + ") but usable space in export directory is only " + + FileUtils.byteCountToDisplaySize(usableExportSpace) + + ". Not continuing with reindex, please use the " + DIRECTORY_OPTION + + " option to specify an alternative export directy with sufficient space."); + return; + } - // Create a temp directory to store temporary core data - File tempDataDir = new File(ConfigurationManager.getProperty("dspace.dir") + File.separator + "temp" + File.separator + "solr-data"); - boolean createdTempDataDir = tempDataDir.mkdirs(); - if (!createdTempDataDir && !tempDataDir.exists()) - { - throw new SolrImportExportException("Could not create temporary data directory " + tempDataDir.getCanonicalPath()); - } - if (!tempDataDir.canWrite()) - { - throw new SolrImportExportException("Can't write to temporary data directory " + tempDataDir.getCanonicalPath()); - } + // Create a temp directory to store temporary core data + File tempDataDir = new File(ConfigurationManager.getProperty("dspace.dir") + File.separator + "temp" + File.separator + "solr-data"); + boolean createdTempDataDir = tempDataDir.mkdirs(); + if (!createdTempDataDir && !tempDataDir.exists()) + { + throw new SolrImportExportException("Could not create temporary data directory " + tempDataDir.getCanonicalPath()); + } + if (!tempDataDir.canWrite()) + { + throw new SolrImportExportException("Can't write to temporary data directory " + tempDataDir.getCanonicalPath()); + } - try - { - // create a temporary core to hold documents coming in during the reindex - CoreAdminRequest.Create createRequest = new CoreAdminRequest.Create(); - createRequest.setInstanceDir(solrInstanceDir); - createRequest.setDataDir(tempDataDir.getCanonicalPath()); - createRequest.setCoreName(tempIndexName); + try + { + // create a temporary core to hold documents coming in during the reindex + CoreAdminRequest.Create createRequest = new CoreAdminRequest.Create(); + createRequest.setInstanceDir(solrInstanceDir); + createRequest.setDataDir(tempDataDir.getCanonicalPath()); + createRequest.setCoreName(tempIndexName); - createRequest.process(adminSolr).getStatus(); - } - catch (SolrServerException e) - { - // try to continue -- it may just be that the core already existed from a previous, failed attempt - System.err.println("Caught exception when trying to create temporary core: " + e.getMessage() + "; trying to recover."); - e.printStackTrace(System.err); - } + createRequest.process(adminSolr).getStatus(); + } + catch (SolrServerException e) + { + // try to continue -- it may just be that the core already existed from a previous, failed attempt + System.err.println("Caught exception when trying to create temporary core: " + e.getMessage() + "; trying to recover."); + e.printStackTrace(System.err); + } - // swap actual core with temporary one - CoreAdminRequest swapRequest = new CoreAdminRequest(); - swapRequest.setCoreName(indexName); - swapRequest.setOtherCoreName(tempIndexName); - swapRequest.setAction(CoreAdminParams.CoreAdminAction.SWAP); - swapRequest.process(adminSolr); + // swap actual core with temporary one + CoreAdminRequest swapRequest = new CoreAdminRequest(); + swapRequest.setCoreName(indexName); + swapRequest.setOtherCoreName(tempIndexName); + swapRequest.setAction(CoreAdminParams.CoreAdminAction.SWAP); + swapRequest.process(adminSolr); - try - { - // export from the actual core (from temp core name, actual data dir) - exportIndex(indexName, exportDir, tempSolrUrl, timeField); + try + { + // export from the actual core (from temp core name, actual data dir) + exportIndex(indexName, exportDir, tempSolrUrl, timeField); - // clear actual core (temp core name, clearing actual data dir) & import - importIndex(indexName, exportDir, tempSolrUrl, true, true); - } - catch (Exception e) - { - // we ran into some problems with the export/import -- keep going to try and restore the solr cores - System.err.println("Encountered problem during reindex: " + e.getMessage() + ", will attempt to restore Solr cores"); - e.printStackTrace(System.err); - } + // clear actual core (temp core name, clearing actual data dir) & import + importIndex(indexName, exportDir, tempSolrUrl, true, true); + } + catch (Exception e) + { + // we ran into some problems with the export/import -- keep going to try and restore the solr cores + System.err.println("Encountered problem during reindex: " + e.getMessage() + ", will attempt to restore Solr cores"); + e.printStackTrace(System.err); + } - // commit changes - HttpSolrServer origSolr = new HttpSolrServer(origSolrUrl); - origSolr.commit(); + // commit changes + HttpSolrServer origSolr = new HttpSolrServer(origSolrUrl); + origSolr.commit(); - // swap back (statistics now going to actual core name in actual data dir) - swapRequest = new CoreAdminRequest(); - swapRequest.setCoreName(tempIndexName); - swapRequest.setOtherCoreName(indexName); - swapRequest.setAction(CoreAdminParams.CoreAdminAction.SWAP); - swapRequest.process(adminSolr); + // swap back (statistics now going to actual core name in actual data dir) + swapRequest = new CoreAdminRequest(); + swapRequest.setCoreName(tempIndexName); + swapRequest.setOtherCoreName(indexName); + swapRequest.setAction(CoreAdminParams.CoreAdminAction.SWAP); + swapRequest.process(adminSolr); - // export all docs from now-temp core into export directory -- this won't cause name collisions with the actual export - // because the core name for the temporary export has -temp in it while the actual core doesn't - exportIndex(tempIndexName, exportDir, tempSolrUrl, timeField); - // ...and import them into the now-again-actual core *without* clearing - importIndex(tempIndexName, exportDir, origSolrUrl, false, true); + // export all docs from now-temp core into export directory -- this won't cause name collisions with the actual export + // because the core name for the temporary export has -temp in it while the actual core doesn't + exportIndex(tempIndexName, exportDir, tempSolrUrl, timeField); + // ...and import them into the now-again-actual core *without* clearing + importIndex(tempIndexName, exportDir, origSolrUrl, false, true); - // commit changes - origSolr.commit(); + // commit changes + origSolr.commit(); - // unload now-temp core (temp core name) - CoreAdminRequest.unloadCore(tempIndexName, false, false, adminSolr); + // unload now-temp core (temp core name) + CoreAdminRequest.unloadCore(tempIndexName, false, false, adminSolr); - // clean up temporary data dir if this method created it - if (createdTempDataDir && tempDataDir.exists()) - { - FileUtils.deleteDirectory(tempDataDir); - } - } - finally - { - // clean up export dir if appropriate - if (!keepExport && createdExportDir && exportDir.exists()) - { - FileUtils.deleteDirectory(exportDir); - } - } - } + // clean up temporary data dir if this method created it + if (createdTempDataDir && tempDataDir.exists()) + { + FileUtils.deleteDirectory(tempDataDir); + } + } + finally + { + // clean up export dir if appropriate + if (!keepExport && createdExportDir && exportDir.exists()) + { + FileUtils.deleteDirectory(exportDir); + } + } + } - /** - * Exports all documents in the given index to the specified target directory in batches of #ROWS_PER_FILE. - * See #makeExportFilename for the file names that are generated. - * - * @param indexName The index to export. - * @param toDir The target directory for the export. Will be created if it doesn't exist yet. The directory must be writeable. - * @param solrUrl The solr URL for the index to export. Must not be null. - * @param timeField The time field to use for sorting the export. Must not be null. - * @throws SolrServerException if there is a problem with exporting the index. - * @throws IOException if there is a problem creating the files or communicating with Solr. - * @throws SolrImportExportException if there is a problem in communicating with Solr. - */ - public static void exportIndex(String indexName, File toDir, String solrUrl, String timeField) - throws SolrServerException, SolrImportExportException, IOException { - exportIndex(indexName, toDir, solrUrl, timeField, null); - } + /** + * Exports all documents in the given index to the specified target directory in batches of #ROWS_PER_FILE. + * See #makeExportFilename for the file names that are generated. + * + * @param indexName The index to export. + * @param toDir The target directory for the export. Will be created if it doesn't exist yet. The directory must be writeable. + * @param solrUrl The solr URL for the index to export. Must not be null. + * @param timeField The time field to use for sorting the export. Must not be null. + * @throws SolrServerException if there is a problem with exporting the index. + * @throws IOException if there is a problem creating the files or communicating with Solr. + * @throws SolrImportExportException if there is a problem in communicating with Solr. + */ + public static void exportIndex(String indexName, File toDir, String solrUrl, String timeField) + throws SolrServerException, SolrImportExportException, IOException { + exportIndex(indexName, toDir, solrUrl, timeField, null); + } - /** - * Import previously exported documents (or externally created CSV files that have the appropriate structure) into the specified index. - * @param indexName the index to import. - * @param fromDir the source directory. Must exist and be readable. - * The importer will look for files whose name starts with

indexName
- * and ends with .csv (to match what is generated by #makeExportFilename). - * @param solrUrl The solr URL for the index to export. Must not be null. - * @param clear if true, clear the index before importing. - * @param overwrite if true, skip _version_ field on import to disable Solr's optimistic concurrency functionality - * @throws IOException if there is a problem reading the files or communicating with Solr. - * @throws SolrServerException if there is a problem reading the files or communicating with Solr. - * @throws SolrImportExportException if there is a problem communicating with Solr. - */ - public static void importIndex(final String indexName, File fromDir, String solrUrl, boolean clear, boolean overwrite) - throws IOException, SolrServerException, SolrImportExportException - { - if (StringUtils.isBlank(solrUrl)) - { - throw new SolrImportExportException("Could not construct solr URL for index" + indexName + ", aborting export."); - } + /** + * Import previously exported documents (or externally created CSV files that have the appropriate structure) into the specified index. + * @param indexName the index to import. + * @param fromDir the source directory. Must exist and be readable. + * The importer will look for files whose name starts with
indexName
+ * and ends with .csv (to match what is generated by #makeExportFilename). + * @param solrUrl The solr URL for the index to export. Must not be null. + * @param clear if true, clear the index before importing. + * @param overwrite if true, skip _version_ field on import to disable Solr's optimistic concurrency functionality + * @throws IOException if there is a problem reading the files or communicating with Solr. + * @throws SolrServerException if there is a problem reading the files or communicating with Solr. + * @throws SolrImportExportException if there is a problem communicating with Solr. + */ + public static void importIndex(final String indexName, File fromDir, String solrUrl, boolean clear, boolean overwrite) + throws IOException, SolrServerException, SolrImportExportException + { + if (StringUtils.isBlank(solrUrl)) + { + throw new SolrImportExportException("Could not construct solr URL for index" + indexName + ", aborting export."); + } - if (!fromDir.exists() || !fromDir.canRead()) - { - throw new SolrImportExportException("Source directory " + fromDir - + " doesn't exist or isn't readable, aborting export of index " - + indexName); - } + if (!fromDir.exists() || !fromDir.canRead()) + { + throw new SolrImportExportException("Source directory " + fromDir + + " doesn't exist or isn't readable, aborting export of index " + + indexName); + } - HttpSolrServer solr = new HttpSolrServer(solrUrl); + HttpSolrServer solr = new HttpSolrServer(solrUrl); - // must get multivalue fields before clearing - List multivaluedFields = getMultiValuedFields(solr); + // must get multivalue fields before clearing + List multivaluedFields = getMultiValuedFields(solr); - if (clear) - { - clearIndex(solrUrl); - } + if (clear) + { + clearIndex(solrUrl); + } - File[] files = fromDir.listFiles(new FilenameFilter() - { - @Override - public boolean accept(File dir, String name) - { - return name.startsWith(indexName) && name.endsWith(".csv"); - } - }); + File[] files = fromDir.listFiles(new FilenameFilter() + { + @Override + public boolean accept(File dir, String name) + { + return name.startsWith(indexName) && name.endsWith(".csv"); + } + }); - if (files == null || files.length == 0) - { - log.warn("No export files found in directory " + fromDir.getCanonicalPath() + " for index " + indexName); - return; - } + if (files == null || files.length == 0) + { + log.warn("No export files found in directory " + fromDir.getCanonicalPath() + " for index " + indexName); + return; + } - Arrays.sort(files); + Arrays.sort(files); - for (File file : files) - { - log.info("Importing file " + file.getCanonicalPath()); - ContentStreamUpdateRequest contentStreamUpdateRequest = new ContentStreamUpdateRequest("/update/csv"); - if (overwrite) - { - contentStreamUpdateRequest.setParam("skip", "_version_"); - } - for (String mvField : multivaluedFields) { - contentStreamUpdateRequest.setParam("f." + mvField + ".split", "true"); - contentStreamUpdateRequest.setParam("f." + mvField + ".escape", "\\"); - } - contentStreamUpdateRequest.setParam("stream.contentType", "text/csv;charset=utf-8"); - contentStreamUpdateRequest.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true); - contentStreamUpdateRequest.addFile(file, "text/csv;charset=utf-8"); + for (File file : files) + { + log.info("Importing file " + file.getCanonicalPath()); + ContentStreamUpdateRequest contentStreamUpdateRequest = new ContentStreamUpdateRequest("/update/csv"); + if (overwrite) + { + contentStreamUpdateRequest.setParam("skip", "_version_"); + } + for (String mvField : multivaluedFields) { + contentStreamUpdateRequest.setParam("f." + mvField + ".split", "true"); + contentStreamUpdateRequest.setParam("f." + mvField + ".escape", "\\"); + } + contentStreamUpdateRequest.setParam("stream.contentType", "text/csv;charset=utf-8"); + contentStreamUpdateRequest.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true); + contentStreamUpdateRequest.addFile(file, "text/csv;charset=utf-8"); - solr.request(contentStreamUpdateRequest); - } + solr.request(contentStreamUpdateRequest); + } - solr.commit(true, true); - } + solr.commit(true, true); + } - /** - * Determine the names of all multi-valued fields from the data in the index. - * @param solr the solr server to query. - * @return A list containing all multi-valued fields, or an empty list if none are found / there aren't any. - */ - private static List getMultiValuedFields(HttpSolrServer solr) - { - List result = new ArrayList<>(); - try - { - LukeRequest request = new LukeRequest(); - // this needs to be a non-schema request, otherwise we'll miss dynamic fields - LukeResponse response = request.process(solr); - Map fields = response.getFieldInfo(); - for (LukeResponse.FieldInfo info : fields.values()) - { - if (info.getSchema().contains(FieldFlag.MULTI_VALUED.getAbbreviation() + "")) - { - result.add(info.getName()); - } - } - } - catch (IOException | SolrServerException e) - { - log.fatal("Cannot determine which fields are multi valued: " + e.getMessage(), e); - } - return result; - } + /** + * Determine the names of all multi-valued fields from the data in the index. + * @param solr the solr server to query. + * @return A list containing all multi-valued fields, or an empty list if none are found / there aren't any. + */ + private static List getMultiValuedFields(HttpSolrServer solr) + { + List result = new ArrayList<>(); + try + { + LukeRequest request = new LukeRequest(); + // this needs to be a non-schema request, otherwise we'll miss dynamic fields + LukeResponse response = request.process(solr); + Map fields = response.getFieldInfo(); + for (LukeResponse.FieldInfo info : fields.values()) + { + if (info.getSchema().contains(FieldFlag.MULTI_VALUED.getAbbreviation() + "")) + { + result.add(info.getName()); + } + } + } + catch (IOException | SolrServerException e) + { + log.fatal("Cannot determine which fields are multi valued: " + e.getMessage(), e); + } + return result; + } - /** - * Remove all documents from the Solr index with the given URL, then commit and optimise the index. - * - * @throws IOException if there is a problem in communicating with Solr. - * @throws SolrServerException if there is a problem in communicating with Solr. - * @param solrUrl URL of the Solr core to clear. - */ - public static void clearIndex(String solrUrl) throws IOException, SolrServerException - { - HttpSolrServer solr = new HttpSolrServer(solrUrl); - solr.deleteByQuery("*:*"); - solr.commit(); - solr.optimize(); - } + /** + * Remove all documents from the Solr index with the given URL, then commit and optimise the index. + * + * @throws IOException if there is a problem in communicating with Solr. + * @throws SolrServerException if there is a problem in communicating with Solr. + * @param solrUrl URL of the Solr core to clear. + */ + public static void clearIndex(String solrUrl) throws IOException, SolrServerException + { + HttpSolrServer solr = new HttpSolrServer(solrUrl); + solr.deleteByQuery("*:*"); + solr.commit(); + solr.optimize(); + } - /** - * Exports documents from the given index to the specified target directory in batches of #ROWS_PER_FILE, starting at fromWhen (or all documents). - * See #makeExportFilename for the file names that are generated. - * - * @param indexName The index to export. - * @param toDir The target directory for the export. Will be created if it doesn't exist yet. The directory must be writeable. - * @param solrUrl The solr URL for the index to export. Must not be null. - * @param timeField The time field to use for sorting the export. Must not be null. - * @param fromWhen Optionally, from when to export. See options for allowed values. If null or empty, all documents will be exported. - * @throws SolrServerException if there is a problem with exporting the index. - * @throws IOException if there is a problem creating the files or communicating with Solr. - * @throws SolrImportExportException if there is a problem in communicating with Solr. - */ - public static void exportIndex(String indexName, File toDir, String solrUrl, String timeField, String fromWhen) - throws SolrServerException, IOException, SolrImportExportException - { - if (StringUtils.isBlank(solrUrl)) - { - throw new SolrImportExportException("Could not construct solr URL for index" + indexName + ", aborting export."); - } + /** + * Exports documents from the given index to the specified target directory in batches of #ROWS_PER_FILE, starting at fromWhen (or all documents). + * See #makeExportFilename for the file names that are generated. + * + * @param indexName The index to export. + * @param toDir The target directory for the export. Will be created if it doesn't exist yet. The directory must be writeable. + * @param solrUrl The solr URL for the index to export. Must not be null. + * @param timeField The time field to use for sorting the export. Must not be null. + * @param fromWhen Optionally, from when to export. See options for allowed values. If null or empty, all documents will be exported. + * @throws SolrServerException if there is a problem with exporting the index. + * @throws IOException if there is a problem creating the files or communicating with Solr. + * @throws SolrImportExportException if there is a problem in communicating with Solr. + */ + public static void exportIndex(String indexName, File toDir, String solrUrl, String timeField, String fromWhen) + throws SolrServerException, IOException, SolrImportExportException + { + if (StringUtils.isBlank(solrUrl)) + { + throw new SolrImportExportException("Could not construct solr URL for index" + indexName + ", aborting export."); + } - if (!toDir.exists() || !toDir.canWrite()) - { - throw new SolrImportExportException("Target directory " + toDir - + " doesn't exist or is not writable, aborting export of index " - + indexName); - } + if (!toDir.exists() || !toDir.canWrite()) + { + throw new SolrImportExportException("Target directory " + toDir + + " doesn't exist or is not writable, aborting export of index " + + indexName); + } - HttpSolrServer solr = new HttpSolrServer(solrUrl); + HttpSolrServer solr = new HttpSolrServer(solrUrl); - SolrQuery query = new SolrQuery("*:*"); - if (StringUtils.isNotBlank(fromWhen)) - { - String lastValueFilter = makeFilterQuery(timeField, fromWhen); - if (StringUtils.isNotBlank(lastValueFilter)) - { - query.addFilterQuery(lastValueFilter); - } - } + SolrQuery query = new SolrQuery("*:*"); + if (StringUtils.isNotBlank(fromWhen)) + { + String lastValueFilter = makeFilterQuery(timeField, fromWhen); + if (StringUtils.isNotBlank(lastValueFilter)) + { + query.addFilterQuery(lastValueFilter); + } + } - query.setRows(0); - query.setGetFieldStatistics(timeField); - Map fieldInfo = solr.query(query).getFieldStatsInfo(); - if (fieldInfo == null || !fieldInfo.containsKey(timeField)) { - log.warn("Cannot get earliest date, not exporting index " + indexName + ", time field " + timeField + ", from " + fromWhen); - return; - } - FieldStatsInfo timeFieldInfo = fieldInfo.get(timeField); - if (timeFieldInfo == null || timeFieldInfo.getMin() == null) { - log.warn("Cannot get earliest date, not exporting index " + indexName + ", time field " + timeField + ", from " + fromWhen); - return; - } - Date earliestTimestamp = (Date) timeFieldInfo.getMin(); + query.setRows(0); + query.setGetFieldStatistics(timeField); + Map fieldInfo = solr.query(query).getFieldStatsInfo(); + if (fieldInfo == null || !fieldInfo.containsKey(timeField)) { + log.warn("Cannot get earliest date, not exporting index " + indexName + ", time field " + timeField + ", from " + fromWhen); + return; + } + FieldStatsInfo timeFieldInfo = fieldInfo.get(timeField); + if (timeFieldInfo == null || timeFieldInfo.getMin() == null) { + log.warn("Cannot get earliest date, not exporting index " + indexName + ", time field " + timeField + ", from " + fromWhen); + return; + } + Date earliestTimestamp = (Date) timeFieldInfo.getMin(); - query.setGetFieldStatistics(false); - query.clearSorts(); - query.setRows(0); - query.setFacet(true); - query.add(FacetParams.FACET_RANGE, timeField); - query.add(FacetParams.FACET_RANGE_START, SOLR_DATE_FORMAT.get().format(earliestTimestamp) + "/MONTH"); - query.add(FacetParams.FACET_RANGE_END, "NOW/MONTH+1MONTH"); - query.add(FacetParams.FACET_RANGE_GAP, "+1MONTH"); - query.setFacetMinCount(1); + query.setGetFieldStatistics(false); + query.clearSorts(); + query.setRows(0); + query.setFacet(true); + query.add(FacetParams.FACET_RANGE, timeField); + query.add(FacetParams.FACET_RANGE_START, SOLR_DATE_FORMAT.get().format(earliestTimestamp) + "/MONTH"); + query.add(FacetParams.FACET_RANGE_END, "NOW/MONTH+1MONTH"); + query.add(FacetParams.FACET_RANGE_GAP, "+1MONTH"); + query.setFacetMinCount(1); - List monthFacets = solr.query(query).getFacetRanges().get(0).getCounts(); + List monthFacets = solr.query(query).getFacetRanges().get(0).getCounts(); - for (RangeFacet.Count monthFacet : monthFacets) { - Date monthStartDate; - String monthStart = monthFacet.getValue(); - try - { - monthStartDate = SOLR_DATE_FORMAT_NO_MS.get().parse(monthStart); - } - catch (java.text.ParseException e) - { - throw new SolrImportExportException("Could not read start of month batch as date: " + monthStart, e); - } - int docsThisMonth = monthFacet.getCount(); + for (RangeFacet.Count monthFacet : monthFacets) { + Date monthStartDate; + String monthStart = monthFacet.getValue(); + try + { + monthStartDate = SOLR_DATE_FORMAT_NO_MS.get().parse(monthStart); + } + catch (java.text.ParseException e) + { + throw new SolrImportExportException("Could not read start of month batch as date: " + monthStart, e); + } + int docsThisMonth = monthFacet.getCount(); - SolrQuery monthQuery = new SolrQuery("*:*"); - monthQuery.setRows(ROWS_PER_FILE); - monthQuery.set("wt", "csv"); - monthQuery.set("fl", "*"); + SolrQuery monthQuery = new SolrQuery("*:*"); + monthQuery.setRows(ROWS_PER_FILE); + monthQuery.set("wt", "csv"); + monthQuery.set("fl", "*"); - monthQuery.addFilterQuery(timeField + ":[" +monthStart + " TO " + monthStart + "+1MONTH]"); + monthQuery.addFilterQuery(timeField + ":[" +monthStart + " TO " + monthStart + "+1MONTH]"); - for (int i = 0; i < docsThisMonth; i+= ROWS_PER_FILE) - { - monthQuery.setStart(i); - URL url = new URL(solrUrl + "/select?" + monthQuery.toString()); + for (int i = 0; i < docsThisMonth; i+= ROWS_PER_FILE) + { + monthQuery.setStart(i); + URL url = new URL(solrUrl + "/select?" + monthQuery.toString()); - File file = new File(toDir.getCanonicalPath(), makeExportFilename(indexName, monthStartDate, docsThisMonth, i)); - if (file.createNewFile()) - { - FileUtils.copyURLToFile(url, file); - log.info("Exported batch " + i + " to " + file.getCanonicalPath()); - } - else - { - throw new SolrImportExportException("Could not create file " + file.getCanonicalPath() - + " while exporting index " + indexName - + ", month" + monthStart - + ", batch " + i); - } - } - } - } + File file = new File(toDir.getCanonicalPath(), makeExportFilename(indexName, monthStartDate, docsThisMonth, i)); + if (file.createNewFile()) + { + FileUtils.copyURLToFile(url, file); + log.info("Exported batch " + i + " to " + file.getCanonicalPath()); + } + else + { + throw new SolrImportExportException("Could not create file " + file.getCanonicalPath() + + " while exporting index " + indexName + + ", month" + monthStart + + ", batch " + i); + } + } + } + } - /** - * Return a filter query that represents the export date range passed in as lastValue - * @param timeField the time field to use for the date range - * @param lastValue the requested date range, see options for acceptable values - * @return a filter query representing the date range, or null if no suitable date range can be created. - */ - private static String makeFilterQuery(String timeField, String lastValue) { - if ("m".equals(lastValue)) - { - // export data from the previous month - return timeField + ":[NOW/MONTH-1MONTH TO NOW/MONTH]"; - } + /** + * Return a filter query that represents the export date range passed in as lastValue + * @param timeField the time field to use for the date range + * @param lastValue the requested date range, see options for acceptable values + * @return a filter query representing the date range, or null if no suitable date range can be created. + */ + private static String makeFilterQuery(String timeField, String lastValue) { + if ("m".equals(lastValue)) + { + // export data from the previous month + return timeField + ":[NOW/MONTH-1MONTH TO NOW/MONTH]"; + } - int days; - if ("d".equals(lastValue)) - { - days = 1; - } - else - { - // other acceptable value: a number, specifying how many days back to export - days = Integer.valueOf(lastValue); // TODO check value? - } - return timeField + ":[NOW/DAY-" + days + "DAYS TO " + SOLR_DATE_FORMAT.get().format(new Date()) + "]"; - } + int days; + if ("d".equals(lastValue)) + { + days = 1; + } + else + { + // other acceptable value: a number, specifying how many days back to export + days = Integer.valueOf(lastValue); // TODO check value? + } + return timeField + ":[NOW/DAY-" + days + "DAYS TO " + SOLR_DATE_FORMAT.get().format(new Date()) + "]"; + } - /** - * Return the specified directory name or fall back to a default value. - * - * @param directoryValue a specific directory name. Optional. - * @return directoryValue if given as a non-blank string. A default directory otherwise. - */ - private static String makeDirectoryName(String directoryValue) - { - if (StringUtils.isNotBlank(directoryValue)) - { - return directoryValue; - } - return ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr-export" + File.separator; - } + /** + * Return the specified directory name or fall back to a default value. + * + * @param directoryValue a specific directory name. Optional. + * @return directoryValue if given as a non-blank string. A default directory otherwise. + */ + private static String makeDirectoryName(String directoryValue) + { + if (StringUtils.isNotBlank(directoryValue)) + { + return directoryValue; + } + return ConfigurationManager.getProperty("dspace.dir") + File.separator + "solr-export" + File.separator; + } - /** - * Creates a filename for the export batch. - * - * @param indexName The name of the index being exported. - * @param exportStart The start timestamp of the export - * @param totalRecords The total number of records in the export. - * @param index The index of the current batch. - * @return A file name that is appropriate to use for exporting the batch of data described by the parameters. - */ - private static String makeExportFilename(String indexName, Date exportStart, long totalRecords, int index) - { + /** + * Creates a filename for the export batch. + * + * @param indexName The name of the index being exported. + * @param exportStart The start timestamp of the export + * @param totalRecords The total number of records in the export. + * @param index The index of the current batch. + * @return A file name that is appropriate to use for exporting the batch of data described by the parameters. + */ + private static String makeExportFilename(String indexName, Date exportStart, long totalRecords, int index) + { String exportFileNumber = ""; - if (totalRecords > ROWS_PER_FILE) { - exportFileNumber = StringUtils.leftPad("" + (index / ROWS_PER_FILE), (int) Math.ceil(Math.log10(totalRecords / ROWS_PER_FILE)), "0"); - } - return indexName - + "_export_" - + EXPORT_DATE_FORMAT.get().format(exportStart) - + (StringUtils.isNotBlank(exportFileNumber) ? "_" + exportFileNumber : "") - + ".csv"; - } + if (totalRecords > ROWS_PER_FILE) { + exportFileNumber = StringUtils.leftPad("" + (index / ROWS_PER_FILE), (int) Math.ceil(Math.log10(totalRecords / ROWS_PER_FILE)), "0"); + } + return indexName + + "_export_" + + EXPORT_DATE_FORMAT.get().format(exportStart) + + (StringUtils.isNotBlank(exportFileNumber) ? "_" + exportFileNumber : "") + + ".csv"; + } - /** - * Returns the full URL for the specified index name. - * - * @param indexName the index name whose Solr URL is required. If the index name starts with - * "statistics" or is "authority", the Solr base URL will be looked up - * in the corresponding DSpace configuration file. Otherwise, it will fall back to a default. - * @return the full URL to the Solr index, as a String. - */ - private static String makeSolrUrl(String indexName) - { - if (indexName.startsWith("statistics")) - { - // TODO account for year shards properly? - return ConfigurationManager.getProperty("solr-statistics", "server") + indexName.replaceFirst("statistics", ""); - } - else if ("authority".equals(indexName)) - { - return ConfigurationManager.getProperty("solr.authority.server"); - } - return "http://localhost:8080/solr/" + indexName; // TODO better default? - } + /** + * Returns the full URL for the specified index name. + * + * @param indexName the index name whose Solr URL is required. If the index name starts with + * "statistics" or is "authority", the Solr base URL will be looked up + * in the corresponding DSpace configuration file. Otherwise, it will fall back to a default. + * @return the full URL to the Solr index, as a String. + */ + private static String makeSolrUrl(String indexName) + { + if (indexName.startsWith("statistics")) + { + // TODO account for year shards properly? + return ConfigurationManager.getProperty("solr-statistics", "server") + indexName.replaceFirst("statistics", ""); + } + else if ("authority".equals(indexName)) + { + return ConfigurationManager.getProperty("solr.authority.server"); + } + return "http://localhost:8080/solr/" + indexName; // TODO better default? + } - /** - * Returns a time field for the specified index name that is suitable for incremental export. - * - * @param indexName the index name whose Solr URL is required. - * @return the name of the time field, or null if no suitable field can be determined. - */ - private static String makeTimeField(String indexName) - { - if (indexName.startsWith("statistics")) - { - return "time"; - } - else if ("authority".equals(indexName)) - { - return "last_modified_date"; - } - return null; // TODO some sort of default? - } + /** + * Returns a time field for the specified index name that is suitable for incremental export. + * + * @param indexName the index name whose Solr URL is required. + * @return the name of the time field, or null if no suitable field can be determined. + */ + private static String makeTimeField(String indexName) + { + if (indexName.startsWith("statistics")) + { + return "time"; + } + else if ("authority".equals(indexName)) + { + return "last_modified_date"; + } + return null; // TODO some sort of default? + } - /** - * A utility method to print out all available command-line options and exit given the specified code. - * - * @param options the supported options. - * @param exitCode the exit code to use. The method will call System#exit(int) with the given code. - */ - private static void printHelpAndExit(Options options, int exitCode) - { - HelpFormatter myhelp = new HelpFormatter(); - myhelp.printHelp(SolrImportExport.class.getSimpleName() + "\n", options); - System.exit(exitCode); - } + /** + * A utility method to print out all available command-line options and exit given the specified code. + * + * @param options the supported options. + * @param exitCode the exit code to use. The method will call System#exit(int) with the given code. + */ + private static void printHelpAndExit(Options options, int exitCode) + { + HelpFormatter myhelp = new HelpFormatter(); + myhelp.printHelp(SolrImportExport.class.getSimpleName() + "\n", options); + System.exit(exitCode); + } } diff --git a/dspace-api/src/main/java/org/dspace/versioning/VersionHistory.java b/dspace-api/src/main/java/org/dspace/versioning/VersionHistory.java index c0fbc45c94..abdb92fe1f 100644 --- a/dspace-api/src/main/java/org/dspace/versioning/VersionHistory.java +++ b/dspace-api/src/main/java/org/dspace/versioning/VersionHistory.java @@ -61,6 +61,8 @@ public class VersionHistory implements ReloadableEntity { * To keep version number stables we keep information about deleted Versions. * {@code org.dspace.versioning.service.VersioningService#getVersionsByHistory(Context, VersionHistory) VersioningService#getVersionsByHistory} filters * such versions and returns only active versions. + * + * @return list of versions */ protected List getVersions() { return versions; @@ -104,8 +106,8 @@ public class VersionHistory implements ReloadableEntity { @Override public int hashCode() { - int hash=7; - hash=79*hash+ this.getID(); + int hash = 7; + hash = 79*hash + this.getID(); return hash; } diff --git a/dspace-api/src/main/java/org/dspace/versioning/dao/VersionDAO.java b/dspace-api/src/main/java/org/dspace/versioning/dao/VersionDAO.java index c8dfbfc2f0..c255fc2897 100644 --- a/dspace-api/src/main/java/org/dspace/versioning/dao/VersionDAO.java +++ b/dspace-api/src/main/java/org/dspace/versioning/dao/VersionDAO.java @@ -33,6 +33,14 @@ public interface VersionDAO extends GenericDAO * remove a version we set the item, date, summary and eperson null. This * method returns only versions that aren't soft deleted and have items * assigned. + * + * @param context + * The relevant DSpace Context. + * @param versionHistory + * version history + * @return all versions of an version history that have items assigned. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List findVersionsWithItems(Context context, VersionHistory versionHistory) throws SQLException; diff --git a/dspace-api/src/main/java/org/dspace/versioning/service/VersioningService.java b/dspace-api/src/main/java/org/dspace/versioning/service/VersioningService.java index 9939fe2dbc..8b60d4637c 100644 --- a/dspace-api/src/main/java/org/dspace/versioning/service/VersioningService.java +++ b/dspace-api/src/main/java/org/dspace/versioning/service/VersioningService.java @@ -34,7 +34,14 @@ public interface VersioningService { * To keep version numbers stable we do not delete versions, we do only set * the item, date, summary and eperson null. This methods returns only those * versions that have an item assigned. + * + * @param c + * The relevant DSpace Context. + * @param vh + * version history * @return All versions of a version history that have an item assigned. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ List getVersionsByHistory(Context c, VersionHistory vh) throws SQLException; diff --git a/dspace-api/src/main/java/org/dspace/workflow/WorkflowItemService.java b/dspace-api/src/main/java/org/dspace/workflow/WorkflowItemService.java index 3c9a8de9d1..9afd234521 100644 --- a/dspace-api/src/main/java/org/dspace/workflow/WorkflowItemService.java +++ b/dspace-api/src/main/java/org/dspace/workflow/WorkflowItemService.java @@ -33,19 +33,25 @@ public interface WorkflowItemService extends InProgressS * Get a workflow item from the database. * * @param context - * DSpace context object + * The relevant DSpace Context. * @param id - * ID of the workflow item + * ID of the workflow item * * @return the workflow item, or null if the ID is invalid. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public T find(Context context, int id) throws SQLException; /** * return all workflowitems * - * @param context active context + * @param context + * The relevant DSpace Context. + * * @return List of all workflowItems in system + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List findAll(Context context) throws SQLException; @@ -53,11 +59,13 @@ public interface WorkflowItemService extends InProgressS * Get all workflow items for a particular collection. * * @param context - * the context object + * The relevant DSpace Context. * @param collection - * the collection + * the collection * * @return array of the corresponding workflow items + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List findByCollection(Context context, Collection collection) throws SQLException; @@ -66,11 +74,13 @@ public interface WorkflowItemService extends InProgressS * If so, its WorkflowItem is returned. If not, null is returned * * @param context - * the context object + * The relevant DSpace Context. * @param item - * the item + * the item * * @return workflow item corresponding to the item, or null + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public T findByItem(Context context, Item item) throws SQLException; @@ -79,17 +89,50 @@ public interface WorkflowItemService extends InProgressS * e-person. * * @param context - * the context object + * The relevant DSpace Context. * @param ep - * the eperson + * the eperson * * @return the corresponding workflow items + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List findBySubmitter(Context context, EPerson ep) throws SQLException; + /** + * Delete all workflow items present in the specified collection. + * + * @param context + * The relevant DSpace Context. + * @param collection + * the containing collection + * + * @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 deleteByCollection(Context context, Collection collection) throws SQLException, IOException, AuthorizeException; - + /** + * Delete the specified workflow item. + * + * @param context + * The relevant DSpace Context. + * @param workflowItem + * which workflow item to delete + * + * @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 delete(Context context, T workflowItem) throws SQLException, AuthorizeException, IOException; } diff --git a/dspace-api/src/main/java/org/dspace/workflow/WorkflowService.java b/dspace-api/src/main/java/org/dspace/workflow/WorkflowService.java index 6ad5779a5b..9068e15325 100644 --- a/dspace-api/src/main/java/org/dspace/workflow/WorkflowService.java +++ b/dspace-api/src/main/java/org/dspace/workflow/WorkflowService.java @@ -26,6 +26,7 @@ import java.util.List; * are required to have. * * @author kevinvandevelde at atmire.com + * @param some implementation of workflow item. */ public interface WorkflowService { @@ -36,10 +37,18 @@ public interface WorkflowService { * the PersonalWorkspace entry and turn it into a WorkflowItem. * * @param context - * Context + * The relevant DSpace Context. * @param wsi - * The WorkspaceItem to convert to a workflow item + * The WorkspaceItem to convert to a workflow item * @return The resulting workflow item + * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws WorkflowException if workflow error */ public T start(Context context, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException, WorkflowException; @@ -47,6 +56,20 @@ public interface WorkflowService { * startWithoutNotify() starts the workflow normally, but disables * notifications (useful for large imports,) for the first workflow step - * subsequent notifications happen normally + * + * @param c + * The relevant DSpace Context. + * @param wsi + * workspace item + * @return the resulting workflow item. + * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws WorkflowException if workflow error */ public T startWithoutNotify(Context c, WorkspaceItem wsi) throws SQLException, AuthorizeException, IOException, WorkflowException; @@ -58,11 +81,19 @@ public interface WorkflowService { * the user's PersonalWorkspace * * @param c - * Context + * The relevant DSpace Context. * @param wi - * WorkflowItem to operate on + * WorkflowItem to operate on * @param e - * EPerson doing the operation + * EPerson doing the operation + * @return workspace item returned to workspace + * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public WorkspaceItem abort(Context c, T wi, EPerson e) throws SQLException, AuthorizeException, IOException; diff --git a/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java b/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java index 46229e49ef..e94a5c504c 100644 --- a/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java @@ -100,7 +100,7 @@ public class BasicWorkflowServiceImpl implements BasicWorkflowService @Override public void addInitialWorkspaceItemPolicies(Context context, WorkspaceItem workspaceItem) throws SQLException, AuthorizeException { - // Now create the policies for the submitter and workflow + // Now create the policies for the submitter and workflow // users to modify item and contents // contents = bitstreams, bundles // FIXME: icky hardcoded workflow steps @@ -639,7 +639,18 @@ public class BasicWorkflowServiceImpl implements BasicWorkflowService * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. * + * @param context + * The relevant DSpace Context. + * @param workflowItem + * which workflow item to archive * @return the fully archived item. + * @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 Item archive(Context context, BasicWorkflowItem workflowItem) @@ -664,6 +675,17 @@ public class BasicWorkflowServiceImpl implements BasicWorkflowService /** * notify the submitter that the item is archived + * + * @param context + * The relevant DSpace Context. + * @param item + * which item was archived + * @param coll + * collection name to display in template + * @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. */ protected void notifyOfArchive(Context context, Item item, Collection coll) throws SQLException, IOException @@ -717,6 +739,13 @@ public class BasicWorkflowServiceImpl implements BasicWorkflowService * @param wfi * WorkflowItem to be 'dismantled' * @return the workspace item + * @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 AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ protected WorkspaceItem returnToWorkspace(Context c, BasicWorkflowItem wfi) throws SQLException, IOException, AuthorizeException @@ -1087,20 +1116,20 @@ public class BasicWorkflowServiceImpl implements BasicWorkflowService if (roleGroup == null) roleGroup = collectionService.createWorkflowGroup(context, collection, 1); - } - else if ("WF_STEP2".equals(roleName)) - { + } + else if ("WF_STEP2".equals(roleName)) + { roleGroup = collection.getWorkflowStep2(); if (roleGroup == null) roleGroup = collectionService.createWorkflowGroup(context, collection, 2); } - else if ("WF_STEP3".equals(roleName)) - { + else if ("WF_STEP3".equals(roleName)) + { roleGroup = collection.getWorkflowStep3(); if (roleGroup == null) roleGroup = collectionService.createWorkflowGroup(context, collection, 3); - } + } return roleGroup; } diff --git a/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowItemService.java b/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowItemService.java index 26520e8c39..2ae77efc0a 100644 --- a/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowItemService.java +++ b/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowItemService.java @@ -28,10 +28,13 @@ public interface BasicWorkflowItemService extends WorkflowItemService findByOwner(Context context, EPerson ePerson) throws SQLException; diff --git a/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowService.java b/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowService.java index 04acc1ff52..f26af1a893 100644 --- a/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowService.java +++ b/dspace-api/src/main/java/org/dspace/workflowbasic/service/BasicWorkflowService.java @@ -84,8 +84,13 @@ public interface BasicWorkflowService extends WorkflowService * claimed and owned by an EPerson. The GUI displays this info on the * MyDSpace page. * + * @param context + * The relevant DSpace Context. * @param e - * The EPerson we want to fetch owned tasks for. + * The EPerson we want to fetch owned tasks for. + * @return list of basic workflow items + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List getOwnedTasks(Context context, EPerson e) throws java.sql.SQLException; @@ -94,18 +99,32 @@ public interface BasicWorkflowService extends WorkflowService * getPooledTasks() returns a List of WorkflowItems an EPerson could claim * (as a reviewer, etc.) for display on a user's MyDSpace page. * + * @param context + * The relevant DSpace Context. * @param e - * The Eperson we want to fetch the pooled tasks for. + * The Eperson we want to fetch the pooled tasks for. + * @return list of basic workflow items + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List getPooledTasks(Context context, EPerson e) throws SQLException; /** * claim() claims a workflow task for an EPerson * + * @param context + * The relevant DSpace Context. * @param workflowItem - * WorkflowItem to do the claim on + * WorkflowItem to do the claim on * @param e - * The EPerson doing the claim + * The EPerson doing the claim + * @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 AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ public void claim(Context context, BasicWorkflowItem workflowItem, EPerson e) throws SQLException, IOException, AuthorizeException; @@ -119,11 +138,18 @@ public interface BasicWorkflowService extends WorkflowService * submitter of a successful submission * * @param context - * Context + * The relevant DSpace Context. * @param workflowItem - * WorkflowItem do do the approval on + * WorkflowItem do do the approval on * @param e - * EPerson doing the approval + * EPerson doing the approval + * @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 AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ public void advance(Context context, BasicWorkflowItem workflowItem, EPerson e) throws SQLException, IOException, AuthorizeException; @@ -136,17 +162,23 @@ public interface BasicWorkflowService extends WorkflowService * submitter of a successful submission * * @param context - * Context + * The relevant DSpace Context. * @param workflowItem - * WorkflowItem do do the approval on + * WorkflowItem do do the approval on * @param e - * EPerson doing the approval - * + * EPerson doing the approval * @param curate - * boolean indicating whether curation tasks should be done - * + * boolean indicating whether curation tasks should be done * @param record - * boolean indicating whether to record action + * boolean indicating whether to record action + * @return true if the item was successfully archived + * @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 AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ public boolean advance(Context context, BasicWorkflowItem workflowItem, EPerson e, boolean curate, boolean record) @@ -161,6 +193,13 @@ public interface BasicWorkflowService extends WorkflowService * WorkflowItem to operate on * @param e * EPerson doing the operation + * @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 AuthorizeException + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ public void unclaim(Context context, BasicWorkflowItem workflowItem, EPerson e) throws SQLException, IOException, AuthorizeException; @@ -182,6 +221,9 @@ public interface BasicWorkflowService extends WorkflowService * get the title of the item in this workflow * * @param wi the workflow item object + * @return item title + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public String getItemTitle(BasicWorkflowItem wi) throws SQLException; @@ -189,6 +231,9 @@ public interface BasicWorkflowService extends WorkflowService * get the name of the eperson who started this workflow * * @param wi the workflow item + * @return submitter's name + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public String getSubmitterName(BasicWorkflowItem wi) throws SQLException; } diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java index 55ea7ba3be..f2a02ca5fa 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java @@ -116,7 +116,7 @@ public class WorkflowUtils extends Util{ * it can be called after a forward safely. * * @param request - * the HTTP request + * Servlet's HTTP request object. */ public static void storeOriginalURL(HttpServletRequest request) { @@ -206,20 +206,52 @@ public class WorkflowUtils extends Util{ * WORKFLOW ROLE MANAGEMENT **************************************/ - /* + /** * Creates a role for a collection by linking a group of epersons to a role ID + * + * @param context + * The relevant DSpace Context. + * @param collection + * the target collection + * @param roleId + * the role to be linked. + * @param group + * group of EPersons + * @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 static void createCollectionWorkflowRole(Context context, Collection collection, String roleId, Group group) throws AuthorizeException, SQLException { + public static void createCollectionWorkflowRole(Context context, Collection collection, String roleId, Group group) + throws AuthorizeException, SQLException + { CollectionRole ass = collectionRoleService.create(context, collection, roleId, group); collectionRoleService.update(context, ass); } + /* * Deletes a role group linked to a given role and a collection + * + * @param context + * The relevant DSpace Context. + * @param collection + * + * @param roleId + * + * @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 WorkflowConfigurationException + * occurs if there is a configuration error in the workflow */ - public static void deleteRoleGroup(Context context, Collection collection, String roleID) throws SQLException, IOException, WorkflowConfigurationException { + public static void deleteRoleGroup(Context context, Collection collection, String roleID) + throws SQLException, IOException, WorkflowConfigurationException + { Workflow workflow = xmlWorkflowFactory.getWorkflow(collection); Role role = workflow.getRoles().get(roleID); - if(role.getScope() == Role.Scope.COLLECTION){ + if (role.getScope() == Role.Scope.COLLECTION) { CollectionRole ass = collectionRoleService.find(context, collection, roleID); collectionRoleService.delete(context, ass); } @@ -229,14 +261,14 @@ public class WorkflowUtils extends Util{ public static HashMap getCollectionRoles(Collection thisCollection) throws IOException, WorkflowConfigurationException, SQLException { Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection); LinkedHashMap result = new LinkedHashMap(); - if(workflow != null){ + if (workflow != null) { //Make sure we find one HashMap allRoles = workflow.getRoles(); //We have retrieved all our roles, not get the ones which can be configured by the collection - for(String roleId : allRoles.keySet()){ + for (String roleId : allRoles.keySet()) { Role role = allRoles.get(roleId); // We just require the roles which have a scope of collection - if(role.getScope() == Role.Scope.COLLECTION && !role.isInternal()){ + if (role.getScope() == Role.Scope.COLLECTION && !role.isInternal()) { result.put(roleId, role); } } @@ -249,14 +281,14 @@ public class WorkflowUtils extends Util{ public static HashMap getCollectionAndRepositoryRoles(Collection thisCollection) throws IOException, WorkflowConfigurationException, SQLException { Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection); LinkedHashMap result = new LinkedHashMap(); - if(workflow != null){ + if (workflow != null) { //Make sure we find one HashMap allRoles = workflow.getRoles(); //We have retrieved all our roles, not get the ones which can be configured by the collection - for(String roleId : allRoles.keySet()){ + for (String roleId : allRoles.keySet()) { Role role = allRoles.get(roleId); // We just require the roles which have a scope of collection - if((role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY) && !role.isInternal()){ + if ((role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY) && !role.isInternal()) { result.put(roleId, role); } } @@ -269,14 +301,14 @@ public class WorkflowUtils extends Util{ public static HashMap getAllExternalRoles(Collection thisCollection) throws IOException, WorkflowConfigurationException, SQLException { Workflow workflow = xmlWorkflowFactory.getWorkflow(thisCollection); LinkedHashMap result = new LinkedHashMap(); - if(workflow != null){ + if (workflow != null) { //Make sure we find one HashMap allRoles = workflow.getRoles(); //We have retrieved all our roles, not get the ones which can be configured by the collection - for(String roleId : allRoles.keySet()){ + for (String roleId : allRoles.keySet()) { Role role = allRoles.get(roleId); // We just require the roles which have a scope of collection - if(!role.isInternal()){ + if (!role.isInternal()) { result.put(roleId, role); } } @@ -286,26 +318,26 @@ public class WorkflowUtils extends Util{ } public static Group getRoleGroup(Context context, Collection collection, Role role) throws SQLException { - if(role.getScope() == Role.Scope.REPOSITORY){ + if (role.getScope() == Role.Scope.REPOSITORY) { return groupService.findByName(context, role.getName()); - }else - if(role.getScope() == Role.Scope.COLLECTION){ - CollectionRole collectionRole = collectionRoleService.find(context, collection, role.getId()); - if(collectionRole == null) - return null; + } else + if (role.getScope() == Role.Scope.COLLECTION) { + CollectionRole collectionRole = collectionRoleService.find(context, collection, role.getId()); + if (collectionRole == null) + return null; - return collectionRole.getGroup(); - }else - if(role.getScope() == Role.Scope.ITEM){ + return collectionRole.getGroup(); + } else + if (role.getScope() == Role.Scope.ITEM) { - } + } return null; } // public static List getAllUsedStepIdentifiers(Context context) throws SQLException { // TableRowIterator tri = DatabaseManager.queryTable(context, "cwf_claimtask", "SELECT DISTINCT step_id FROM cwf_pooltask UNION SELECT DISTINCT step_id FROM cwf_claimtask"); // List result = new ArrayList(); -// while(tri.hasNext()){ +// while(tri.hasNext()) { // TableRow row = tri.next(); // result.add(row.getStringColumn("step_id")); // } diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java index 8dca275979..41e2bbfc6a 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java @@ -106,15 +106,15 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { @Override public List getEPersonDeleteConstraints(Context context, EPerson ePerson) throws SQLException { List constraints = new ArrayList(); - if(CollectionUtils.isNotEmpty(claimedTaskService.findByEperson(context, ePerson))) + if (CollectionUtils.isNotEmpty(claimedTaskService.findByEperson(context, ePerson))) { constraints.add("cwf_claimtask"); } - if(CollectionUtils.isNotEmpty(poolTaskService.findByEPerson(context, ePerson))) + if (CollectionUtils.isNotEmpty(poolTaskService.findByEPerson(context, ePerson))) { constraints.add("cwf_pooltask"); } - if(CollectionUtils.isNotEmpty(workflowItemRoleService.findByEPerson(context, ePerson))) + if (CollectionUtils.isNotEmpty(workflowItemRoleService.findByEPerson(context, ePerson))) { constraints.add("cwf_workflowitemrole"); } @@ -125,12 +125,12 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { public Group getWorkflowRoleGroup(Context context, Collection collection, String roleName, Group roleGroup) throws SQLException, IOException, WorkflowException, AuthorizeException { try { Role role = WorkflowUtils.getCollectionAndRepositoryRoles(collection).get(roleName); - if(role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY){ + if (role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY){ roleGroup = WorkflowUtils.getRoleGroup(context, collection, role); - if(roleGroup == null){ + if (roleGroup == null){ authorizeService.authorizeAction(context, collection, Constants.WRITE); roleGroup = groupService.create(context); - if(role.getScope() == Role.Scope.COLLECTION){ + if (role.getScope() == Role.Scope.COLLECTION){ groupService.setName(roleGroup, "COLLECTION_" + collection.getID().toString() + "_WORKFLOW_ROLE_" + roleName); @@ -139,7 +139,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { } groupService.update(context, roleGroup); authorizeService.addPolicy(context, collection, Constants.ADD, roleGroup); - if(role.getScope() == Role.Scope.COLLECTION){ + if (role.getScope() == Role.Scope.COLLECTION){ WorkflowUtils.createCollectionWorkflowRole(context, collection, roleName, roleGroup); } } @@ -172,12 +172,12 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { context.turnOffAuthorisationSystem(); Step firstStep = wf.getFirstStep(); - if(firstStep.isValidStep(context, wfi)){ + if (firstStep.isValidStep(context, wfi)){ activateFirstStep(context, wf, firstStep, wfi); } else { //Get our next step, if none is found, archive our item firstStep = wf.getNextStep(context, wfi, firstStep, ActionResult.OUTCOME_COMPLETE); - if(firstStep == null){ + if (firstStep == null){ archive(context, wfi); }else{ activateFirstStep(context, wf, firstStep, wfi); @@ -233,13 +233,13 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { List itempols = authorizeService.getPolicies(context, item); EPerson submitter = item.getSubmitter(); for (ResourcePolicy resourcePolicy : itempols) { - if(submitter.equals(resourcePolicy.getEPerson())){ + if (submitter.equals(resourcePolicy.getEPerson())){ //The user has already got this policy so add it to the list userHasPolicies.add(resourcePolicy.getAction()); } } //Make sure we don't add duplicate policies - if(!userHasPolicies.contains(Constants.READ)) + if (!userHasPolicies.contains(Constants.READ)) addPolicyToItem(context, item, Constants.READ, submitter); } @@ -258,7 +258,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { logWorkflowEvent(context, firstStep.getWorkflow().getID(), null, null, wfi, null, firstStep, firstActionConfig); //If we don't have a UI activate it - if(!firstActionConfig.requiresUI()){ + if (!firstActionConfig.requiresUI()){ ActionResult outcome = firstActionConfig.getProcessingAction().execute(context, wfi, firstStep, null); processOutcome(context, null, wf, firstStep, firstActionConfig, outcome, wfi, true); } @@ -272,7 +272,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { try { XmlWorkflowItem wi = xmlWorkflowItemService.find(c, workflowItemId); Step currentStep = currentActionConfig.getStep(); - if(currentActionConfig.getProcessingAction().isAuthorized(c, request, wi)){ + if (currentActionConfig.getProcessingAction().isAuthorized(c, request, wi)){ ActionResult outcome = currentActionConfig.getProcessingAction().execute(c, wi, currentStep, request); return processOutcome(c, user, workflow, currentStep, currentActionConfig, outcome, wi, false); }else{ @@ -287,12 +287,12 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { @Override public WorkflowActionConfig processOutcome(Context c, EPerson user, Workflow workflow, Step currentStep, WorkflowActionConfig currentActionConfig, ActionResult currentOutcome, XmlWorkflowItem wfi, boolean enteredNewStep) throws IOException, AuthorizeException, SQLException, WorkflowException { - if(currentOutcome.getType() == ActionResult.TYPE.TYPE_PAGE || currentOutcome.getType() == ActionResult.TYPE.TYPE_ERROR){ + if (currentOutcome.getType() == ActionResult.TYPE.TYPE_PAGE || currentOutcome.getType() == ActionResult.TYPE.TYPE_ERROR){ //Our outcome is a page or an error, so return our current action c.restoreAuthSystemState(); return currentActionConfig; }else - if(currentOutcome.getType() == ActionResult.TYPE.TYPE_CANCEL || currentOutcome.getType() == ActionResult.TYPE.TYPE_SUBMISSION_PAGE){ + if (currentOutcome.getType() == ActionResult.TYPE.TYPE_CANCEL || currentOutcome.getType() == ActionResult.TYPE.TYPE_SUBMISSION_PAGE){ //We either pressed the cancel button or got an order to return to the submission page, so don't return an action //By not returning an action we ensure ourselfs that we go back to the submission page c.restoreAuthSystemState(); @@ -303,7 +303,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { WorkflowActionConfig nextActionConfig = null; try { //We have completed our action search & retrieve the next action - if(currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE){ + if (currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE){ nextActionConfig = currentStep.getNextAction(currentActionConfig); } @@ -314,7 +314,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { if (nextActionConfig.requiresUI() && !enteredNewStep) { createOwnedTask(c, wfi, currentStep, nextActionConfig, user); return nextActionConfig; - } else if( nextActionConfig.requiresUI() && enteredNewStep){ + } else if ( nextActionConfig.requiresUI() && enteredNewStep){ //We have entered a new step and have encountered a UI, return null since the current user doesn't have anything to do with this c.restoreAuthSystemState(); return null; @@ -323,13 +323,13 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { return processOutcome(c, user, workflow, currentStep, nextActionConfig, newOutcome, wfi, enteredNewStep); } }else - if(enteredNewStep){ + if (enteredNewStep){ // If the user finished his/her step, we keep processing until there is a UI step action or no step at all nextStep = workflow.getNextStep(c, wfi, currentStep, currentOutcome.getResult()); c.turnOffAuthorisationSystem(); nextActionConfig = processNextStep(c, user, workflow, currentOutcome, wfi, nextStep); //If we require a user interface return null so that the user is redirected to the "submissions page" - if(nextActionConfig == null || nextActionConfig.requiresUI()){ + if (nextActionConfig == null || nextActionConfig.requiresUI()){ return null; }else{ return nextActionConfig; @@ -342,7 +342,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { workflowRequirementsService.addFinishedUser(c, wfi, user); c.turnOffAuthorisationSystem(); //Check if our requirements have been met - if((currentStep.isFinished(c, wfi) && currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE) || currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ + if ((currentStep.isFinished(c, wfi) && currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE) || currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ //Delete all the table rows containing the users who performed this task workflowRequirementsService.clearInProgressUsers(c, wfi); //Remove all the tasks @@ -353,7 +353,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { nextActionConfig = processNextStep(c, user, workflow, currentOutcome, wfi, nextStep); //If we require a user interface return null so that the user is redirected to the "submissions page" - if(nextActionConfig == null || nextActionConfig.requiresUI()){ + if (nextActionConfig == null || nextActionConfig.requiresUI()){ return null; }else{ return nextActionConfig; @@ -372,7 +372,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { e.printStackTrace(); } finally { - if((nextStep != null && currentStep != null && nextActionConfig != null) || (wfi.getItem().isArchived() && currentStep != null)){ + if ((nextStep != null && currentStep != null && nextActionConfig != null) || (wfi.getItem().isArchived() && currentStep != null)){ logWorkflowEvent(c, currentStep.getWorkflow().getID(), currentStep.getId(), currentActionConfig.getId(), wfi, user, nextStep, nextActionConfig); } } @@ -393,14 +393,14 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { List currentEpersonOwners = new ArrayList(); List currentGroupOwners = new ArrayList(); //These are only null if our item is sent back to the submission - if(newStep != null && newActionConfig != null){ + if (newStep != null && newActionConfig != null){ workflowStepString = workflowId + "." + newStep.getId() + "." + newActionConfig.getId(); //Retrieve the current owners of the task List claimedTasks = claimedTaskService.find(c, wfi, newStep.getId()); List pooledTasks = poolTaskService.find(c, wfi); for (PoolTask poolTask : pooledTasks){ - if(poolTask.getEperson() != null){ + if (poolTask.getEperson() != null){ currentEpersonOwners.add(poolTask.getEperson()); }else{ currentGroupOwners.add(poolTask.getGroup()); @@ -411,7 +411,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { } } String previousWorkflowStepString = null; - if(previousStepId != null && previousActionConfigId != null){ + if (previousStepId != null && previousActionConfigId != null){ previousWorkflowStepString = workflowId + "." + previousStepId + "." + previousActionConfigId; } @@ -430,7 +430,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { protected WorkflowActionConfig processNextStep(Context c, EPerson user, Workflow workflow, ActionResult currentOutcome, XmlWorkflowItem wfi, Step nextStep) throws SQLException, IOException, AuthorizeException, WorkflowException, WorkflowConfigurationException { WorkflowActionConfig nextActionConfig; - if(nextStep!=null){ + if (nextStep!=null){ nextActionConfig = nextStep.getUserSelectionMethod(); nextActionConfig.getProcessingAction().activate(c, wfi); // nextActionConfig.getProcessingAction().generateTasks(); @@ -445,7 +445,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { return processOutcome(c, user, workflow, nextStep, nextActionConfig, newOutcome, wfi, true); } }else{ - if(currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ + if (currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE){ c.restoreAuthSystemState(); throw new WorkflowException("No alternate step was found for outcome: " + currentOutcome.getResult()); } @@ -461,7 +461,18 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { * with the relevant collection, added to the search index, and any other * tasks such as assigning dates are performed. * + * @param context + * The relevant DSpace Context. + * @param wfi + * workflow item * @return the fully archived item. + * @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 Item archive(Context context, XmlWorkflowItem wfi) @@ -495,6 +506,17 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { /** * notify the submitter that the item is archived + * + * @param context + * The relevant DSpace Context. + * @param item + * which item was archived + * @param coll + * collection name to display in template + * @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. */ protected void notifyOfArchive(Context context, Item item, Collection coll) throws SQLException, IOException { @@ -540,9 +562,12 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { /** * Deletes all tasks from this workflowflowitem * @param context the dspace context - * @param wi the workflow item for whom we are to delete the tasks - * @throws SQLException ... - * @throws org.dspace.authorize.AuthorizeException ... + * @param wi the workflow item for which we are to delete the tasks + * @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 deleteAllTasks(Context context, XmlWorkflowItem wi) throws SQLException, AuthorizeException { @@ -571,8 +596,8 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { */ @Override public void deletePooledTask(Context context, XmlWorkflowItem wi, PoolTask task) throws SQLException, AuthorizeException { - if(task != null){ - if(task.getEperson() != null){ + if (task != null){ + if (task.getEperson() != null){ removeUserItemPolicies(context, wi.getItem(), task.getEperson()); }else{ removeGroupItemPolicies(context, wi.getItem(), task.getGroup()); @@ -583,7 +608,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { @Override public void deleteClaimedTask(Context c, XmlWorkflowItem wi, ClaimedTask task) throws SQLException, AuthorizeException { - if(task != null){ + if (task != null){ removeUserItemPolicies(c, wi.getItem(), task.getOwner()); claimedTaskService.delete(c, task); } @@ -637,58 +662,58 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { } protected void grantUserAllItemPolicies(Context context, Item item, EPerson epa) throws AuthorizeException, SQLException { - if(epa != null){ + if (epa != null){ //A list of policies the user has for this item List userHasPolicies = new ArrayList(); List itempols = authorizeService.getPolicies(context, item); for (ResourcePolicy resourcePolicy : itempols) { - if(epa.equals(resourcePolicy.getEPerson())){ + if (epa.equals(resourcePolicy.getEPerson())){ //The user has already got this policy so it it to the list userHasPolicies.add(resourcePolicy.getAction()); } } //Make sure we don't add duplicate policies - if(!userHasPolicies.contains(Constants.READ)) + if (!userHasPolicies.contains(Constants.READ)) addPolicyToItem(context, item, Constants.READ, epa); - if(!userHasPolicies.contains(Constants.WRITE)) + if (!userHasPolicies.contains(Constants.WRITE)) addPolicyToItem(context, item, Constants.WRITE, epa); - if(!userHasPolicies.contains(Constants.DELETE)) + if (!userHasPolicies.contains(Constants.DELETE)) addPolicyToItem(context, item, Constants.DELETE, epa); - if(!userHasPolicies.contains(Constants.ADD)) + if (!userHasPolicies.contains(Constants.ADD)) addPolicyToItem(context, item, Constants.ADD, epa); - if(!userHasPolicies.contains(Constants.REMOVE)) + if (!userHasPolicies.contains(Constants.REMOVE)) addPolicyToItem(context, item, Constants.REMOVE, epa); } } protected void grantGroupAllItemPolicies(Context context, Item item, Group group) throws AuthorizeException, SQLException { - if(group != null){ + if (group != null){ //A list of policies the user has for this item List groupHasPolicies = new ArrayList(); List itempols = authorizeService.getPolicies(context, item); for (ResourcePolicy resourcePolicy : itempols) { - if(group.equals(resourcePolicy.getGroup())){ + if (group.equals(resourcePolicy.getGroup())){ //The user has already got this policy so it it to the list groupHasPolicies.add(resourcePolicy.getAction()); } } //Make sure we don't add duplicate policies - if(!groupHasPolicies.contains(Constants.READ)) + if (!groupHasPolicies.contains(Constants.READ)) addGroupPolicyToItem(context, item, Constants.READ, group); - if(!groupHasPolicies.contains(Constants.WRITE)) + if (!groupHasPolicies.contains(Constants.WRITE)) addGroupPolicyToItem(context, item, Constants.WRITE, group); - if(!groupHasPolicies.contains(Constants.DELETE)) + if (!groupHasPolicies.contains(Constants.DELETE)) addGroupPolicyToItem(context, item, Constants.DELETE, group); - if(!groupHasPolicies.contains(Constants.ADD)) + if (!groupHasPolicies.contains(Constants.ADD)) addGroupPolicyToItem(context, item, Constants.ADD, group); - if(!groupHasPolicies.contains(Constants.REMOVE)) + if (!groupHasPolicies.contains(Constants.REMOVE)) addGroupPolicyToItem(context, item, Constants.REMOVE, group); } } protected void addPolicyToItem(Context context, Item item, int type, EPerson epa) throws AuthorizeException, SQLException { - if(epa != null){ + if (epa != null){ authorizeService.addPolicy(context, item, type, epa); List bundles = item.getBundles(); for (Bundle bundle : bundles) { @@ -701,7 +726,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { } } protected void addGroupPolicyToItem(Context context, Item item, int type, Group group) throws AuthorizeException, SQLException { - if(group != null){ + if (group != null){ authorizeService.addPolicy(context, item, type, group); List bundles = item.getBundles(); for (Bundle bundle : bundles) { @@ -715,7 +740,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { } protected void removeUserItemPolicies(Context context, Item item, EPerson e) throws SQLException, AuthorizeException { - if(e != null){ + if (e != null){ //Also remove any lingering authorizations from this user authorizeService.removeEPersonPolicies(context, item, e); //Remove the bundle rights @@ -728,7 +753,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { } } // Ensure that the submitter always retains his resource policies - if(e.getID().equals(item.getSubmitter().getID())){ + if (e.getID().equals(item.getSubmitter().getID())){ grantSubmitterReadPolicies(context, item); } } @@ -736,7 +761,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { protected void removeGroupItemPolicies(Context context, Item item, Group e) throws SQLException, AuthorizeException { - if(e != null){ + if (e != null){ //Also remove any lingering authorizations from this user authorizeService.removeGroupPolicies(context, item, e); //Remove the bundle rights @@ -761,7 +786,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService { String currentStepId = null; String currentActionConfigId = null; ClaimedTask claimedTask = claimedTaskService.findByWorkflowIdAndEPerson(context, wi, e); - if(claimedTask != null){ + if (claimedTask != null){ //Log it workflowID = claimedTask.getWorkflowID(); currentStepId = claimedTask.getStepID(); diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Step.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Step.java index 70d7d6e4fe..b1c8bba5d4 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Step.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Step.java @@ -47,7 +47,7 @@ public class Step { private Workflow workflow; private int requiredUsers; - public Step(String id, Workflow workflow, Role role, UserSelectionActionConfig userSelectionMethod, List actionConfigsList, Map outcomes, int requiredUsers){ + public Step(String id, Workflow workflow, Role role, UserSelectionActionConfig userSelectionMethod, List actionConfigsList, Map outcomes, int requiredUsers) { this.actionConfigsMap = new HashMap<>(); this.outcomes = outcomes; this.userSelectionMethod = userSelectionMethod; @@ -61,9 +61,9 @@ public class Step { } public WorkflowActionConfig getActionConfig(String actionID) { - if(actionConfigsMap.get(actionID)!=null){ + if (actionConfigsMap.get(actionID)!=null) { return actionConfigsMap.get(actionID); - }else{ + } else { WorkflowActionConfig action = xmlWorkflowFactory.createWorkflowActionConfig(actionID); action.setStep(this); actionConfigsMap.put(actionID, action); @@ -75,7 +75,7 @@ public class Step { * Boolean that returns whether or not the actions in this step have a ui * @return a boolean */ - public boolean hasUI(){ + public boolean hasUI() { for (String actionConfigId : actionConfigsList) { WorkflowActionConfig actionConfig = getActionConfig(actionConfigId); if (actionConfig.requiresUI()) { @@ -102,9 +102,9 @@ public class Step { public WorkflowActionConfig getNextAction(WorkflowActionConfig currentAction) { int index = actionConfigsList.indexOf(currentAction.getId()); - if(index < actionConfigsList.size()-1){ + if (index < actionConfigsList.size()-1) { return getActionConfig(actionConfigsList.get(index+1)); - }else{ + } else { return null; } } @@ -120,14 +120,19 @@ public class Step { /** * Check if enough users have finished this step for it to continue - * @param wfi the workflow item to check + * @param c + * The relevant DSpace Context. + * @param wfi + * the workflow item to check * @return if enough users have finished this task + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public boolean isFinished(Context c, XmlWorkflowItem wfi) throws SQLException { return inProgressUserService.getNumberOfFinishedUsers(c, wfi) == requiredUsers; } - public int getRequiredUsers(){ + public int getRequiredUsers() { return requiredUsers; } @@ -135,6 +140,6 @@ public class Step { return role; } -// public boolean skipStep(){ +// public boolean skipStep() { // } } diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Workflow.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Workflow.java index e357542feb..99094aaa39 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Workflow.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/Workflow.java @@ -21,7 +21,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; /** - * Class that contains all the steps & roles involved in a certain + * Class that contains all the steps and roles involved in a certain * configured workflow * * @author Bram De Schouwer (bram.deschouwer at dot com) @@ -49,7 +49,7 @@ public class Workflow { return firstStep; } - public String getID(){ + public String getID() { return id; } @@ -57,11 +57,11 @@ public class Workflow { * Return a step with a given id */ public Step getStep(String stepID) throws WorkflowConfigurationException, IOException { - if(steps.get(id)!=null){ + if (steps.get(id)!=null) { return steps.get(id); - }else{ + } else { Step step = xmlWorkflowFactory.createStep(this, stepID); - if(step== null){ + if (step== null){ throw new WorkflowConfigurationException("Step definition not found for: "+stepID); } steps.put(stepID, step); @@ -71,11 +71,11 @@ public class Workflow { public Step getNextStep(Context context, XmlWorkflowItem wfi, Step currentStep, int outcome) throws IOException, WorkflowConfigurationException, WorkflowException, SQLException { String nextStepID = currentStep.getNextStepID(outcome); - if(nextStepID != null){ + if (nextStepID != null) { Step nextStep = getStep(nextStepID); - if(nextStep == null) + if (nextStep == null) throw new WorkflowException("Error while processing outcome, the following action was undefined: " + nextStepID); - if(nextStep.isValidStep(context, wfi)){ + if (nextStep.isValidStep(context, wfi)) { return nextStep; } else { return getNextStep(context, wfi, nextStep, 0); diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java index 71db0ae178..ef6a94df01 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java @@ -24,7 +24,7 @@ import java.util.List; /** * This abstract class represents an api action * Each step in the xml workflow consists of a number of actions - * this abstract action contains some utility methods & the methods + * this abstract action contains some utility methods and the methods * that each of these actions must implement including: * activating, execution, ... * diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/ActionResult.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/ActionResult.java index cc2c3c5e4b..8582d7da60 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/ActionResult.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/ActionResult.java @@ -9,8 +9,8 @@ package org.dspace.xmlworkflow.state.actions; /** * A class that represent the result of an action - * The result consists of 2 parts a type & and a result - * The type is represented by an enum & can either be something like + * The result consists of 2 parts a type and a result + * The type is represented by an enum and can either be something like * TYPE_OUTCOME: we have a certain outcome so move to another action/step * TYPE_ERROR: an error has occurred while processing the action * ... diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/UserSelectionAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/UserSelectionAction.java index aebb5c7bc0..19193ac996 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/UserSelectionAction.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/UserSelectionAction.java @@ -64,8 +64,11 @@ public abstract class UserSelectionAction extends Action { * @param c the dspace context * @param wfi the workflowitem * @param roleMembers the list of users for which tasks must be regenerated - * @throws SQLException ... * @throws AuthorizeException thrown if the current user isn't authorized + * @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 abstract void regenerateTasks(Context c, XmlWorkflowItem wfi, RoleMembers roleMembers) throws SQLException, AuthorizeException, IOException; @@ -77,7 +80,8 @@ public abstract class UserSelectionAction extends Action { * @param hasUI boolean indicating whether or not the action has a user interface * @return if the action is valid * @throws WorkflowConfigurationException occurs if there is a configuration error in the workflow - * @throws SQLException ... + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public abstract boolean isValidUserSelection(Context context, XmlWorkflowItem wfi, boolean hasUI) throws WorkflowConfigurationException, SQLException; diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/storedcomponents/service/XmlWorkflowItemService.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/storedcomponents/service/XmlWorkflowItemService.java index aa8baa3778..cfa033091a 100644 --- a/dspace-api/src/main/java/org/dspace/xmlworkflow/storedcomponents/service/XmlWorkflowItemService.java +++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/storedcomponents/service/XmlWorkflowItemService.java @@ -26,34 +26,57 @@ public interface XmlWorkflowItemService extends WorkflowItemService findAll(Context context, Integer page, Integer pagesize) throws SQLException; /** * return all workflowitems for a certain page with a certain collection * - * @param collection active context + * @param context + * The relevant DSpace Context. + * @param page + * paging: page number + * @param pagesize + * paging: items per page + * @param collection + * restrict to this collection * @return WorkflowItem list of all the workflow items in system + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public List findAllInCollection(Context context, Integer page, Integer pagesize, Collection collection) throws SQLException; /** * return how many workflow items appear in the database * - * @param context active context + * @param context + * The relevant DSpace Context. * @return the number of workflow items + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public int countAll(Context context) throws SQLException; /** * return how many workflow items that appear in the collection * - * @param context active context + * @param context + * The relevant DSpace Context. + * @param collection + * restrict to this collection * @return the number of workflow items + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public int countAllInCollection(Context context, Collection collection) throws SQLException; - } diff --git a/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java b/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java index 3bf6f116e6..021182e79d 100644 --- a/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java +++ b/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java @@ -38,6 +38,8 @@ public class IPMatcherTest /** * This also tests instantiation of correct masked and unmasked IPv6 addresses. * @throws IPMatcherException + * if there is an error parsing the specification (i.e. it is + * somehow malformed) */ @BeforeClass static public void setUp() throws IPMatcherException diff --git a/dspace-api/src/test/java/org/dspace/content/VersioningTest.java b/dspace-api/src/test/java/org/dspace/content/VersioningTest.java index f1bfe1c8b4..9dcd8dbba8 100644 --- a/dspace-api/src/test/java/org/dspace/content/VersioningTest.java +++ b/dspace-api/src/test/java/org/dspace/content/VersioningTest.java @@ -151,7 +151,7 @@ public class VersioningTest extends AbstractUnitTest { /* The following assertments are specific to the VersionHandleIdentifier * that use "canonical" handles that are moved from version to version. * It would be good to create Tests for each IdentifierProvider, which - * would need to tell spring which one to use for which test. + * would need to tell Spring which one to use for which test. * * assertTrue("Test_version_handle 4 ", versionedItem.getHandles().size() == 2); * assertTrue("Test_version_handle 5 ", originalItem.getHandle().matches(versionedHandleRegex)); diff --git a/dspace-jspui/pom.xml b/dspace-jspui/pom.xml index b4a9188a7b..e5dfb47835 100644 --- a/dspace-jspui/pom.xml +++ b/dspace-jspui/pom.xml @@ -13,7 +13,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissions.java b/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissions.java index ff06eaba5b..5b36a6d9e4 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissions.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissions.java @@ -21,57 +21,58 @@ import org.dspace.content.Item; */ public class RecentSubmissions { - /** The set of items being represented */ - private List items; - - /** - * Construct a new RecentSubmissions object to represent the passed - * array of items - * - * @param items - */ - public RecentSubmissions(List items) - { - this.items = items; - } + /** The set of items being represented */ + private List items; + + /** + * Construct a new RecentSubmissions object to represent the passed + * array of items + * + * @param items + * items to put into recent submissions + */ + public RecentSubmissions(List items) + { + this.items = items; + } - /** - * obtain the number of recent submissions available - * - * @return the number of items - */ - public int count() - { - return items.size(); - } - - /** - * Obtain the array of items - * - * @return an array of items - */ - public List getRecentSubmissions() - { - return items; - } - - /** - * Get the item which is in the i'th position. Therefore i = 1 gets the - * most recently submitted item, while i = 3 gets the 3rd most recently - * submitted item - * - * @param i the position of the item to retrieve - * @return the Item - */ - public Item getRecentSubmission(int i) - { - if (i < items.size()) - { - return items.get(i); - } - else - { - return null; - } - } + /** + * obtain the number of recent submissions available + * + * @return the number of items + */ + public int count() + { + return items.size(); + } + + /** + * Obtain the array of items + * + * @return an array of items + */ + public List getRecentSubmissions() + { + return items; + } + + /** + * Get the item which is in the i'th position. Therefore i = 1 gets the + * most recently submitted item, while i = 3 gets the 3rd most recently + * submitted item + * + * @param i the position of the item to retrieve + * @return the Item + */ + public Item getRecentSubmission(int i) + { + if (i < items.size()) + { + return items.get(i); + } + else + { + return null; + } + } } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissionsManager.java b/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissionsManager.java index b746104f93..95d62ba7d1 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissionsManager.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/components/RecentSubmissionsManager.java @@ -29,52 +29,54 @@ import org.dspace.sort.SortOption; */ public class RecentSubmissionsManager { - /** logger */ - private static Logger log = Logger.getLogger(RecentSubmissionsManager.class); - - /** DSpace context */ - private Context context; - - /** - * Construct a new RecentSubmissionsManager with the given DSpace context - * - * @param context - */ - public RecentSubmissionsManager(Context context) - { - this.context = context; - } + /** logger */ + private static Logger log = Logger.getLogger(RecentSubmissionsManager.class); + + /** DSpace context */ + private Context context; + + /** + * Construct a new RecentSubmissionsManager with the given DSpace context + * + * @param context + * The relevant DSpace Context. + */ + public RecentSubmissionsManager(Context context) + { + this.context = context; + } - /** - * Obtain the recent submissions from the given container object. This - * method uses the configuration to determine which field and how many - * items to retrieve from the DSpace Object. - * - * If the object you pass in is not a Community or Collection (e.g. an Item - * is a DSpaceObject which cannot be used here), an exception will be thrown - * - * @param dso DSpaceObject: Community, Collection or null for SITE - * @return The recently submitted items - * @throws RecentSubmissionsException - */ - public RecentSubmissions getRecentSubmissions(DSpaceObject dso) - throws RecentSubmissionsException - { - try - { - // get our configuration - String source = ConfigurationManager.getProperty("recent.submissions.sort-option"); - String count = ConfigurationManager.getProperty("recent.submissions.count"); - - // prep our engine and scope - BrowseEngine be = new BrowseEngine(context); - BrowserScope bs = new BrowserScope(context); - BrowseIndex bi = BrowseIndex.getItemBrowseIndex(); - - // fill in the scope with the relevant gubbins - bs.setBrowseIndex(bi); - bs.setOrder(SortOption.DESCENDING); - bs.setResultsPerPage(Integer.parseInt(count)); + /** + * Obtain the recent submissions from the given container object. This + * method uses the configuration to determine which field and how many + * items to retrieve from the DSpace Object. + * + * If the object you pass in is not a Community or Collection (e.g. an Item + * is a DSpaceObject which cannot be used here), an exception will be thrown + * + * @param dso DSpaceObject: Community, Collection or null for SITE + * @return The recently submitted items + * @throws RecentSubmissionsException + * General exception to be thrown by code working with recent submissions + */ + public RecentSubmissions getRecentSubmissions(DSpaceObject dso) + throws RecentSubmissionsException + { + try + { + // get our configuration + String source = ConfigurationManager.getProperty("recent.submissions.sort-option"); + String count = ConfigurationManager.getProperty("recent.submissions.count"); + + // prep our engine and scope + BrowseEngine be = new BrowseEngine(context); + BrowserScope bs = new BrowserScope(context); + BrowseIndex bi = BrowseIndex.getItemBrowseIndex(); + + // fill in the scope with the relevant gubbins + bs.setBrowseIndex(bi); + bs.setOrder(SortOption.DESCENDING); + bs.setResultsPerPage(Integer.parseInt(count)); if (dso != null) { bs.setBrowseContainer(dso); @@ -86,25 +88,25 @@ public class RecentSubmissionsManager bs.setSortBy(so.getNumber()); } } - - BrowseInfo results = be.browseMini(bs); - - List items = results.getResults(); - - RecentSubmissions rs = new RecentSubmissions(items); - - return rs; - } + + BrowseInfo results = be.browseMini(bs); + + List items = results.getResults(); + + RecentSubmissions rs = new RecentSubmissions(items); + + return rs; + } catch (SortException se) { log.error("caught exception: ", se); throw new RecentSubmissionsException(se); } - catch (BrowseException e) - { - log.error("caught exception: ", e); - throw new RecentSubmissionsException(e); - } - } - + catch (BrowseException e) + { + log.error("caught exception: ", e); + throw new RecentSubmissionsException(e); + } + } + } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverUtility.java b/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverUtility.java index 2dc3b55b91..c3714d056b 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverUtility.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverUtility.java @@ -47,9 +47,16 @@ public class DiscoverUtility * Get the scope of the search using the parameter found in the request. * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. + * @return scope of the search using the parameter found in the request * @throws IllegalStateException + * Signals that a method has been invoked at an illegal or inappropriate + * time. In other words, the Java environment or Java application is + * not in an appropriate state for the requested operation. * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static DSpaceObject getSearchScope(Context context, HttpServletRequest request) throws IllegalStateException, @@ -77,29 +84,35 @@ public class DiscoverUtility /** * Build a DiscoverQuery object using the parameter in the request * + * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. + * @param scope + * DSpace object + * @param enableFacet + * FIXME: PLEASE DOCUMENT. * @return the query. - * @throws SearchServiceException */ public static DiscoverQuery getDiscoverQuery(Context context, HttpServletRequest request, DSpaceObject scope, boolean enableFacet) { DiscoverQuery queryArgs = new DiscoverQuery(); - DiscoveryConfiguration discoveryConfiguration = SearchUtils - .getDiscoveryConfiguration(scope); + DiscoveryConfiguration discoveryConfiguration = + SearchUtils.getDiscoveryConfiguration(scope); - List userFilters = setupBasicQuery(context, - discoveryConfiguration, request, queryArgs); + List userFilters = setupBasicQuery( + context, discoveryConfiguration, request, queryArgs); setPagination(request, queryArgs, discoveryConfiguration); - if (enableFacet - && !"submit_export_metadata".equals(UIUtil.getSubmitButton( - request, "submit"))) + if (enableFacet && !"submit_export_metadata".equals( + UIUtil.getSubmitButton( request, "submit"))) { setFacet(context, request, scope, queryArgs, - discoveryConfiguration, userFilters, discoveryConfiguration - .getSidebarFacets(), TYPE_FACETS); + discoveryConfiguration, userFilters, + discoveryConfiguration.getSidebarFacets(), + TYPE_FACETS); } return queryArgs; @@ -108,29 +121,35 @@ public class DiscoverUtility /** * Build a DiscoverQuery object using the tag cloud parameter in the request * + * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. + * @param scope + * DSpace object + * @param enableFacet + * FIXME: PLEASE DOCUMENT. * @return the query. - * @throws SearchServiceException */ public static DiscoverQuery getTagCloudDiscoverQuery(Context context, HttpServletRequest request, DSpaceObject scope, boolean enableFacet) { DiscoverQuery queryArgs = new DiscoverQuery(); - DiscoveryConfiguration discoveryConfiguration = SearchUtils - .getDiscoveryConfiguration(scope); + DiscoveryConfiguration discoveryConfiguration = + SearchUtils.getDiscoveryConfiguration(scope); List userFilters = setupBasicQuery(context, - discoveryConfiguration, request, queryArgs); + discoveryConfiguration, request, queryArgs); setPagination(request, queryArgs, discoveryConfiguration); - if (enableFacet - && !"submit_export_metadata".equals(UIUtil.getSubmitButton( - request, "submit"))) + if (enableFacet && !"submit_export_metadata".equals( + UIUtil.getSubmitButton(request, "submit"))) { setFacet(context, request, scope, queryArgs, - discoveryConfiguration, userFilters, discoveryConfiguration - .getTagCloudFacetConfiguration().getTagCloudFacets(), TYPE_TAGCLOUD); + discoveryConfiguration, userFilters, discoveryConfiguration + .getTagCloudFacetConfiguration().getTagCloudFacets(), + TYPE_TAGCLOUD); } return queryArgs; @@ -141,8 +160,11 @@ public class DiscoverUtility * parameters in the request * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param scope + * target DSpace object to search in * @return the query. */ public static DiscoverQuery getDiscoverAutocomplete(Context context, @@ -200,9 +222,8 @@ public class DiscoverUtility { limit = 10; } - DiscoverFacetField autocompleteField = new DiscoverFacetField(autoIndex, - autoType, - limit, sortBy, autoQuery.toLowerCase()); + DiscoverFacetField autocompleteField = new DiscoverFacetField( + autoIndex, autoType, limit, sortBy, autoQuery.toLowerCase()); queryArgs.addFacetField(autocompleteField); queryArgs.setMaxResults(0); queryArgs.setFacetMinCount(1); @@ -214,7 +235,9 @@ public class DiscoverUtility * (default + user). Return the list of user filter * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param queryArgs * the query object to populate * @return the list of user filer (as filter query) @@ -232,8 +255,8 @@ public class DiscoverUtility queryArgs.setQuery(query); } - List defaultFilterQueries = discoveryConfiguration - .getDefaultFilterQueries(); + List defaultFilterQueries = + discoveryConfiguration.getDefaultFilterQueries(); if (defaultFilterQueries != null) { for (String f : defaultFilterQueries) @@ -247,26 +270,25 @@ public class DiscoverUtility { try { - String newFilterQuery = null; - if (StringUtils.isNotBlank(f[0]) && StringUtils.isNotBlank(f[2])) - { - newFilterQuery = SearchUtils.getSearchService() + String newFilterQuery = null; + if (StringUtils.isNotBlank(f[0]) && StringUtils.isNotBlank(f[2])) + { + newFilterQuery = SearchUtils.getSearchService() .toFilterQuery(context, f[0], f[1], f[2]) .getFilterQuery(); - } - if (newFilterQuery != null) - { - queryArgs.addFilterQueries(newFilterQuery); - userFilters.add(newFilterQuery); - } + } + if (newFilterQuery != null) + { + queryArgs.addFilterQueries(newFilterQuery); + userFilters.add(newFilterQuery); + } } catch (SQLException e) { log.error(LogManager.getHeader(context, - "Error in discovery while setting up user facet query", - "filter_field: " + f[0] + ",filter_type:" - + f[1] + ",filer_value:" - + f[2]), e); + "Error in discovery while setting up user facet query", + "filter_field: " + f[0] + ",filter_type:" + + f[1] + ",filer_value:" + f[2]), e); } } @@ -302,26 +324,23 @@ public class DiscoverUtility String sortBy = request.getParameter("sort_by"); String sortOrder = request.getParameter("order"); - DiscoverySortConfiguration searchSortConfiguration = discoveryConfiguration - .getSearchSortConfiguration(); + DiscoverySortConfiguration searchSortConfiguration = + discoveryConfiguration.getSearchSortConfiguration(); if (sortBy == null) { // Attempt to find the default one, if none found we use SCORE sortBy = "score"; if (searchSortConfiguration != null) { - for (DiscoverySortFieldConfiguration sortFieldConfiguration : searchSortConfiguration - .getSortFields()) + for (DiscoverySortFieldConfiguration sortFieldConfiguration : + searchSortConfiguration.getSortFields()) { - if (sortFieldConfiguration.equals(searchSortConfiguration - .getDefaultSort())) + if (sortFieldConfiguration.equals( + searchSortConfiguration.getDefaultSort())) { - sortBy = SearchUtils - .getSearchService() - .toSortFieldIndex( - sortFieldConfiguration - .getMetadataField(), - sortFieldConfiguration.getType()); + sortBy = SearchUtils.getSearchService().toSortFieldIndex( + sortFieldConfiguration.getMetadataField(), + sortFieldConfiguration.getType()); } } } @@ -635,12 +654,10 @@ public class DiscoverUtility } catch (Exception e) { - log.error( - LogManager - .getHeader( - context, - "Error in discovery while setting up date facet range", - "date facet: " + dateFacet), e); + log.error(LogManager.getHeader( + context, + "Error in discovery while setting up date facet range", + "date facet: " + dateFacet), e); } } else @@ -648,7 +665,7 @@ public class DiscoverUtility int facetLimit = type==TYPE_FACETS?facet.getFacetLimit():-1; int facetPage = UIUtil.getIntParameter(request, - facet.getIndexFieldName() + "_page"); + facet.getIndexFieldName() + "_page"); if (facetPage < 0) { facetPage = 0; @@ -665,17 +682,17 @@ public class DiscoverUtility // top list // if possible int limit = 0; - if (type==TYPE_FACETS){ - limit = facetLimit + 1 + alreadySelected; + if (type==TYPE_FACETS) { + limit = facetLimit + 1 + alreadySelected; } else - limit = facetLimit; + limit = facetLimit; - queryArgs.addFacetField(new DiscoverFacetField(facet - .getIndexFieldName(), - DiscoveryConfigurationParameters.TYPE_TEXT, - limit, facet - .getSortOrderSidebar(), facetPage * facetLimit)); + queryArgs.addFacetField(new DiscoverFacetField( + facet.getIndexFieldName(), + DiscoveryConfigurationParameters.TYPE_TEXT, + limit, facet.getSortOrderSidebar(), + facetPage * facetLimit)); } } } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverySearchRequestProcessor.java b/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverySearchRequestProcessor.java index 9ebb6afbd1..7c414e099b 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverySearchRequestProcessor.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/discovery/DiscoverySearchRequestProcessor.java @@ -320,14 +320,14 @@ public class DiscoverySearchRequestProcessor implements SearchRequestProcessor { try { - DSpaceObject pDso = ContentServiceFactory.getInstance().getDSpaceObjectService(scope) - .getParentObject(context, scope); + DSpaceObject pDso = ContentServiceFactory.getInstance().getDSpaceObjectService(scope) + .getParentObject(context, scope); while (pDso != null) { // add to the available scopes in reverse order scopes.add(0, pDso); pDso = ContentServiceFactory.getInstance().getDSpaceObjectService(pDso) - .getParentObject(context, pDso); + .getParentObject(context, pDso); } scopes.add(scope); if (scope instanceof Community) @@ -436,10 +436,9 @@ public class DiscoverySearchRequestProcessor implements SearchRequestProcessor } catch (SearchServiceException e) { - log.error( - LogManager.getHeader(context, "search", "query=" - + queryArgs.getQuery() + ",scope=" + scope - + ",error=" + e.getMessage()), e); + log.error(LogManager.getHeader(context, "search", "query=" + + queryArgs.getQuery() + ",scope=" + scope + + ",error=" + e.getMessage()), e); request.setAttribute("search.error", true); request.setAttribute("search.error.message", e.getMessage()); } @@ -451,13 +450,15 @@ public class DiscoverySearchRequestProcessor implements SearchRequestProcessor * Export the search results as a csv file * * @param context - * The DSpace context + * The relevant DSpace Context. * @param response - * The request object + * Servlet's HTTP response object. * @param items - * The result items + * search results (list of items) * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ protected void exportMetadata(Context context, HttpServletResponse response, List items) throws IOException, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/json/JSONRequest.java b/dspace-jspui/src/main/java/org/dspace/app/webui/json/JSONRequest.java index 671edb0cfc..98fd5fa91c 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/json/JSONRequest.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/json/JSONRequest.java @@ -29,7 +29,9 @@ public abstract class JSONRequest /** * Set the subPath that this plugin-instance will serve + * * @param subPath + * URL subpath to be served by this servlet plugin */ public void setSubPath(String subPath) { diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java b/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java index c28352fc22..ad46bcabd4 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/ItemTag.java @@ -92,7 +92,7 @@ import org.dspace.workflow.factory.WorkflowServiceFactory; * dc.identifier.uri(link) = DC identifier.uri, render as a link * dc.date.issued(date) = DC date.issued, render as a date * dc.identifier.doi(doi) = DC identifier.doi, render as link to http://dx.doi.org - * dc.identifier.hdl(handle) = DC identifier.hanlde, render as link to http://hdl.handle.net + * dc.identifier.hdl(handle) = DC identifier.handle, render as link to http://hdl.handle.net * dc.relation.isPartOf(resolver) = DC relation.isPartOf, render as link to the base url of the resolver * according to the specified urn in the metadata value (doi:xxxx, hdl:xxxxx, * urn:issn:xxxx, etc.) @@ -101,8 +101,8 @@ import org.dspace.workflow.factory.WorkflowServiceFactory; * *

* When using "resolver" in webui.itemdisplay to render identifiers as resolvable - * links, the base URL is taken from webui.resolver..baseurl - * where webui.resolver..urn matches the urn specified in the metadata value. + * links, the base URL is taken from webui.resolver.<n>.baseurl + * where webui.resolver.<n>.urn matches the urn specified in the metadata value. * The value is appended to the "baseurl" as is, so the baseurl need to end with slash almost in any case. * If no urn is specified in the value it will be displayed as simple text. * @@ -115,6 +115,7 @@ import org.dspace.workflow.factory.WorkflowServiceFactory; * * * + *

* For the doi and hdl urn defaults values are provided, respectively http://dx.doi.org/ and * http://hdl.handle.net/ are used.
* @@ -122,8 +123,6 @@ import org.dspace.workflow.factory.WorkflowServiceFactory; * already, it is simply rendered as a link with no other manipulation. *

* - *
- * 
  * 

* If an item has no value for a particular field, it won't be displayed. The * name of the field for display will be drawn from the current UI dictionary, @@ -137,9 +136,11 @@ import org.dspace.workflow.factory.WorkflowServiceFactory; * e.g. "metadata.thesis.dc.title" "metadata.thesis.dc.contributor.*" * "metadata.thesis.dc.date.issued" * + *

* * if this key is not found will be used the more general one * + *
  * "metadata.<field>"
  * 
  * e.g. "metadata.dc.title" "metadata.dc.contributor.*"
diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/LayoutTag.java b/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/LayoutTag.java
index 8abc194b09..c00dddc30e 100644
--- a/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/LayoutTag.java
+++ b/dspace-jspui/src/main/java/org/dspace/app/webui/jsptag/LayoutTag.java
@@ -29,10 +29,8 @@ import org.dspace.core.ConfigurationManager;
 
 /**
  * Tag for HTML page layout ("skin").
- * 

* This tag sets request attributes that should be used by the header * and footer to render the page appropriately: - *

*

    *
  • dspace.layout.title - title of page
  • *
  • dspace.layout.locbar - value will Boolean true or false @@ -58,10 +56,8 @@ import org.dspace.core.ConfigurationManager; * (e.g. rss_1.0). Hence, this array will have 3n * elements where n is the number of feeds.
  • *
- *

* * * Additionally the following parameter may be set elsewhere in a Servlet. - *

*

    *
  • dspace.layout.head - extra data to include verbatim in * the <head> element of the page
  • @@ -69,7 +65,6 @@ import org.dspace.core.ConfigurationManager; * * Furthermore it sets the content type of the response to text/html using UTF-8 * to ensure this will be returned in the HTTP header. - *

    * * @author Robert Tansley * @version $Revision$ @@ -272,58 +267,58 @@ public class LayoutTag extends BodyTagSupport if (feedData != null && ! "NONE".equals(feedData)) { // set the links' reference - community or collection - boolean commLinks = feedData.startsWith("comm:"); - boolean collLinks = feedData.startsWith("coll:"); - if ( commLinks ) - { + boolean commLinks = feedData.startsWith("comm:"); + boolean collLinks = feedData.startsWith("coll:"); + if ( commLinks ) + { Community com = (Community)request.getAttribute("dspace.community"); - request.setAttribute("dspace.layout.feedref", com.getHandle()); - } - else if( collLinks ) - { - Collection col = (Collection)request.getAttribute("dspace.collection"); - request.setAttribute("dspace.layout.feedref", col.getHandle()); - } - else //feed is across all of DSpace and not Community/Collection specific - { - request.setAttribute("dspace.layout.feedref", FeedServlet.SITE_FEED_KEY); - } - - // build a list of link attributes for each link format - String[] formats = feedData.substring(feedData.indexOf(':')+1).split(","); - List linkParts = new ArrayList(); - // each link has a mime-type, title, and format (used in href URL) - for (int i = 0; i < formats.length; i++) - { - if("rss_1.0".equals(formats[i])) - { - linkParts.add("rdf+xml"); - } - else - { - linkParts.add("rss+xml"); - } - - if (commLinks) - { - linkParts.add("Items in Community"); - } - else if(collLinks) - { - linkParts.add("Items in Collection"); - } - else - { - linkParts.add("Items in " + ConfigurationManager.getProperty("dspace.name")); - } - - linkParts.add(formats[i]); - } - request.setAttribute("dspace.layout.linkparts", linkParts); + request.setAttribute("dspace.layout.feedref", com.getHandle()); + } + else if( collLinks ) + { + Collection col = (Collection)request.getAttribute("dspace.collection"); + request.setAttribute("dspace.layout.feedref", col.getHandle()); + } + else //feed is across all of DSpace and not Community/Collection specific + { + request.setAttribute("dspace.layout.feedref", FeedServlet.SITE_FEED_KEY); + } + + // build a list of link attributes for each link format + String[] formats = feedData.substring(feedData.indexOf(':')+1).split(","); + List linkParts = new ArrayList(); + // each link has a mime-type, title, and format (used in href URL) + for (int i = 0; i < formats.length; i++) + { + if("rss_1.0".equals(formats[i])) + { + linkParts.add("rdf+xml"); + } + else + { + linkParts.add("rss+xml"); + } + + if (commLinks) + { + linkParts.add("Items in Community"); + } + else if(collLinks) + { + linkParts.add("Items in Collection"); + } + else + { + linkParts.add("Items in " + ConfigurationManager.getProperty("dspace.name")); + } + + linkParts.add(formats[i]); + } + request.setAttribute("dspace.layout.linkparts", linkParts); } else { - request.setAttribute("dspace.layout.feedref", "NONE" ); + request.setAttribute("dspace.layout.feedref", "NONE" ); } return EVAL_BODY_BUFFERED; diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java index 916c36cd66..c1e4763834 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java @@ -72,9 +72,14 @@ public abstract class AbstractBrowserServlet extends DSpaceServlet * @param response The servlet response * @return A BrowserScope for the current parameters * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected BrowserScope getBrowserScopeForRequest(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException @@ -91,15 +96,15 @@ public abstract class AbstractBrowserServlet extends DSpaceServlet String startsWith = request.getParameter("starts_with"); //validate input to avoid cross-site scripting try { - if (StringUtils.isNotBlank(month) && !"-1".equals(month)) { - Integer.valueOf(month); - } - if (StringUtils.isNotBlank(year) && !"-1".equals(year)) { - Integer.valueOf(year); - } - if(StringUtils.isNotBlank(startsWith)) { - startsWith = Utils.addEntities(startsWith); - } + if (StringUtils.isNotBlank(month) && !"-1".equals(month)) { + Integer.valueOf(month); + } + if (StringUtils.isNotBlank(year) && !"-1".equals(year)) { + Integer.valueOf(year); + } + if (StringUtils.isNotBlank(startsWith)) { + startsWith = Utils.addEntities(startsWith); + } } catch(Exception ex) { log.warn("We were unable to parse the browse request: maybe a cross-site scripting attach?"); @@ -324,6 +329,24 @@ public abstract class AbstractBrowserServlet extends DSpaceServlet /** * Do the usual DSpace GET method. You will notice that browse does not currently * respond to POST requests. + * + * @param context + * The relevant DSpace Context. + * @param scope + * represents the initial request to the browse system + * @param request + * Servlet's HTTP request object. + * @param response + * Servlet's HTTP response object. + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ protected void processBrowse(Context context, BrowserScope scope, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -349,14 +372,14 @@ public abstract class AbstractBrowserServlet extends DSpaceServlet { if (bi.isMetadataIndex() && !scope.isSecondLevel()) { - if (bi.isTagCloudEnabled()){ - TagCloudConfiguration tagCloudConfiguration = DSpaceServicesFactory.getInstance().getServiceManager().getServiceByName("browseTagCloudConfiguration", TagCloudConfiguration.class); - if (tagCloudConfiguration == null){ - tagCloudConfiguration = new TagCloudConfiguration(); - } - request.setAttribute("tagCloudConfig", tagCloudConfiguration); - } - + if (bi.isTagCloudEnabled()) { + TagCloudConfiguration tagCloudConfiguration = DSpaceServicesFactory.getInstance().getServiceManager().getServiceByName("browseTagCloudConfiguration", TagCloudConfiguration.class); + if (tagCloudConfiguration == null) { + tagCloudConfiguration = new TagCloudConfiguration(); + } + request.setAttribute("tagCloudConfig", tagCloudConfiguration); + } + showSinglePage(context, request, response); } else @@ -380,12 +403,20 @@ public abstract class AbstractBrowserServlet extends DSpaceServlet * Display the error page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected abstract void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -395,12 +426,20 @@ public abstract class AbstractBrowserServlet extends DSpaceServlet * Display the No Results page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected abstract void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -412,17 +451,44 @@ public abstract class AbstractBrowserServlet extends DSpaceServlet * that match that metadata value * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected abstract void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; + /** + * Display the full page. + * + * @param context + * The relevant DSpace Context. + * @param request + * Servlet's HTTP request object. + * @param response + * Servlet's HTTP response object. + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. + */ protected abstract void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BatchImportServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BatchImportServlet.java index ee426de174..14fa95d5c7 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BatchImportServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BatchImportServlet.java @@ -54,14 +54,21 @@ public class BatchImportServlet extends DSpaceServlet /** * Respond to a post request for metadata bulk importing via csv * - * @param context a DSpace Context object - * @param request the HTTP request - * @param response the HTTP response - * + * @param context + * The relevant DSpace Context. + * @param request + * Servlet's HTTP request object. + * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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 protected void doDSPost(Context context, HttpServletRequest request, @@ -242,43 +249,47 @@ public class BatchImportServlet extends DSpaceServlet * GET request is only ever used to show the upload form * * @param context - * a DSpace Context object + * The relevant DSpace Context. * @param request - * the HTTP request + * Servlet's HTTP request object. * @param response - * the HTTP response - * + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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 protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { - //Get all collections - List collections = null; - String colIdS = request.getParameter("colId"); - if (colIdS!=null){ - collections = new ArrayList<>(); - collections.add(collectionService.findByIdOrLegacyId(context, colIdS)); + //Get all collections + List collections = null; + String colIdS = request.getParameter("colId"); + if (colIdS!=null){ + collections = new ArrayList<>(); + collections.add(collectionService.findByIdOrLegacyId(context, colIdS)); - } - else { - collections = collectionService.findAll(context); - } + } + else { + collections = collectionService.findAll(context); + } - request.setAttribute("collections", collections); + request.setAttribute("collections", collections); - //Get all the possible data loaders from the Spring configuration - BTEBatchImportService dls = new DSpace().getSingletonService(BTEBatchImportService.class); - List inputTypes = dls.getFileDataLoaders(); - request.setAttribute("input-types", inputTypes); + //Get all the possible data loaders from the Spring configuration + BTEBatchImportService dls = new DSpace().getSingletonService(BTEBatchImportService.class); + List inputTypes = dls.getFileDataLoaders(); + request.setAttribute("input-types", inputTypes); - // Show the upload screen - JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); + // Show the upload screen + JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); } /** diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BrowserServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BrowserServlet.java index f311f22d5b..de9ad79a49 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BrowserServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/BrowserServlet.java @@ -95,12 +95,20 @@ public class BrowserServlet extends AbstractBrowserServlet * Display the error page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -113,12 +121,20 @@ public class BrowserServlet extends AbstractBrowserServlet * Display the No Results page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -134,12 +150,20 @@ public class BrowserServlet extends AbstractBrowserServlet * that match that metadata value * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -153,12 +177,20 @@ public class BrowserServlet extends AbstractBrowserServlet * Display a full item listing. * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -171,12 +203,18 @@ public class BrowserServlet extends AbstractBrowserServlet /** * Export the metadata from a browse * - * @param context The DSpace context - * @param request The request object - * @param response The response object - * @param scope The browse scope - * @throws IOException + * @param context + * The relevant DSpace Context. + * @param request + * Servlet's HTTP request object. + * @param response + * Servlet's HTTP response object. + * @param scope + The browse scope * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ protected void exportMetadata(Context context, HttpServletRequest request, HttpServletResponse response, BrowserScope scope) diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/ControlledVocabularySearchServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/ControlledVocabularySearchServlet.java index 123f8c8f80..9fb05f55db 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/ControlledVocabularySearchServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/ControlledVocabularySearchServlet.java @@ -125,7 +125,9 @@ public class ControlledVocabularySearchServlet extends DSpaceServlet * @param query * The query expression * @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. */ private void doSearch(Context context, HttpServletRequest request, String query) throws IOException, SQLException diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/DSpaceServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/DSpaceServlet.java index 9eef1ae66a..07833b59b1 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/DSpaceServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/DSpaceServlet.java @@ -84,9 +84,14 @@ public class DSpaceServlet extends HttpServlet * Process an incoming request * * @param request - * the request object + * the HTTP request * @param response - * the response object + * the HTTP response + * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException @@ -203,10 +208,15 @@ public class DSpaceServlet extends HttpServlet * @param response * the HTTP response * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. * @throws SQLException - * if a database error occurs + * An exception that provides information on a database access error or other errors. * @throws AuthorizeException - * if some authorization error occurs + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, @@ -229,10 +239,15 @@ public class DSpaceServlet extends HttpServlet * @param response * the HTTP response * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. * @throws SQLException - * if a database error occurs + * An exception that provides information on a database access error or other errors. * @throws AuthorizeException - * if some authorization error occurs + * Exception indicating the current user of the context does not have permission + * to perform a particular action. */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/EditProfileServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/EditProfileServlet.java index 7a9b2c2de3..b36926d400 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/EditProfileServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/EditProfileServlet.java @@ -117,6 +117,8 @@ public class EditProfileServlet extends DSpaceServlet * request. This assumes that authentication has occurred. This method * doesn't write the changes to the database (i.e. doesn't call update.) * + * @param context + * The relevant DSpace Context. * @param eperson * the e-person * @param request @@ -124,6 +126,8 @@ public class EditProfileServlet extends DSpaceServlet * * @return true if the user supplied all the required information, false if * they left something out. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public boolean updateUserProfile(Context context, EPerson eperson, HttpServletRequest request) throws SQLException diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataExportServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataExportServlet.java index 054cbfed99..c67c7b419e 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataExportServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataExportServlet.java @@ -54,14 +54,21 @@ public class MetadataExportServlet extends DSpaceServlet /** * Respond to a post request * - * @param context a DSpace Context object - * @param request the HTTP request - * @param response the HTTP response - * + * @param context + * The relevant DSpace Context. + * @param request + * Servlet's HTTP request object. + * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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 protected void doDSPost(Context context, HttpServletRequest request, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataImportServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataImportServlet.java index 052559690f..7b6b7e4a6d 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataImportServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/MetadataImportServlet.java @@ -55,14 +55,21 @@ public class MetadataImportServlet extends DSpaceServlet /** * Respond to a post request for metadata bulk importing via csv * - * @param context a DSpace Context object - * @param request the HTTP request - * @param response the HTTP response - * + * @param context + * The relevant DSpace Context. + * @param request + * Servlet's HTTP request object. + * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, @@ -169,16 +176,20 @@ public class MetadataImportServlet extends DSpaceServlet * GET request is only ever used to show the upload form * * @param context - * a DSpace Context object + * The relevant DSpace Context. * @param request - * the HTTP request + * Servlet's HTTP request object. * @param response - * the HTTP response - * + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, @@ -221,4 +232,4 @@ public class MetadataImportServlet extends DSpaceServlet // Return the changes return changes; } -} \ No newline at end of file +} diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/RequestItemServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/RequestItemServlet.java index 30184fb70e..4171bd5434 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/RequestItemServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/RequestItemServlet.java @@ -95,36 +95,36 @@ public class RequestItemServlet extends DSpaceServlet try { - switch (step) - { - case ENTER_FORM_PAGE: - processForm(context, request, response); - break; - - case ENTER_TOKEN: - processToken(context, request, response); - break; - - case APROVE_TOKEN: - processLetter(context, request, response); - break; - - case RESUME_REQUEST: - processAttach(context, request, response); - break; - - case RESUME_FREEACESS: - processAdmin(context, request, response); - break; - - default: - processForm(context, request, response); - } - context.complete(); + switch (step) + { + case ENTER_FORM_PAGE: + processForm(context, request, response); + break; + + case ENTER_TOKEN: + processToken(context, request, response); + break; + + case APROVE_TOKEN: + processLetter(context, request, response); + break; + + case RESUME_REQUEST: + processAttach(context, request, response); + break; + + case RESUME_FREEACESS: + processAdmin(context, request, response); + break; + + default: + processForm(context, request, response); + } + context.complete(); } catch (MessagingException e) { - throw new RuntimeException(e.getMessage(), e); + throw new RuntimeException(e.getMessage(), e); } } @@ -143,19 +143,19 @@ public class RequestItemServlet extends DSpaceServlet HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { - boolean showRequestCopy = false; - if ("all".equalsIgnoreCase(ConfigurationManager.getProperty("request.item.type")) || - ("logged".equalsIgnoreCase(ConfigurationManager.getProperty("request.item.type")) && - context.getCurrentUser() != null)) - { - showRequestCopy = true; - } - - if (!showRequestCopy) - { - throw new AuthorizeException("The request copy feature is disabled"); - } - + boolean showRequestCopy = false; + if ("all".equalsIgnoreCase(ConfigurationManager.getProperty("request.item.type")) || + ("logged".equalsIgnoreCase(ConfigurationManager.getProperty("request.item.type")) && + context.getCurrentUser() != null)) + { + showRequestCopy = true; + } + + if (!showRequestCopy) + { + throw new AuthorizeException("The request copy feature is disabled"); + } + // handle String handle = request.getParameter("handle"); @@ -171,13 +171,13 @@ public class RequestItemServlet extends DSpaceServlet } if (item == null) { - JSPManager.showInvalidIDError(request, response, handle, -1); + JSPManager.showInvalidIDError(request, response, handle, -1); } title = itemService.getMetadataFirstValue(item, "dc", "title", null, Item.ANY); if (title == null) - { - title = I18nUtil.getMessage("jsp.general.untitled", context); - } + { + title = I18nUtil.getMessage("jsp.general.untitled", context); + } // User email from context String requesterEmail = request.getParameter("email"); @@ -217,44 +217,44 @@ public class RequestItemServlet extends DSpaceServlet try { - String token = requestItemService.createRequest(context, bitstream_id != null? - bitstreamService.find(context, bitstream_id):null, item, allfiles, requesterEmail, reqname, coment); - + String token = requestItemService.createRequest(context, bitstream_id != null? + bitstreamService.find(context, bitstream_id):null, item, allfiles, requesterEmail, reqname, coment); + String linkedToken = getLinkTokenEmail(context, token); // All data is there, send the email - Email email = Email.getEmail(I18nUtil.getEmailFilename( - context.getCurrentLocale(), "request_item.author")); - - RequestItemAuthor author = DSpaceServicesFactory.getInstance().getServiceManager() - .getServiceByName( - RequestItemAuthorExtractor.class.getName(), - RequestItemAuthorExtractor.class) - .getRequestItemAuthor(context, item); - - String authorEmail = author.getEmail(); - String authorName = author.getFullName(); - - email.addRecipient(authorEmail); + Email email = Email.getEmail(I18nUtil.getEmailFilename( + context.getCurrentLocale(), "request_item.author")); + + RequestItemAuthor author = DSpaceServicesFactory.getInstance().getServiceManager() + .getServiceByName( + RequestItemAuthorExtractor.class.getName(), + RequestItemAuthorExtractor.class) + .getRequestItemAuthor(context, item); + + String authorEmail = author.getEmail(); + String authorName = author.getFullName(); + + email.addRecipient(authorEmail); - email.addArgument(reqname); - email.addArgument(requesterEmail); - email.addArgument(allfiles ? I18nUtil - .getMessage("itemRequest.all") : bitstreamService.find(context, bitstream_id).getName()); - email.addArgument(handleService.getCanonicalForm(item + email.addArgument(reqname); + email.addArgument(requesterEmail); + email.addArgument(allfiles ? I18nUtil + .getMessage("itemRequest.all") : bitstreamService.find(context, bitstream_id).getName()); + email.addArgument(handleService.getCanonicalForm(item .getHandle())); - email.addArgument(title); // request item title - email.addArgument(coment); // message - email.addArgument(linkedToken); - - email.addArgument(authorName); // corresponding author name - email.addArgument(authorEmail); // corresponding author email - email.addArgument(ConfigurationManager - .getProperty("dspace.name")); - email.addArgument(ConfigurationManager - .getProperty("mail.helpdesk")); - email.setReplyTo(requesterEmail); - email.send(); + email.addArgument(title); // request item title + email.addArgument(coment); // message + email.addArgument(linkedToken); + + email.addArgument(authorName); // corresponding author name + email.addArgument(authorEmail); // corresponding author email + email.addArgument(ConfigurationManager + .getProperty("dspace.name")); + email.addArgument(ConfigurationManager + .getProperty("mail.helpdesk")); + email.setReplyTo(requesterEmail); + email.send(); log.info(LogManager.getHeader(context, "sent_email_requestItem", @@ -300,93 +300,93 @@ public class RequestItemServlet extends DSpaceServlet HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { - // Token + // Token String token = request.getParameter("token"); RequestItem requestItem = requestItemService.findByToken(context, token); // validate if (requestItem != null) { - Item item = requestItem.getItem(); - String title = ""; - String handle = ""; - if (item != null) { - title = itemService.getMetadataFirstValue(item, "dc", "title", null, Item.ANY); - if (title == null) { - title = ""; - } - handle = item.getHandle(); - } + Item item = requestItem.getItem(); + String title = ""; + String handle = ""; + if (item != null) { + title = itemService.getMetadataFirstValue(item, "dc", "title", null, Item.ANY); + if (title == null) { + title = ""; + } + handle = item.getHandle(); + } request.setAttribute("request-name", requestItem.getReqName()); request.setAttribute("handle", handle); request.setAttribute("title", title); JSPManager.showJSP(request, response, "/requestItem/request-information.jsp"); - }else{ + } else { JSPManager.showInvalidIDError(request, response, token, -1); } } - /* - * receive approvation and generate a letter - * get all request data by token - * send email to request user - */ - private void processLetter(Context context, HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException, - SQLException, AuthorizeException, MessagingException { - // Token - String token = request.getParameter("token"); - boolean yes = request.getParameter("submit_yes") != null; - boolean no = request.getParameter("submit_no") != null; + /* + * receive approvation and generate a letter + * get all request data by token + * send email to request user + */ + private void processLetter(Context context, HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException, + SQLException, AuthorizeException, MessagingException { + // Token + String token = request.getParameter("token"); + boolean yes = request.getParameter("submit_yes") != null; + boolean no = request.getParameter("submit_no") != null; - // get token, get register, get email template, format email, get - // message to jsp - RequestItem requestItem = requestItemService.findByToken(context, - token); + // get token, get register, get email template, format email, get + // message to jsp + RequestItem requestItem = requestItemService.findByToken(context, + token); - if (requestItem != null && (yes || no)) { - Item item = requestItem.getItem(); + if (requestItem != null && (yes || no)) { + Item item = requestItem.getItem(); - String title = itemService.getMetadataFirstValue(item, "dc", "title", null, Item.ANY); - title = title != null ? title : I18nUtil - .getMessage("jsp.general.untitled", context); - + String title = itemService.getMetadataFirstValue(item, "dc", "title", null, Item.ANY); + title = title != null ? title : I18nUtil + .getMessage("jsp.general.untitled", context); + - EPerson submiter = item.getSubmitter(); + EPerson submiter = item.getSubmitter(); - Object[] args = new String[]{ - requestItem.getReqName(), - handleService.getCanonicalForm(item.getHandle()), // User - title, // request item title - submiter.getFullName(), // # submmiter name - submiter.getEmail() // # submmiter email - }; - - String subject = I18nUtil.getMessage("itemRequest.response.subject." - + (yes ? "approve" : "reject"), context); - String message = MessageFormat.format(I18nUtil.getMessage("itemRequest.response.body." - + (yes ? "approve" : "reject"), context), args); - - // page - request.setAttribute("response", yes); - request.setAttribute("subject", subject); - request.setAttribute("message", message); - JSPManager.showJSP(request, response, - "/requestItem/request-letter.jsp"); - } else { - JSPManager.showInvalidIDError(request, response, token, -1); - } - } + Object[] args = new String[]{ + requestItem.getReqName(), + handleService.getCanonicalForm(item.getHandle()), // User + title, // request item title + submiter.getFullName(), // # submmiter name + submiter.getEmail() // # submmiter email + }; + + String subject = I18nUtil.getMessage("itemRequest.response.subject." + + (yes ? "approve" : "reject"), context); + String message = MessageFormat.format(I18nUtil.getMessage("itemRequest.response.body." + + (yes ? "approve" : "reject"), context), args); + + // page + request.setAttribute("response", yes); + request.setAttribute("subject", subject); + request.setAttribute("message", message); + JSPManager.showJSP(request, response, + "/requestItem/request-letter.jsp"); + } else { + JSPManager.showInvalidIDError(request, response, token, -1); + } + } - /* - * receive token - * get all request data by token - * send email to request user - */ - private void processAttach (Context context, + /* + * receive token + * get all request data by token + * send email to request user + */ + private void processAttach(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException @@ -413,35 +413,35 @@ public class RequestItemServlet extends DSpaceServlet Email email = new Email(); email.setSubject(subject); email.setContent("{0}"); - email.addRecipient(requestItem.getReqEmail()); + email.addRecipient(requestItem.getReqEmail()); email.addArgument(message); - // add attach - if (accept) { - if (requestItem.getBitstream() == null) { - List bundles = itemService.getBundles(item, "ORIGINAL"); - for (Bundle b : bundles) { - List bbitstreams = b.getBitstreams(); - for (Bitstream bitstream : bbitstreams) { - if (!bitstream.getFormat(context).isInternal() - && authorizeService.authorizeActionBoolean(context, null, bitstream, Constants.READ, false)) { - email.addAttachment( - bitstreamService - .retrieve( + // add attach + if (accept) { + if (requestItem.getBitstream() == null) { + List bundles = itemService.getBundles(item, "ORIGINAL"); + for (Bundle b : bundles) { + List bbitstreams = b.getBitstreams(); + for (Bitstream bitstream : bbitstreams) { + if (!bitstream.getFormat(context).isInternal() + && authorizeService.authorizeActionBoolean(context, null, bitstream, Constants.READ, false)) { + email.addAttachment( + bitstreamService + .retrieve( context, bitstream), - bitstream.getName(), - bitstream.getFormat(context) - .getMIMEType()); - } - } - } - } else { - Bitstream bit = requestItem.getBitstream(); - email.addAttachment(bitstreamService.retrieve(context, bit), bit.getName(), - bit.getFormat(context).getMIMEType()); - } - } + bitstream.getName(), + bitstream.getFormat(context) + .getMIMEType()); + } + } + } + } else { + Bitstream bit = requestItem.getBitstream(); + email.addAttachment(bitstreamService.retrieve(context, bit), bit.getName(), + bit.getFormat(context).getMIMEType()); + } + } email.send(); requestItem.setAccept_request(accept); @@ -462,78 +462,78 @@ public class RequestItemServlet extends DSpaceServlet ""), me); JSPManager.showInternalError(request, response); } - } else - JSPManager.showInvalidIDError(request, response, null, -1); - } else { - processToken(context, request, response); - } + } else + JSPManager.showInvalidIDError(request, response, null, -1); + } else { + processToken(context, request, response); + } } - /* - * receive approvation and generate a letter - * get all request data by token - * send email to request user - */ - private void processAdmin(Context context, + /* + * receive approvation and generate a letter + * get all request data by token + * send email to request user + */ + private void processAdmin(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { - // Token - String token = request.getParameter("token"); - boolean free = request.getParameter("submit_free") != null; - String name = request.getParameter("name"); - String mail = request.getParameter("email"); - // get token, get register, get email template, format email, get - // message to jsp - RequestItem requestItem = requestItemService.findByToken(context, - token); + // Token + String token = request.getParameter("token"); + boolean free = request.getParameter("submit_free") != null; + String name = request.getParameter("name"); + String mail = request.getParameter("email"); + // get token, get register, get email template, format email, get + // message to jsp + RequestItem requestItem = requestItemService.findByToken(context, + token); - if (requestItem != null && free) { - try { - Item item = requestItem.getItem(); + if (requestItem != null && free) { + try { + Item item = requestItem.getItem(); - String emailRequest; - EPerson submiter = item.getSubmitter(); - if (submiter != null) { - emailRequest = submiter.getEmail(); - } else { - emailRequest = ConfigurationManager - .getProperty("mail.helpdesk"); - } - if (emailRequest == null) { - emailRequest = ConfigurationManager - .getProperty("mail.admin"); - } - Email email = Email.getEmail(I18nUtil.getEmailFilename( - context.getCurrentLocale(), "request_item.admin")); - email.addRecipient(emailRequest); + String emailRequest; + EPerson submiter = item.getSubmitter(); + if (submiter != null) { + emailRequest = submiter.getEmail(); + } else { + emailRequest = ConfigurationManager + .getProperty("mail.helpdesk"); + } + if (emailRequest == null) { + emailRequest = ConfigurationManager + .getProperty("mail.admin"); + } + Email email = Email.getEmail(I18nUtil.getEmailFilename( + context.getCurrentLocale(), "request_item.admin")); + email.addRecipient(emailRequest); - email.addArgument(requestItem.getBitstream().getName()); - email.addArgument(handleService.getCanonicalForm(item + email.addArgument(requestItem.getBitstream().getName()); + email.addArgument(handleService.getCanonicalForm(item .getHandle())); - email.addArgument(requestItem.getToken()); - email.addArgument(name); - email.addArgument(mail); + email.addArgument(requestItem.getToken()); + email.addArgument(name); + email.addArgument(mail); - email.send(); + email.send(); - log.info(LogManager.getHeader(context, "sent_adm_requestItem", - "token=" + requestItem.getToken() - + "item_id=" + item.getID())); + log.info(LogManager.getHeader(context, "sent_adm_requestItem", + "token=" + requestItem.getToken() + + "item_id=" + item.getID())); - JSPManager.showJSP(request, response, - "/requestItem/response-send.jsp"); - } catch (MessagingException me) { - log.warn(LogManager.getHeader(context, - "error_mailing_requestItem", ""), me); - JSPManager.showInternalError(request, response); - } - } else { - JSPManager.showInvalidIDError(request, response, token, -1); - } + JSPManager.showJSP(request, response, + "/requestItem/response-send.jsp"); + } catch (MessagingException me) { + log.warn(LogManager.getHeader(context, + "error_mailing_requestItem", ""), me); + JSPManager.showInternalError(request, response); + } + } else { + JSPManager.showInvalidIDError(request, response, token, -1); + } } - + /** * Get the link to the author in RequestLink email. * @@ -544,7 +544,8 @@ public class RequestItemServlet extends DSpaceServlet * * @return link based on the token * - * @throws java.sql.SQLException + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static String getLinkTokenEmail(Context context, String token) throws SQLException diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SearchResultLogServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SearchResultLogServlet.java index 50ecac3284..4ec8f3ac6a 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SearchResultLogServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SearchResultLogServlet.java @@ -26,8 +26,8 @@ import org.dspace.usage.UsageEvent; import org.dspace.usage.UsageSearchEvent; /** - * Every time a user clicks on a search result he will be redirected through this servlet - * this servlet will retrieve all query information & store this for the search statistics + * Every time a user clicks on a search result he will be redirected through this servlet. + * This servlet will retrieve all query information and store it for the search statistics * Once everything has been stored the user will be * redirected to the dso he clicked on (indicated by the redirectUrl parameter) * @@ -37,7 +37,7 @@ import org.dspace.usage.UsageSearchEvent; */ public class SearchResultLogServlet extends DSpaceServlet { - private final transient HandleService handleService + private final transient HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); @Override @@ -57,16 +57,16 @@ public class SearchResultLogServlet extends DSpaceServlet result, Arrays.asList(request.getParameterValues("query")), scope); - if(!StringUtils.isBlank(request.getParameter("rpp"))){ + if (!StringUtils.isBlank(request.getParameter("rpp"))) { searchEvent.setRpp(Integer.parseInt(request.getParameter("rpp"))); } - if(!StringUtils.isBlank(request.getParameter("sort_by"))){ + if (!StringUtils.isBlank(request.getParameter("sort_by"))) { searchEvent.setSortBy(request.getParameter("sort_by")); } - if(!StringUtils.isBlank(request.getParameter("order"))){ + if (!StringUtils.isBlank(request.getParameter("order"))) { searchEvent.setSortOrder(request.getParameter("order")); } - if(!StringUtils.isBlank(request.getParameter("page"))){ + if (!StringUtils.isBlank(request.getParameter("page"))) { searchEvent.setPage(Integer.parseInt(request.getParameter("page"))); } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SubmissionController.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SubmissionController.java index 24d6d107a8..958c8d3b0f 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SubmissionController.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/SubmissionController.java @@ -119,8 +119,8 @@ public class SubmissionController extends DSpaceServlet private static Object mutex = new Object(); /** log4j logger */ - private static Logger log = Logger - .getLogger(SubmissionController.class); + private static Logger log = + Logger.getLogger(SubmissionController.class); private static WorkspaceItemService workspaceItemService; @@ -132,12 +132,12 @@ public class SubmissionController extends DSpaceServlet @Override public void init() throws ServletException { - super.init(); - // this is a sort of HACK as we are injecting static services using the singleton nature of the servlet... - workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); - bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); - bundleService = ContentServiceFactory.getInstance().getBundleService(); - workflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService(); + super.init(); + // this is a sort of HACK as we are injecting static services using the singleton nature of the servlet... + workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); + bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); + bundleService = ContentServiceFactory.getInstance().getBundleService(); + workflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService(); } protected void doDSGet(Context context, HttpServletRequest request, @@ -179,7 +179,7 @@ public class SubmissionController extends DSpaceServlet //where the submission process now has less steps, then //we will need to reset the stepReached in the database //(Hopefully this will never happen, but just in case!) - if(getStepReached(si) >= si.getSubmissionConfig().getNumberOfSteps()) + if (getStepReached(si) >= si.getSubmissionConfig().getNumberOfSteps()) { //update Stage Reached to the last step in the Process int lastStep = si.getSubmissionConfig().getNumberOfSteps()-1; @@ -249,7 +249,7 @@ public class SubmissionController extends DSpaceServlet HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { - // Configuration of current step in Item Submission Process + // Configuration of current step in Item Submission Process SubmissionStepConfig currentStepConfig; //need to find out what type of form we are dealing with @@ -275,7 +275,7 @@ public class SubmissionController extends DSpaceServlet { log.debug("Starting doPostResumable method."); completedFile = doPostResumable(request); - } catch(IOException e){ + } catch(IOException e) { // we were unable to receive the complete chunk => initialize reupload response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); } @@ -390,10 +390,10 @@ public class SubmissionController extends DSpaceServlet // First, check for a click on "Cancel/Save" button. if (UIUtil.getSubmitButton(request, "").equals(AbstractProcessingStep.CANCEL_BUTTON)) { - // Get the current step + // Get the current step currentStepConfig = getCurrentStepConfig(request, subInfo); - // forward user to JSP which will confirm + // forward user to JSP which will confirm // the cancel/save request. doCancelOrSave(context, request, response, subInfo, currentStepConfig); @@ -464,8 +464,8 @@ public class SubmissionController extends DSpaceServlet throws ServletException, IOException, SQLException, AuthorizeException { - SubmissionStepConfig currentStepConfig = null; - + SubmissionStepConfig currentStepConfig = null; + if (subInfo.getSubmissionConfig() != null) { // get step to perform @@ -505,11 +505,11 @@ public class SubmissionController extends DSpaceServlet boolean stepFinished = stepManager.processStep(context, request, response, subInfo); //if this step is finished, continue to next step - if(stepFinished) + if (stepFinished) { // If we finished up an upload, then we need to change // the FileUploadRequest object back to a normal HTTPServletRequest - if(request instanceof FileUploadRequest) + if (request instanceof FileUploadRequest) { request = ((FileUploadRequest)request).getOriginalRequest(); } @@ -528,7 +528,7 @@ public class SubmissionController extends DSpaceServlet } catch (AuthorizeException ae) { - throw ae; + throw ae; } catch (Exception e) { @@ -582,7 +582,7 @@ public class SubmissionController extends DSpaceServlet { //if this submission is in the workflow process, //forward user back to relevant task page - if(subInfo.isInWorkflow()) + if (subInfo.isInWorkflow()) { request.setAttribute("workflow.item", subInfo.getSubmissionItem()); JSPManager.showJSP(request, response, @@ -656,7 +656,7 @@ public class SubmissionController extends DSpaceServlet //since there are pages before this one in this current step //just go backwards one page. - if(currentPageNum > 1) + if (currentPageNum > 1) { //decrease current page number AbstractProcessingStep.setCurrentPage(request, currentPageNum-1); @@ -678,13 +678,13 @@ public class SubmissionController extends DSpaceServlet currentStepConfig = getPreviousVisibleStep(request, subInfo); - if(currentStepConfig != null) + if (currentStepConfig != null) { currentStepNum = currentStepConfig.getStepNumber(); foundPrevious = true; } - if(foundPrevious) + if (foundPrevious) { //flag to JSPStepManager that we are going backwards //an entire step @@ -698,7 +698,7 @@ public class SubmissionController extends DSpaceServlet } //if there is no previous, visible step, throw an error! - if(!foundPrevious) + if (!foundPrevious) { log.error(LogManager .getHeader(context, "no_previous_visible_step", @@ -893,7 +893,7 @@ public class SubmissionController extends DSpaceServlet double currStepAndPage = Float.parseFloat(currStep+"."+currPage); double stepAndPageReached = Float.parseFloat(getStepReached(subInfo)+"."+JSPStepManager.getPageReached(subInfo)); - if (result != AbstractProcessingStep.STATUS_COMPLETE && currStepAndPage < stepAndPageReached){ + if (result != AbstractProcessingStep.STATUS_COMPLETE && currStepAndPage < stepAndPageReached) { setReachedStepAndPage(context, subInfo, currStep, currPage); } @@ -906,7 +906,7 @@ public class SubmissionController extends DSpaceServlet // forward to cancellation confirmation JSP showProgressAwareJSP(request, response, subInfo, - "/submit/cancel.jsp"); + "/submit/cancel.jsp"); } } } @@ -922,9 +922,8 @@ public class SubmissionController extends DSpaceServlet try { // call post-processing on Step (to save any inputs from JSP) - log - .debug("Cancel/Save or Jump/Previous Request: calling processing for Step: '" - + stepConfig.getProcessingClassName() + "'"); + log.debug("Cancel/Save or Jump/Previous Request: calling processing for Step: '" + + stepConfig.getProcessingClassName() + "'"); try { @@ -935,14 +934,14 @@ public class SubmissionController extends DSpaceServlet // load the JSPStepManager object for this step AbstractProcessingStep step = (AbstractProcessingStep) stepClass - .newInstance(); + .newInstance(); result = step.doProcessing(context, request, response, subInfo); } catch (Exception e) { log.error("Error loading step class'" - + stepConfig.getProcessingClassName() + "':", e); + + stepConfig.getProcessingClassName() + "':", e); JSPManager.showInternalError(request, response); } } @@ -966,6 +965,15 @@ public class SubmissionController extends DSpaceServlet * current servlet response object * @param subInfo * submission info object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ private void processCancelOrSave(Context context, HttpServletRequest request, HttpServletResponse response, @@ -978,8 +986,8 @@ public class SubmissionController extends DSpaceServlet { // re-load current step at beginning setBeginningOfStep(request, true); - doStep(context, request, response, subInfo, currentStepConfig - .getStepNumber()); + doStep(context, request, response, subInfo, + currentStepConfig.getStepNumber()); } else if (buttonPressed.equals("submit_remove")) { @@ -990,7 +998,7 @@ public class SubmissionController extends DSpaceServlet workspaceItemService.deleteAll(context, wi); JSPManager.showJSP(request, response, - "/submit/cancelled-removed.jsp"); + "/submit/cancelled-removed.jsp"); context.complete(); } @@ -1022,6 +1030,10 @@ public class SubmissionController extends DSpaceServlet * the SubmissionInfo object * @param jspPath * relative path to JSP + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ private static void showProgressAwareJSP(HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, String jspPath) @@ -1042,6 +1054,10 @@ public class SubmissionController extends DSpaceServlet * HTTP request * * @return filled-out submission info, or null + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static SubmissionInfo getSubmissionInfo(Context context, HttpServletRequest request) throws SQLException, ServletException @@ -1056,8 +1072,6 @@ public class SubmissionController extends DSpaceServlet } else { - - // Need to rebuild Submission Info from Request Parameters if (request.getParameter("workflow_id") != null) { @@ -1065,10 +1079,10 @@ public class SubmissionController extends DSpaceServlet info = SubmissionInfo.load(request, workflowItemService.find(context, workflowID)); } - else if(request.getParameter("workspace_item_id") != null) + else if (request.getParameter("workspace_item_id") != null) { int workspaceID = UIUtil.getIntParameter(request, - "workspace_item_id"); + "workspace_item_id"); info = SubmissionInfo.load(request, workspaceItemService.find(context, workspaceID)); } @@ -1084,8 +1098,8 @@ public class SubmissionController extends DSpaceServlet && (info.getSubmissionItem() == null)) { log.warn(LogManager.getHeader(context, - "cannot_load_submission_info", - "InProgressSubmission is null!")); + "cannot_load_submission_info", + "InProgressSubmission is null!")); return null; } @@ -1229,7 +1243,7 @@ public class SubmissionController extends DSpaceServlet //get previous step currentStepConfig = si.getSubmissionConfig().getStep(currentStepNum); - if(currentStepConfig.isVisible()) + if (currentStepConfig.isVisible()) { previousStep = currentStepConfig; break; @@ -1331,6 +1345,10 @@ public class SubmissionController extends DSpaceServlet * @param request * HTTP request * @return HTML hidden parameters + * @throws SQLException + * An exception that provides information on a database access error or other errors. + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ public static String getSubmissionParameters(Context context, HttpServletRequest request) throws SQLException, ServletException @@ -1344,33 +1362,33 @@ public class SubmissionController extends DSpaceServlet if ((si.getSubmissionItem() != null) && si.isInWorkflow()) { info = info - + ""; + + ""; } else if (si.getSubmissionItem() != null) { info = info - + ""; + + ""; } if (si.getBundle() != null) { info = info + ""; + + si.getBundle().getID() + "\"/>"; } if (si.getBitstream() != null) { info = info - + ""; + + ""; } if (step != null) { info = info + ""; + + step.getStepNumber() + "\"/>"; } // save the current page from the current Step Servlet @@ -1381,7 +1399,7 @@ public class SubmissionController extends DSpaceServlet // save the current JSP name to a hidden variable String jspDisplayed = JSPStepManager.getLastJSPDisplayed(request); info = info + ""; + + jspDisplayed + "\"/>"; return info; } @@ -1400,6 +1418,13 @@ public class SubmissionController extends DSpaceServlet * the SubmissionInfo object pertaining to the current submission * @param step * the step the user has just reached + * @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. */ private void userHasReached(Context c, SubmissionInfo subInfo, int step) throws SQLException, AuthorizeException, IOException @@ -1412,20 +1437,27 @@ public class SubmissionController extends DSpaceServlet { wi.setStageReached(step); wi.setPageReached(1); // reset page reached back to 1 (since - // it's page 1 of the new step) + // it's page 1 of the new step) workspaceItemService.update(c, wi); } } } /** - * Set a specific step and page as reached. - * It will also "set back" where a user has reached. - * - * @param subInfo + * Set a specific step and page as reached. + * It will also "set back" where a user has reached. + * + * @param subInfo * the SubmissionInfo object pertaining to the current submission - * @param step the step to set as reached, can be also a previous reached step - * @param page the page (within the step) to set as reached, can be also a previous reached page + * @param step the step to set as reached, can be also a previous reached step + * @param page the page (within the step) to set as reached, can be also a previous reached page + * @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. */ private void setReachedStepAndPage(Context c, SubmissionInfo subInfo, int step, int page) throws SQLException, AuthorizeException, IOException @@ -1482,6 +1514,10 @@ public class SubmissionController extends DSpaceServlet * * @throws ServletException * if there are no more pages in this step + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws FileSizeLimitExceededException + * if the file size if the uploaded item exceeded the limit */ private HttpServletRequest wrapMultipartRequest(HttpServletRequest request) throws ServletException, FileSizeLimitExceededException @@ -1523,6 +1559,8 @@ public class SubmissionController extends DSpaceServlet * current DSpace context * @param request * current servlet request object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ public void uploadFiles(Context context, HttpServletRequest request) throws ServletException @@ -1601,7 +1639,7 @@ public class SubmissionController extends DSpaceServlet String resumableIdentifier = request.getParameter("resumableIdentifier"); String resumableChunkNumber = request.getParameter("resumableChunkNumber"); long resumableCurrentChunkSize = - Long.valueOf(request.getParameter("resumableCurrentChunkSize")); + Long.valueOf(request.getParameter("resumableCurrentChunkSize")); tempDir = tempDir + File.separator + resumableIdentifier; @@ -1675,7 +1713,7 @@ public class SubmissionController extends DSpaceServlet long currentSize = 0l; // check whether all chunks were received. - if(chunkDirPathFile.exists()) + if (chunkDirPathFile.exists()) { for (int p = 1; p <= resumableTotalChunks; p++) { @@ -1748,7 +1786,7 @@ public class SubmissionController extends DSpaceServlet catch (IOException e) { // try to delete destination file, as we got an exception while writing it. - if(!destFile.delete()) + if (!destFile.delete()) { log.warn("While writing an uploaded file an error occurred. " + "We were unable to delete the damaged file: " diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/VersionHistoryServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/VersionHistoryServlet.java index 84376600ea..799beea7e1 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/VersionHistoryServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/VersionHistoryServlet.java @@ -162,8 +162,12 @@ public class VersionHistoryServlet extends DSpaceServlet * Delete the given version(s) * * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. * @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. */ private Item doDeleteVersions(HttpServletRequest request, UUID itemID, String... versionIDs) throws SQLException, @@ -179,8 +183,12 @@ public class VersionHistoryServlet extends DSpaceServlet * Restore the given version * * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. * @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. * @throws NumberFormatException */ private UUID doRestoreVersion(HttpServletRequest request, @@ -198,8 +206,12 @@ public class VersionHistoryServlet extends DSpaceServlet * Update the summary of the given version * * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. * @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. */ private UUID doUpdateVersion(HttpServletRequest request, UUID itemID, String versionID) throws SQLException, AuthorizeException, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/CollectionWizardServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/CollectionWizardServlet.java index 9a791f6222..e799d18a57 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/CollectionWizardServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/CollectionWizardServlet.java @@ -480,13 +480,20 @@ public class CollectionWizardServlet extends DSpaceServlet * process input from basic info page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response - * @param collection - * @throws SQLException + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ private void processBasicInfo(Context context, HttpServletRequest request, HttpServletResponse response) throws SQLException, @@ -616,16 +623,25 @@ public class CollectionWizardServlet extends DSpaceServlet * Work out which page to show next, and show it * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @param collection + * DSpace Collection object. * @param stage - * the stage the user just finished, or if PERMISSIONS, the - * particular permissions page - * @throws SQLException + * the stage the user just finished, or if PERMISSIONS, the + * particular permissions page * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ private void showNextPage(Context context, HttpServletRequest request, HttpServletResponse response, Collection collection, int stage) diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java index 5bc4f5e701..9bca5fffcc 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/EditCommunitiesServlet.java @@ -305,9 +305,13 @@ public class EditCommunitiesServlet extends DSpaceServlet * needed/allowed for the community edit form * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param community + * DSpace Community object. * @throws SQLException + * An exception that provides information on a database access error or other errors. */ private void storeAuthorizeAttributeCommunityEdit(Context context, HttpServletRequest request, Community community) throws SQLException @@ -363,9 +367,13 @@ public class EditCommunitiesServlet extends DSpaceServlet * needed/allowed for the collection edit form * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param community + * DSpace Community object. * @throws SQLException + * An exception that provides information on a database access error or other errors. */ static void storeAuthorizeAttributeCollectionEdit(Context context, HttpServletRequest request, Collection collection) throws SQLException diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java index e09556534c..2a544b7c8a 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java @@ -82,14 +82,14 @@ public class MetadataFieldRegistryServlet extends DSpaceServlet ResourceBundle labels = ResourceBundle.getBundle("Messages", locale); String element = request.getParameter("element"); - String scope = request.getParameter("scope_note"); + String scope = request.getParameter("scope_note"); String qual = request.getParameter("qualifier"); if ("".equals(qual)) { qual = null; } - if ("submit_update".equals(button)) + if ("submit_update".equals(button)) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) @@ -198,7 +198,7 @@ public class MetadataFieldRegistryServlet extends DSpaceServlet } else { - schema = schemaService.find(context, schemaID); + schema = schemaService.find(context, schemaID); for (int ii = 0; ii < param.length; ii++) { int fieldID = Integer.parseInt(param[ii]); @@ -253,16 +253,21 @@ public class MetadataFieldRegistryServlet extends DSpaceServlet * Show list of DC type * * @param context - * Current DSpace context + * The relevant DSpace Context. * @param request - * Current HTTP request + * Servlet's HTTP request object. * @param response - * Current HTTP response + * Servlet's HTTP response object. * @param schemaID * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ private void showTypes(Context context, HttpServletRequest request, HttpServletResponse response, MetadataSchema schema) @@ -291,6 +296,7 @@ public class MetadataFieldRegistryServlet extends DSpaceServlet * description. * * @param request + * Servlet's HTTP request object. * @param labels * @return true of false */ @@ -329,7 +335,7 @@ public class MetadataFieldRegistryServlet extends DSpaceServlet for (int ii = 0; ii < qualifier.length(); ii++) { if (qualifier.charAt(ii) == '.' || qualifier.charAt(ii) == '_' - || qualifier.charAt(ii) == ' ') + || qualifier.charAt(ii) == ' ') { return error(request, labels.getString(clazz + ".badqualchar")); @@ -344,8 +350,10 @@ public class MetadataFieldRegistryServlet extends DSpaceServlet * Bind the error text to the request object. * * @param request + * Servlet's HTTP request object. * @param text - * @return false + * Error text + * @return false - always false */ private boolean error(HttpServletRequest request, String text) { diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataSchemaRegistryServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataSchemaRegistryServlet.java index 727cfde00b..54e94c4045 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataSchemaRegistryServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/MetadataSchemaRegistryServlet.java @@ -191,15 +191,17 @@ public class MetadataSchemaRegistryServlet extends DSpaceServlet * Show list of DC type * * @param context - * Current DSpace context + * The relevant DSpace Context. * @param request - * Current HTTP request + * Servlet's HTTP request object. * @param response - * Current HTTP response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. * @throws SQLException - * @throws IOException + * An exception that provides information on a database access error or other errors. */ private void showSchemas(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/PrivateItemsServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/PrivateItemsServlet.java index dded39dba7..1fcc343b1e 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/PrivateItemsServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/PrivateItemsServlet.java @@ -79,12 +79,20 @@ public class PrivateItemsServlet extends AbstractBrowserServlet * Display the error page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -99,12 +107,20 @@ public class PrivateItemsServlet extends AbstractBrowserServlet * Display the No Results page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -121,12 +137,20 @@ public class PrivateItemsServlet extends AbstractBrowserServlet * that match that metadata value * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -140,12 +164,20 @@ public class PrivateItemsServlet extends AbstractBrowserServlet * Display a full item listing. * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/WithdrawnBrowserServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/WithdrawnBrowserServlet.java index 88ed31e82e..1e69f27c2f 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/WithdrawnBrowserServlet.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/admin/WithdrawnBrowserServlet.java @@ -74,12 +74,20 @@ public class WithdrawnBrowserServlet extends AbstractBrowserServlet * Display the error page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -94,12 +102,20 @@ public class WithdrawnBrowserServlet extends AbstractBrowserServlet * Display the No Results page * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -116,12 +132,20 @@ public class WithdrawnBrowserServlet extends AbstractBrowserServlet * that match that metadata value * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, @@ -135,12 +159,20 @@ public class WithdrawnBrowserServlet extends AbstractBrowserServlet * Display a full item listing. * * @param context + * The relevant DSpace Context. * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @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. */ protected void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStep.java b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStep.java index 456eaac293..9c34c7ef8c 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStep.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStep.java @@ -85,6 +85,15 @@ public abstract class JSPStep * current servlet response object * @param subInfo * submission info object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 abstract void doPreProcessing(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -113,6 +122,15 @@ public abstract class JSPStep * submission info object * @param status * any status/errors reported by doProcessing() method + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 abstract void doPostProcessing(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, int status) @@ -136,6 +154,7 @@ public abstract class JSPStep * current servlet response object * @param subInfo * submission info object + * @return URL path of the JSP to review this step's information */ public abstract String getReviewJSP(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo); diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStepManager.java b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStepManager.java index 01237b7b6a..4084823465 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStepManager.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/JSPStepManager.java @@ -74,6 +74,7 @@ public class JSPStepManager * @throws Exception * if the JSPStep cannot be loaded or the class * specified doesn't implement the JSPStep interface + * @return JSPStepManager instance */ public static JSPStepManager loadStep(SubmissionStepConfig stepConfig) throws Exception { @@ -93,16 +94,17 @@ public class JSPStepManager Object stepInstance = stepClass.newInstance(); - if(stepInstance instanceof AbstractProcessingStep) + if (stepInstance instanceof AbstractProcessingStep) { // load the JSPStep interface for this step stepManager.stepProcessing = (AbstractProcessingStep) stepClass.newInstance(); } else { - throw new Exception("The submission step class specified by '" + stepConfig.getProcessingClassName() + - "' does not extend the class org.dspace.submit.AbstractProcessingStep!" + - " Therefore it cannot be used by the Configurable Submission as the !"); + throw new Exception( + "The submission step class specified by '" + stepConfig.getProcessingClassName() + + "' does not extend the class org.dspace.submit.AbstractProcessingStep!" + + " Therefore it cannot be used by the Configurable Submission as the !"); } @@ -110,24 +112,24 @@ public class JSPStepManager * Next, load the step's JSPUI binding class (using the current class loader) * (Only load JSPUI binding class if specified...otherwise this is a non-interactive step) */ - if(stepConfig.getJSPUIClassName()!=null && stepConfig.getJSPUIClassName().length()>0) + if (stepConfig.getJSPUIClassName()!=null && stepConfig.getJSPUIClassName().length()>0) { - stepClass = loader - .loadClass(stepConfig.getJSPUIClassName()); + stepClass = loader.loadClass(stepConfig.getJSPUIClassName()); - stepInstance = stepClass.newInstance(); + stepInstance = stepClass.newInstance(); - if(stepInstance instanceof JSPStep) - { - // load the JSPStep interface for this step - stepManager.stepJSPUI = (JSPStep) stepClass.newInstance(); - } - else - { - throw new Exception("The submission step class specified by '" + stepConfig.getJSPUIClassName() + - "' does not extend the class org.dspace.app.webui.JSPStep!" + - " Therefore it cannot be used by the Configurable Submission for the JSP user interface!"); - } + if (stepInstance instanceof JSPStep) + { + // load the JSPStep interface for this step + stepManager.stepJSPUI = (JSPStep) stepClass.newInstance(); + } + else + { + throw new Exception( + "The submission step class specified by '" + stepConfig.getJSPUIClassName() + + "' does not extend the class org.dspace.app.webui.JSPStep!" + + " Therefore it cannot be used by the Configurable Submission for the JSP user interface!"); + } } return stepManager; } @@ -188,8 +190,8 @@ public class JSPStepManager .booleanValue()) { // current page should be the LAST page in this step - currentPage = getNumPagesInProgressBar(subInfo, this.stepConfig - .getStepNumber()); + currentPage = getNumPagesInProgressBar(subInfo, + this.stepConfig.getStepNumber()); AbstractProcessingStep.setCurrentPage(request, currentPage); } @@ -235,8 +237,8 @@ public class JSPStepManager * Determine whether we are Starting or Finishing this Step */ // check if we just started this step - boolean beginningOfStep = SubmissionController - .isBeginningOfStep(request); + boolean beginningOfStep = + SubmissionController.isBeginningOfStep(request); // if this step has just been started, do beginning processing if (beginningOfStep) @@ -266,7 +268,15 @@ public class JSPStepManager * * @return true if the step is completed (no JSP was loaded), false * otherwise - * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ private boolean doStepStart(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -277,7 +287,7 @@ public class JSPStepManager // first, do any pre-processing and get the JSP to display // (assuming that this step has an interface) - if(stepJSPUI!=null) + if (stepJSPUI != null) { stepJSPUI.doPreProcessing(context, request, response, subInfo); } @@ -295,7 +305,7 @@ public class JSPStepManager // and forward back to the Submission Controller servlet log.debug("Calling processing for step " - + this.getClass().getName()); + + this.getClass().getName()); int errorFlag = stepProcessing.doProcessing(context, request, response, subInfo); // if it didn't complete successfully, try and log this error! @@ -308,11 +318,11 @@ public class JSPStepManager if (errorMessage == null) { errorMessage = "The doProcessing() method for " - + this.getClass().getName() - + " returned an error flag = " - + errorFlag - + ". " - + "It is recommended to define a custom error message for this error flag using the addErrorMessage() method!"; + + this.getClass().getName() + + " returned an error flag = " + + errorFlag + + ". " + + "It is recommended to define a custom error message for this error flag using the addErrorMessage() method!"; } log.error(errorMessage); @@ -338,7 +348,12 @@ public class JSPStepManager * submission info object * @param pathToJSP * context path to the JSP to display - * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ public static final void showJSP(HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, @@ -385,7 +400,15 @@ public class JSPStepManager * @param subInfo * submission info object * @return true if the step is completed (successfully), false otherwise - * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ private boolean doStepEnd(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -457,6 +480,15 @@ public class JSPStepManager * submission info object * * @return true if step completed (successfully), false otherwise + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ protected final boolean completeStep(Context context, HttpServletRequest request, HttpServletResponse response, @@ -505,10 +537,11 @@ public class JSPStepManager * The current submission information object * @param pageNumber * The current page + * @return true if there are more pages in the current step after the + * current page * * @throws ServletException * if there are no more pages in this step - * */ protected final boolean hasMorePages(HttpServletRequest request, SubmissionInfo subInfo, int pageNumber) throws ServletException @@ -551,6 +584,13 @@ public class JSPStepManager * increment the page reached) * @param pageNumber * new page reached + * @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. */ private void updatePageReached(Context context, SubmissionInfo subInfo, int page) throws SQLException, AuthorizeException, IOException @@ -561,8 +601,8 @@ public class JSPStepManager if (page > wi.getPageReached()) { - WorkspaceItemService wis = ContentServiceFactory.getInstance() - .getWorkspaceItemService(); + WorkspaceItemService wis = ContentServiceFactory.getInstance() + .getWorkspaceItemService(); wi.setPageReached(page); wis.update(context, wi); } @@ -680,6 +720,7 @@ public class JSPStepManager * current servlet response object * @param subInfo * submission info object + * @return URL path of the JSP to review this step's information */ public String getReviewJSP(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPAccessStep.java b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPAccessStep.java index 229b22225b..a9a3ce68e9 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPAccessStep.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPAccessStep.java @@ -159,6 +159,8 @@ public class JSPAccessStep extends JSPStep * The current submission information object * * @return the number of pages in this step + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ public int getNumberOfPages(HttpServletRequest request, SubmissionInfo subInfo) throws ServletException diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPDescribeStep.java b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPDescribeStep.java index f367852eb2..b07d91cdfc 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPDescribeStep.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPDescribeStep.java @@ -74,7 +74,12 @@ public class JSPDescribeStep extends JSPStep /** log4j logger */ private static Logger log = Logger.getLogger(JSPDescribeStep.class); - /** Constructor */ + /** + * Constructor + * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + */ public JSPDescribeStep() throws ServletException { //just call DescribeStep's constructor @@ -103,6 +108,15 @@ public class JSPDescribeStep extends JSPStep * current servlet response object * @param subInfo * submission info object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 doPreProcessing(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -135,6 +149,15 @@ public class JSPDescribeStep extends JSPStep * submission info object * @param status * any status/errors reported by doProcessing() method + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 doPostProcessing(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, int status) @@ -193,7 +216,12 @@ public class JSPDescribeStep extends JSPStep * the response object * @param subInfo * the SubmissionInfo object - * + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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. */ private void showEditMetadata(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPSampleStep.java b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPSampleStep.java index 3f66c2a15e..b8f1c4cd68 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPSampleStep.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPSampleStep.java @@ -33,15 +33,15 @@ import org.dspace.submit.step.SampleStep; * processing class! *

    * This step can be added to any Submission process (for testing purposes) by - * adding the following to the appropriate tag in the + * adding the following to the appropriate <submission-processi> tag in the * /config/item-submission.xml: * - * - * Sample - * org.dspace.submit.step.SampleStep - * org.dspace.app.webui.submit.step.JSPSampleStep - * true - * + * <step> + * <heading>Sample</heading> + * <processing-class>org.dspace.submit.step.SampleStep</processing-class> + * <jspui-binding>org.dspace.app.webui.submit.step.JSPSampleStep</jspui-binding> + * <workflow-editable>true</workflow-editable> + * </step> * *

    * The following methods are called in this order: @@ -99,6 +99,15 @@ public class JSPSampleStep extends JSPStep * current servlet response object * @param subInfo * submission info object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 doPreProcessing(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -327,6 +336,8 @@ public class JSPSampleStep extends JSPStep * The current submission information object * * @return the number of pages in this step + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. */ public int getNumberOfPages(HttpServletRequest request, SubmissionInfo subInfo) throws ServletException diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPUploadStep.java b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPUploadStep.java index eaa71cccfb..83a3e9e189 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPUploadStep.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/submit/step/JSPUploadStep.java @@ -236,11 +236,11 @@ public class JSPUploadStep extends JSPStep for (Bundle bnd : bundles) { - fileAlreadyUploaded = bnd.getBitstreams().size() > 0; - if (fileAlreadyUploaded) - { - break; - } + fileAlreadyUploaded = bnd.getBitstreams().size() > 0; + if (fileAlreadyUploaded) + { + break; + } } // if user already has uploaded at least one file @@ -255,7 +255,7 @@ public class JSPUploadStep extends JSPStep } //If upload failed in JSPUI (just came from upload-error.jsp), user can retry the upload - if(buttonPressed.equalsIgnoreCase("submit_retry")) + if (buttonPressed.equalsIgnoreCase("submit_retry")) { showUploadPage(context, request, response, subInfo, false); } @@ -278,7 +278,7 @@ public class JSPUploadStep extends JSPStep // There was a problem uploading the file! //First, check if we just removed our uploaded file - if(buttonPressed.startsWith("submit_remove_")) + if (buttonPressed.startsWith("submit_remove_")) { //if file was just removed, go back to upload page showUploadPage(context, request, response, subInfo, false); @@ -468,6 +468,12 @@ public class JSPUploadStep extends JSPStep * the SubmissionInfo object * @param justUploaded * true, if the user just finished uploading a file + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 showUploadPage(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo, @@ -481,14 +487,14 @@ public class JSPUploadStep extends JSPStep if (!justUploaded) { - for (Bundle bnd : bundles) - { - fileAlreadyUploaded = bnd.getBitstreams().size() > 0; - if (fileAlreadyUploaded) - { - break; - } - } + for (Bundle bnd : bundles) + { + fileAlreadyUploaded = bnd.getBitstreams().size() > 0; + if (fileAlreadyUploaded) + { + break; + } + } } // if user already has uploaded at least one file @@ -496,7 +502,7 @@ public class JSPUploadStep extends JSPStep { // The item already has files associated with it. showUploadFileList(context, request, response, subInfo, - justUploaded, false); + justUploaded, false); } else { @@ -516,6 +522,12 @@ public class JSPUploadStep extends JSPStep * the response object * @param subInfo * the SubmissionInfo object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 showChooseFile(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -525,10 +537,9 @@ public class JSPUploadStep extends JSPStep "webui.submission.sherparomeo-policy-enabled", true)) { SHERPASubmitService sherpaSubmitService = new DSpace() - .getSingletonService(SHERPASubmitService.class); + .getSingletonService(SHERPASubmitService.class); request.setAttribute("sherpa", sherpaSubmitService - .hasISSNs(context, subInfo.getSubmissionItem() - .getItem())); + .hasISSNs(context, subInfo.getSubmissionItem().getItem())); } // set to null the bitstream in subInfo, we need to process a new file @@ -558,6 +569,12 @@ public class JSPUploadStep extends JSPStep * pass in true if the user just successfully uploaded a file * @param showChecksums * pass in true if checksums should be displayed + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 showUploadFileList(Context context, HttpServletRequest request, HttpServletResponse response, @@ -598,6 +615,12 @@ public class JSPUploadStep extends JSPStep * the response object * @param subInfo * the SubmissionInfo object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 showGetFileFormat(Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) @@ -617,8 +640,8 @@ public class JSPUploadStep extends JSPStep request.setAttribute("bitstream.formats", formats); // What does the system think it is? - BitstreamFormat guess = bitstreamFormatService.guessFormat(context, subInfo - .getBitstream()); + BitstreamFormat guess = bitstreamFormatService.guessFormat(context, + subInfo.getBitstream()); request.setAttribute("guessed.format", guess); @@ -638,6 +661,12 @@ public class JSPUploadStep extends JSPStep * the response object * @param subInfo * the SubmissionInfo object + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @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 showFileDescription(Context context, HttpServletRequest request, HttpServletResponse response, diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/Authenticate.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/Authenticate.java index e6606be5c2..68625c5596 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/Authenticate.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/Authenticate.java @@ -54,12 +54,12 @@ public class Authenticate private static EPersonService personService; private static synchronized void initialize() { - if (initialized) { - return; - } - authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); - authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - personService = EPersonServiceFactory.getInstance().getEPersonService(); + if (initialized) { + return; + } + authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); + authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + personService = EPersonServiceFactory.getInstance().getEPersonService(); } /** @@ -75,15 +75,15 @@ public class Authenticate */ public static HttpServletRequest getRealRequest(HttpServletRequest request) { - initialize(); - + initialize(); + HttpSession session = request.getSession(); if (session.getAttribute("resuming.request") != null) { // Get info about the interrupted request RequestInfo requestInfo = (RequestInfo) session - .getAttribute("interrupted.request.info"); + .getAttribute("interrupted.request.info"); HttpServletRequest actualRequest; @@ -125,15 +125,17 @@ public class Authenticate * current HTTP request * @param response * HTTP response + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void resumeInterruptedRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { - initialize(); - + initialize(); + HttpSession session = request.getSession(); String originalURL = (String) session - .getAttribute("interrupted.request.url"); + .getAttribute("interrupted.request.url"); if (originalURL == null) { @@ -170,13 +172,17 @@ public class Authenticate * current HTTP response * * @return true if authentication is already finished (implicit method) + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static boolean startAuthentication(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - initialize(); - + initialize(); + HttpSession session = request.getSession(); /* @@ -191,11 +197,11 @@ public class Authenticate { loggedIn(context, request, context.getCurrentUser()); log.info(LogManager.getHeader(context, "login", "type=implicit")); - if(context.getCurrentUser() != null){ + if (context.getCurrentUser() != null) { //We have a new user Authenticate.resumeInterruptedRequest(request, response); return false; - }else{ + } else { //Couldn't log & authentication finished return true; } @@ -214,8 +220,8 @@ public class Authenticate session.setAttribute("interrupted.request.info", info); // Store the URL of the request that led to authentication - session.setAttribute("interrupted.request.url", UIUtil - .getOriginalURL(request)); + session.setAttribute("interrupted.request.url", + UIUtil.getOriginalURL(request)); /* * Grovel over authentication methods, counting the @@ -263,8 +269,8 @@ public class Authenticate HttpServletRequest request, EPerson eperson) { - initialize(); - + initialize(); + HttpSession session = request.getSession(); // For security reasons after login, give the user a new session @@ -280,7 +286,7 @@ public class Authenticate String requestUrl = (String) session.getAttribute("interrupted.request.url"); // Invalidate session unless dspace.cfg says not to - if(ConfigurationManager.getBooleanProperty("webui.session.invalidate", true)) + if (ConfigurationManager.getBooleanProperty("webui.session.invalidate", true)) { session.invalidate(); } @@ -333,7 +339,7 @@ public class Authenticate // and the remote IP address to compare against later requests // so we can detect session hijacking. session.setAttribute("dspace.current.remote.addr", - request.getRemoteAddr()); + request.getRemoteAddr()); } @@ -344,12 +350,13 @@ public class Authenticate * DSpace context * @param request * HTTP request - * @throws SQLException + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static void loggedOut(Context context, HttpServletRequest request) throws SQLException { - initialize(); - + initialize(); + HttpSession session = request.getSession(); context.setCurrentUser(null); @@ -363,8 +370,8 @@ public class Authenticate Locale sessionLocale = UIUtil.getSessionLocale(request); // Invalidate session unless dspace.cfg says not to (or it is a loggedOut from a loginAs) - if(ConfigurationManager.getBooleanProperty("webui.session.invalidate", true) - && previousUserID != null) + if (ConfigurationManager.getBooleanProperty("webui.session.invalidate", true) + && previousUserID != null) { session.invalidate(); } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/CollectionStyleSelection.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/CollectionStyleSelection.java index 262ba732e3..ddcec56fab 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/CollectionStyleSelection.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/CollectionStyleSelection.java @@ -44,7 +44,7 @@ public class CollectionStyleSelection extends AKeyBasedStyleSelection { Collection c = item.getOwningCollection(); - if(c!=null) + if (c != null) { // Style specified & exists return getFromMap(c.getHandle()); @@ -65,7 +65,7 @@ public class CollectionStyleSelection extends AKeyBasedStyleSelection // Get all properties starting with "webui.itemdisplay" List keys = configurationService.getPropertyKeys("webui.itemdisplay"); - for(String key: keys) + for (String key: keys) { if (key.endsWith(".collections")) { @@ -88,6 +88,7 @@ public class CollectionStyleSelection extends AKeyBasedStyleSelection * Check for the style configuration: return the default style if no configuration has found. * * @param handle + * target handle to get style for * @return the specific style or the default if not properly defined */ public String getFromMap(String handle) diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/FileUploadRequest.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/FileUploadRequest.java index bc1165f5e7..2d7293d8a9 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/FileUploadRequest.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/FileUploadRequest.java @@ -52,6 +52,10 @@ public class FileUploadRequest extends HttpServletRequestWrapper * * @param req * the original request + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws FileSizeLimitExceededException + * if the file size if the uploaded item exceeded the limit */ public FileUploadRequest(HttpServletRequest req) throws IOException, FileSizeLimitExceededException { @@ -104,7 +108,7 @@ public class FileUploadRequest extends HttpServletRequestWrapper String chunkPath = chunkDirPath + File.separator + "part" + parameters.get("resumableChunkNumber"); File fileDir = new File(chunkDirPath); - if(fileDir.exists()) + if (fileDir.exists()) { item.write(new File(chunkPath)); } @@ -126,7 +130,7 @@ public class FileUploadRequest extends HttpServletRequestWrapper } } } - catch(IOFileUploadException e){ + catch(IOFileUploadException e) { if (!(e.getMessage().contains("Stream ended unexpectedly"))) { throw new IOException(e.getMessage(), e); @@ -134,7 +138,7 @@ public class FileUploadRequest extends HttpServletRequestWrapper } catch (Exception e) { - if(e.getMessage().contains("exceeds the configured maximum")) + if (e.getMessage().contains("exceeds the configured maximum")) { // ServletFileUpload is not throwing the correct error, so this is workaround // the request was rejected because its size (11302) exceeds the configured maximum (536) diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/JSPManager.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/JSPManager.java index 8838da68c4..d161ef08ed 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/JSPManager.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/JSPManager.java @@ -45,6 +45,10 @@ public class JSPManager * current servlet response object * @param jsp * the JSP page to display, relative to the webapps directory + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void showJSP(HttpServletRequest request, HttpServletResponse response, String jsp) throws ServletException, @@ -53,7 +57,7 @@ public class JSPManager if (log.isDebugEnabled()) { log.debug(LogManager.getHeader((Context) request - .getAttribute("dspace.context"), "view_jsp", jsp)); + .getAttribute("dspace.context"), "view_jsp", jsp)); } try { // For the moment, a simple forward @@ -70,6 +74,10 @@ public class JSPManager * the HTTP request * @param response * the HTTP response + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void showInternalError(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException @@ -86,6 +94,10 @@ public class JSPManager * the HTTP request * @param response * the HTTP response + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void showIntegrityError(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException @@ -105,6 +117,10 @@ public class JSPManager * @param exception * the AuthorizeException leading to this error, passing in * null will display default error message + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void showAuthorizeError(HttpServletRequest request, HttpServletResponse response, AuthorizeException exception) @@ -130,6 +146,10 @@ public class JSPManager * the type of object, from * org.dspace.core.Constants, or -1 * for a default message + * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void showInvalidIDError(HttpServletRequest request, HttpServletResponse response, String badID, int type) @@ -150,13 +170,21 @@ public class JSPManager * Display a "file upload was too large" error message. Passing in information * about the size of the file uploaded, and the maximum file size limit so * the user knows why they encountered an error. + * * @param request + * Servlet's HTTP request object. * @param response + * Servlet's HTTP response object. * @param message + * Error message * @param actualSize + * The actual file size. * @param permittedSize + * Maximum allowed file size. * @throws ServletException + * A general exception a servlet can throw when it encounters difficulty. * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void showFileSizeLimitExceededError(HttpServletRequest request, HttpServletResponse response, String message, long actualSize, long permittedSize) throws ServletException, IOException diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/StyleSelection.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/StyleSelection.java index b97cf6b7cd..82a5465365 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/StyleSelection.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/StyleSelection.java @@ -22,8 +22,10 @@ public interface StyleSelection * Define which display style use for the item. * * @param item + * The DSpace Item to operate on. * @return the style name to use for display simple metadata of the item * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public String getStyleForItem(Item item) throws SQLException; @@ -32,6 +34,7 @@ public interface StyleSelection * The configuration has the following syntax: schema.element[.qualifier|.*][(display-option)] * * @param style + * configuration of display style for item * @return An array of Strings each containing a metadata field and if given a display option. */ public String[] getConfigurationForStyle(String style); diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java index 953c891b23..d19cd7e559 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/UIUtil.java @@ -71,28 +71,28 @@ public class UIUtil extends Util public static final Logger log = Logger.getLogger(UIUtil.class); /** - * Pattern used to get file.ext from filename (which can be a path) - */ - private static Pattern p = Pattern.compile("[^/]*$"); - - private static boolean initialized = false; - - private static AuthenticationService authenticationService; - private static EPersonService personService; - private static IdentifierService identifierService; - private static DOIService doiService; - private static HandleService handleService; - - private static synchronized void initialize() { - if (initialized) { - return; - } - authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); - doiService = IdentifierServiceFactory.getInstance().getDOIService(); - handleService = HandleServiceFactory.getInstance().getHandleService(); - identifierService = IdentifierServiceFactory.getInstance().getIdentifierService(); - personService = EPersonServiceFactory.getInstance().getEPersonService(); - } + * Pattern used to get file.ext from filename (which can be a path) + */ + private static Pattern p = Pattern.compile("[^/]*$"); + + private static boolean initialized = false; + + private static AuthenticationService authenticationService; + private static EPersonService personService; + private static IdentifierService identifierService; + private static DOIService doiService; + private static HandleService handleService; + + private static synchronized void initialize() { + if (initialized) { + return; + } + authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); + doiService = IdentifierServiceFactory.getInstance().getDOIService(); + handleService = HandleServiceFactory.getInstance().getHandleService(); + identifierService = IdentifierServiceFactory.getInstance().getIdentifierService(); + personService = EPersonServiceFactory.getInstance().getEPersonService(); + } /** * Obtain a new context object. If a context object has already been created @@ -104,11 +104,13 @@ public class UIUtil extends Util * the HTTP request * * @return a context object + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static Context obtainContext(HttpServletRequest request) throws SQLException { - initialize(); + initialize(); //Set encoding to UTF-8, if not set yet //This avoids problems of using the HttpServletRequest @@ -117,7 +119,7 @@ public class UIUtil extends Util //non-UTF-8 encoding. try { - if(request.getCharacterEncoding()==null) + if (request.getCharacterEncoding()==null) { request.setCharacterEncoding(Constants.DEFAULT_ENCODING); } @@ -145,15 +147,15 @@ public class UIUtil extends Util String remAddr = (String)session.getAttribute("dspace.current.remote.addr"); if (remAddr != null && remAddr.equals(request.getRemoteAddr())) { - EPerson e = personService.find(c, userID); + EPerson e = personService.find(c, userID); - Authenticate.loggedIn(c, request, e); + Authenticate.loggedIn(c, request, e); } else { - log.warn("POSSIBLE HIJACKED SESSION: request from "+ - request.getRemoteAddr()+" does not match original "+ - "session address: "+remAddr+". Authentication rejected."); + log.warn("POSSIBLE HIJACKED SESSION: request from " + + request.getRemoteAddr()+" does not match original " + + "session address: "+remAddr+". Authentication rejected."); } } @@ -171,17 +173,17 @@ public class UIUtil extends Util if (useProxies == null) { useProxies = ConfigurationManager.getBooleanProperty("useProxies", false); } - if(useProxies && request.getHeader("X-Forwarded-For") != null) + if (useProxies && request.getHeader("X-Forwarded-For") != null) { /* This header is a comma delimited list */ - for(String xfip : request.getHeader("X-Forwarded-For").split(",")) + for(String xfip : request.getHeader("X-Forwarded-For").split(",")) { - if(!request.getHeader("X-Forwarded-For").contains(ip)) + if (!request.getHeader("X-Forwarded-For").contains(ip)) { ip = xfip.trim(); } } - } + } c.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip); // Store the context in the request @@ -206,11 +208,14 @@ public class UIUtil extends Util * If no identifier is found this method returns null. If no handle but a * DOI is found the first value of the array is null. * - * @param ctx DSpace Context - * @param item the item + * @param ctx + * The relevant DSpace Context. + * @param item + * Which DSpace Item to operate on. * @return string array containing URL or null if no ID found; string - array contains null if no handle, but a DOI is found + array contains null if no handle, but a DOI is found * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static String[] getItemIdentifier(Context ctx, Item item) throws SQLException @@ -273,8 +278,8 @@ public class UIUtil extends Util */ public static Community getCommunityLocation(HttpServletRequest request) { - initialize(); - + initialize(); + return ((Community) request.getAttribute("dspace.community")); } @@ -290,8 +295,8 @@ public class UIUtil extends Util */ public static Collection getCollectionLocation(HttpServletRequest request) { - initialize(); - + initialize(); + return ((Collection) request.getAttribute("dspace.collection")); } @@ -306,8 +311,8 @@ public class UIUtil extends Util */ public static void storeOriginalURL(HttpServletRequest request) { - initialize(); - + initialize(); + String orig = (String) request.getAttribute("dspace.original.url"); if (orig == null) @@ -333,8 +338,8 @@ public class UIUtil extends Util */ public static String getOriginalURL(HttpServletRequest request) { - initialize(); - + initialize(); + // Make sure there's a URL in the attribute storeOriginalURL(request); @@ -357,8 +362,8 @@ public class UIUtil extends Util */ public static String displayDate(DCDate d, boolean time, boolean localTime, HttpServletRequest request) { - initialize(); - + initialize(); + return d.displayDate(time, localTime, getSessionLocale(request)); } @@ -372,8 +377,8 @@ public class UIUtil extends Util */ public static String getRequestLogInfo(HttpServletRequest request) { - initialize(); - + initialize(); + StringBuilder report = new StringBuilder(); report.append("-- URL Was: ").append(getOriginalURL(request)).append("\n").toString(); @@ -397,7 +402,7 @@ public class UIUtil extends Util else { report.append("-- ").append(name).append(": \"") - .append(request.getParameter(name)).append("\"\n"); + .append(request.getParameter(name)).append("\"\n"); } } @@ -420,8 +425,8 @@ public class UIUtil extends Util public static Locale getSessionLocale(HttpServletRequest request) { - initialize(); - + initialize(); + String paramLocale = request.getParameter("locale"); Locale sessionLocale = null; Locale supportedLocale = null; @@ -479,8 +484,8 @@ public class UIUtil extends Util */ public static void sendAlert(HttpServletRequest request, Exception exception) { - initialize(); - + initialize(); + String logInfo = UIUtil.getRequestLogInfo(request); Context c = (Context) request.getAttribute("dspace.context"); Locale locale = getSessionLocale(request); @@ -546,71 +551,73 @@ public class UIUtil extends Util } /** - * Evaluate filename and client and encode appropriate disposition - * - * @param filename - * @param request - * @param response - * @throws UnsupportedEncodingException - */ - public static void setBitstreamDisposition(String filename, HttpServletRequest request, - HttpServletResponse response) - { - initialize(); - - String name = filename; + * Evaluate filename and client and encode appropriate disposition + * + * @param filename + * file name to evenluate + * @param request + * Servlet's HTTP request object. + * @param response + * Servlet's HTTP response object. + */ + public static void setBitstreamDisposition(String filename, HttpServletRequest request, + HttpServletResponse response) + { + initialize(); + + String name = filename; - Matcher m = p.matcher(name); + Matcher m = p.matcher(name); - if (m.find() && !m.group().equals("")) - { - name = m.group(); - } + if (m.find() && !m.group().equals("")) + { + name = m.group(); + } - try - { - String agent = request.getHeader("USER-AGENT"); + try + { + String agent = request.getHeader("USER-AGENT"); - if (null != agent && -1 != agent.indexOf("MSIE")) - { - name = URLEncoder.encode(name, "UTF8"); - } - else if (null != agent && -1 != agent.indexOf("Mozilla")) - { - name = MimeUtility.encodeText(name, "UTF8", "B"); - } + if (null != agent && -1 != agent.indexOf("MSIE")) + { + name = URLEncoder.encode(name, "UTF8"); + } + else if (null != agent && -1 != agent.indexOf("Mozilla")) + { + name = MimeUtility.encodeText(name, "UTF8", "B"); + } - } - catch (UnsupportedEncodingException e) - { - log.error(e.getMessage(),e); - } - finally - { - response.setHeader("Content-Disposition", "attachment;filename=" + name); - } - } - - /** - * Generate the (X)HTML required to show the item marking. Based on the markType it tries to find - * the corresponding item marking Strategy on the item_marking.xml Spring configuration file in order - * to apply it to the item. - * This method is used in BrowseListTag and ItemListTag to du the actual item marking in browse - * and search results - * - * @param hrq The servlet request - * @param dso The DSpaceObject to mark (it can be a BrowseItem or an Item) - * @param markType the type of the mark. - * @return (X)HTML markup - * @throws JspException - */ + } + catch (UnsupportedEncodingException e) + { + log.error(e.getMessage(),e); + } + finally + { + response.setHeader("Content-Disposition", "attachment;filename=" + name); + } + } + + /** + * Generate the (X)HTML required to show the item marking. Based on the markType it tries to find + * the corresponding item marking Strategy on the item_marking.xml Spring configuration file in order + * to apply it to the item. + * This method is used in BrowseListTag and ItemListTag to du the actual item marking in browse + * and search results + * + * @param hrq The servlet request + * @param dso The DSpaceObject to mark (it can be a BrowseItem or an Item) + * @param markType the type of the mark. + * @return (X)HTML markup + * @throws JspException on a database error. + */ public static String getMarkingMarkup(HttpServletRequest hrq, DSpaceObject dso, String markType) throws JspException { - initialize(); - - try - { + initialize(); + + try + { String contextPath = hrq.getContextPath(); Context c = UIUtil.obtainContext(hrq); @@ -620,79 +627,79 @@ public class UIUtil extends Util String mark = markType.replace("mark_", ""); ItemMarkingExtractor markingExtractor = DSpaceServicesFactory.getInstance().getServiceManager() - .getServiceByName( - ItemMarkingExtractor.class.getName()+"."+mark, - ItemMarkingExtractor.class); + .getServiceByName( + ItemMarkingExtractor.class.getName() + "." + mark, + ItemMarkingExtractor.class); - if (markingExtractor == null){ // In case we cannot find the corresponding extractor (strategy) in xml beans - return ""; + if (markingExtractor == null) { // In case we cannot find the corresponding extractor (strategy) in xml beans + return ""; } ItemMarkingInfo markInfo = markingExtractor.getItemMarkingInfo(c, item); - if (markInfo == null){ - return ""; + if (markInfo == null) { + return ""; } StringBuffer markFrag = new StringBuffer(); String localizedTooltip = null; - if (markInfo.getTooltip()!=null){ - localizedTooltip = org.dspace.core.I18nUtil.getMessage(markInfo.getTooltip(), hrq.getLocale()); + if (markInfo.getTooltip() != null) { + localizedTooltip = org.dspace.core.I18nUtil.getMessage(markInfo.getTooltip(), hrq.getLocale()); } - + String markLink = markInfo.getLink(); - if (markInfo.getImageName()!=null){ - - //Link - if (StringUtils.isNotEmpty(markLink)){ - markFrag.append(""); - } - - markFrag.append(""); - - //Link - if (StringUtils.isNotEmpty(markLink)){ - markFrag.append(""); - } + if (markInfo.getImageName() != null) { + + //Link + if (StringUtils.isNotEmpty(markLink)) { + markFrag.append(""); + } + + markFrag.append(""); + + //Link + if (StringUtils.isNotEmpty(markLink)) { + markFrag.append(""); + } } - else if (markInfo.getClassInfo()!=null){ - //Link - if (StringUtils.isNotEmpty(markLink)){ - markFrag.append(""); - } + else if (markInfo.getClassInfo() != null) { + //Link + if (StringUtils.isNotEmpty(markLink)) { + markFrag.append(""); + } - markFrag.append("

    "); + markFrag.append("
    "); - //Link - if (StringUtils.isNotEmpty(markLink)){ - markFrag.append(""); - } + //Link + if (StringUtils.isNotEmpty(markLink)) { + markFrag.append(""); + } } - return markFrag.toString(); + return markFrag.toString(); } catch (SQLException sqle) { - throw new JspException(sqle.getMessage(), sqle); + throw new JspException(sqle.getMessage(), sqle); } } } diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/VersionUtil.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/VersionUtil.java index 88dcc155eb..09a2e119b6 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/VersionUtil.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/VersionUtil.java @@ -71,15 +71,19 @@ public class VersionUtil * Create a new version of the specified item, otherwise return null * * @param context - * The DSpace context + * The relevant DSpace Context. * @param itemID - * The id of the to-be-versioned item + * The id of the to-be-versioned item * @param summary - * The motif of the versioning - * @return Integer + * The motif of the versioning + * @return Integer WorkspaceItem's Item ID * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static Integer processCreateNewVersion(Context context, UUID itemID, String summary) throws SQLException, AuthorizeException, @@ -117,14 +121,18 @@ public class VersionUtil * Modify latest version * * @param context - * The DSpace context + * The relevant DSpace Context. * @param itemID - * The id of the to-be-versioned item + * The id of the to-be-versioned item * @param summary - * The motif of the versioning + * The motif of the versioning * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void processUpdateVersion(Context context, UUID itemID, String summary) throws SQLException, AuthorizeException, @@ -157,13 +165,18 @@ public class VersionUtil * Restore a version * * @param versionID - * id of the version to restore + * id of the version to restore * @param context - * The DSpace context + * The relevant DSpace Context. * @param summary + * The motif of the versioning * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static void processRestoreVersion(Context context, int versionID, String summary) throws SQLException, AuthorizeException, @@ -180,15 +193,19 @@ public class VersionUtil * Delete version(s) * * @param context - * The DSpace context + * The relevant DSpace Context. * @param versionIDs - * list of versionIDs to delete + * list of versionIDs to delete * @param itemId - * + * Which DSpace Item to operate on. * @return latest version item id or null if all versions has been removed * @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 IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ public static Item processDeleteVersions(Context context, UUID itemId, String[] versionIDs) throws SQLException, AuthorizeException, @@ -235,9 +252,12 @@ public class VersionUtil * then return null. * * @param context + * The relevant DSpace Context. * @param item + * Which DSpace Item to operate on. * @return the latest version of the item * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static Version checkLatestVersion(Context context, Item item) throws SQLException @@ -267,9 +287,12 @@ public class VersionUtil * Check item if it is in workspace or workflow * * @param context + * The relevant DSpace Context. * @param item + * Which DSpace Item to operate on. * @return true if item is in workflow or workspace * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public static boolean isItemInSubmission(Context context, Item item) throws SQLException @@ -289,7 +312,9 @@ public class VersionUtil * dc.identifier * * @param item + * Which DSpace Item to operate on. * @param version + * item version * @return array of string * @deprecated Use {@link UIUtil#getItemIdentifier(org.dspace.core.Context, org.dspace.content.Item)} instead. */ @@ -321,10 +346,12 @@ public class VersionUtil } /** - * Retrieve the summary for the version + * Retrieve the summary for the version. * * @param context + * The relevant DSpace Context. * @param stringVersionID + * An encoded integer version number. * @return version summary string */ public static String getSummary(Context context, String stringVersionID) diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/util/XMLUtil.java b/dspace-jspui/src/main/java/org/dspace/app/webui/util/XMLUtil.java index 2a453a6abc..a2184b6a30 100644 --- a/dspace-jspui/src/main/java/org/dspace/app/webui/util/XMLUtil.java +++ b/dspace-jspui/src/main/java/org/dspace/app/webui/util/XMLUtil.java @@ -40,11 +40,12 @@ public class XMLUtil * Loads a W3C XML document from a file. * * @param filename - * The name of the file to be loaded + * The name of the file to be loaded * @return a document object model object representing the XML file * @throws IOException - * @throws ParserConfigurationException - * @throws SAXException + * A general class of exceptions produced by failed or interrupted I/O operations. + * @throws ParserConfigurationException if XML parser configuration error + * @throws SAXException if XML parsing error */ public static Document loadXML(String filename) throws IOException, ParserConfigurationException, SAXException @@ -62,7 +63,7 @@ public class XMLUtil * @param xsltFilename * the filename of the stylesheet * @return the transformed xml document - * @throws Exception + * @throws Exception passed through. */ public static Document transformDocument(Document xmlDocument, String xsltFilename) throws Exception @@ -81,7 +82,7 @@ public class XMLUtil * @param xsltFilename * the filename of the stylesheet * @return the transformed xml document - * @throws Exception + * @throws Exception passed through. */ public static Document transformDocument(Document xmlDocument, Map parameters, String xsltFilename) throws Exception { @@ -115,18 +116,18 @@ public class XMLUtil } /** - * Applies a stylesheet (that receives parameters) to a given xml document. + * Applies a stylesheet (that receives parameters) to a given XML document. * The resulting XML document is converted to a string after transformation. * * @param xmlDocument - * the xml document to be transformed + * the XML document to be transformed * @param parameters * the hashtable with the parameters to be passed to the * stylesheet * @param xsltFilename * the filename of the stylesheet - * @return the transformed xml document as a string - * @throws Exception + * @return the transformed XML document as a string + * @throws Exception passed through. */ public static String transformDocumentAsString(Document xmlDocument, Map parameters, String xsltFilename) throws Exception { @@ -154,14 +155,14 @@ public class XMLUtil } /** - * Applies a stylesheet to a given xml document. + * Applies a stylesheet to a given XML document. * * @param xmlDocument - * the xml document to be transformed + * the XML document to be transformed * @param xsltFilename * the filename of the stylesheet - * @return the transformed xml document - * @throws Exception + * @return the transformed XML document + * @throws Exception passed through. */ public static String transformDocumentAsString(Document xmlDocument, String xsltFilename) throws Exception diff --git a/dspace-jspui/src/main/webapp/collection-home.jsp b/dspace-jspui/src/main/webapp/collection-home.jsp index 57418b2709..3994d01848 100644 --- a/dspace-jspui/src/main/webapp/collection-home.jsp +++ b/dspace-jspui/src/main/webapp/collection-home.jsp @@ -64,7 +64,7 @@ Boolean submit_b = (Boolean)request.getAttribute("can_submit_button"); boolean submit_button = (submit_b == null ? false : submit_b.booleanValue()); - // get the browse indices + // get the browse indices BrowseIndex[] bis = BrowseIndex.getBrowseIndices(); CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); @@ -81,7 +81,7 @@ copyright = ""; } String sidebar = collectionService.getMetadata(collection, "side_bar_text"); - if(sidebar == null) + if (sidebar == null) { sidebar = ""; } @@ -109,7 +109,7 @@ boolean show_items = showItems != null ? showItems.booleanValue() : false; %> -<%@page import="org.dspace.app.webui.servlet.MyDSpaceServlet"%> +<%@ page import="org.dspace.app.webui.servlet.MyDSpaceServlet"%> <%@ page import="org.dspace.content.factory.ContentServiceFactory" %> <%@ page import="org.dspace.content.service.CollectionService" %> <%@ page import="org.dspace.content.service.ItemService" %> @@ -117,107 +117,107 @@

    <%= name %> <% - if(configurationService.getBooleanProperty("webui.strengths.show")) + if (configurationService.getBooleanProperty("webui.strengths.show")) { %> : [<%= ic.getCount(collection) %>] <% } %> - +

    <% if (logo != null) { %>
    - Logo + Logo
    -<% } %> -
    +<% } %> +
    <% - if (StringUtils.isNotBlank(intro)) { %> - <%= intro %> -<% } %> + if (StringUtils.isNotBlank(intro)) { %> + <%= intro %> +<% } %>

    <%= copyright %>

    <%-- Browse --%>
    -
    +
    -
    -
    - <%-- Insert the dynamic list of browse options --%> +
    +
    + <%-- Insert the dynamic list of browse options --%> <% - for (int i = 0; i < bis.length; i++) - { - String key = "browse.menu." + bis[i].getName(); + for (int i = 0; i < bis.length; i++) + { + String key = "browse.menu." + bis[i].getName(); %> -
    - - <%-- --%> - "/>"/> -
    -<% - } -%>
    +
    + + <%-- --%> + "/>"/> +
    +<% + } +%>
    <% if (submit_button) { %>
    - " /> + " />
    <% } %>
    <% if (loggedIn && subscribed) { %> - " /> + " /> <% } else { %> - + - " /> + " /> <% } - if(feedEnabled) + if (feedEnabled) { %> <% - String[] fmts = feedData.substring(5).split(","); - String icon = null; - int width = 0; - for (int j = 0; j < fmts.length; j++) - { - if ("rss_1.0".equals(fmts[j])) - { - icon = "rss1.gif"; - width = 80; - } - else if ("rss_2.0".equals(fmts[j])) - { - icon = "rss2.gif"; - width = 80; - } - else - { - icon = "rss.gif"; - width = 36; - } + String[] fmts = feedData.substring(5).split(","); + String icon = null; + int width = 0; + for (int j = 0; j < fmts.length; j++) + { + if ("rss_1.0".equals(fmts[j])) + { + icon = "rss1.gif"; + width = 80; + } + else if ("rss_2.0".equals(fmts[j])) + { + icon = "rss2.gif"; + width = 80; + } + else + { + icon = "rss.gif"; + width = 36; + } %> RSS Feed <% - } %> - <% + } %> + <% } %>
    - <%@ include file="discovery/static-tagcloud-facet.jsp" %> + <%@ include file="discovery/static-tagcloud-facet.jsp" %>
    <% if (show_items) - { + { BrowseInfo bi = (BrowseInfo) request.getAttribute("browse.info"); BrowseIndex bix = bi.getBrowseIndex(); @@ -323,13 +323,13 @@ %> -<% if(admin_button || editor_button ) { %> +<% if (admin_button || editor_button ) { %>
    - "> + ">
    -<% if( editor_button ) { %> +<% if ( editor_button ) { %>
    @@ -338,18 +338,18 @@
    <% } %> -<% if( admin_button ) { %> +<% if ( admin_button ) { %>
    - " /> + " />
    -<% if(submitters != null) { %> -
    - - " /> -
    +<% if (submitters != null) { %> +
    + + " /> +
    <% } %> -<% if( editor_button || admin_button) { %> +<% if ( editor_button || admin_button) { %>
    @@ -373,34 +373,34 @@ <% } %> <% - if (rs != null && rs.count() > 0) - { + if (rs != null && rs.count() > 0) + { %> -

    +

    <% ItemService itemService = ContentServiceFactory.getInstance().getItemService(); List items = rs.getRecentSubmissions(); - for (int i = 0; i < items.size(); i++) - { - List dcv = itemService.getMetadata(items.get(i), "dc", "title", null, Item.ANY); - String displayTitle = "Untitled"; - if (dcv != null) - { - if (dcv.size() > 0) - { - displayTitle = Utils.addEntities(dcv.get(0).getValue()); - } - } - %>

    <%= displayTitle %>

    <% - } + for (int i = 0; i < items.size(); i++) + { + List dcv = itemService.getMetadata(items.get(i), "dc", "title", null, Item.ANY); + String displayTitle = "Untitled"; + if (dcv != null) + { + if (dcv.size() > 0) + { + displayTitle = Utils.addEntities(dcv.get(0).getValue()); + } + } + %>

    <%= displayTitle %>

    <% + } %>

     

    <% } %> <%= sidebar %> <% - int discovery_panel_cols = 12; - int discovery_facet_cols = 12; + int discovery_panel_cols = 12; + int discovery_facet_cols = 12; %> <%@ include file="discovery/static-sidebar-facet.jsp" %> diff --git a/dspace-oai/pom.xml b/dspace-oai/pom.xml index e150296048..2d89c2b6d0 100644 --- a/dspace-oai/pom.xml +++ b/dspace-oai/pom.xml @@ -8,7 +8,7 @@ dspace-parent org.dspace - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-oai/src/main/java/org/dspace/utils/DSpaceWebapp.java b/dspace-oai/src/main/java/org/dspace/utils/DSpaceWebapp.java index fb8bbb3feb..7c3d10d4d3 100644 --- a/dspace-oai/src/main/java/org/dspace/utils/DSpaceWebapp.java +++ b/dspace-oai/src/main/java/org/dspace/utils/DSpaceWebapp.java @@ -13,7 +13,7 @@ import org.dspace.app.util.AbstractDSpaceWebapp; /** * An MBean to identify this web application. * - * @author Christian Scheible + * @author Christian Scheible (christian.scheible at uni-konstanz dot de) */ public class DSpaceWebapp extends AbstractDSpaceWebapp diff --git a/dspace-oai/src/main/java/org/dspace/xoai/app/XOAI.java b/dspace-oai/src/main/java/org/dspace/xoai/app/XOAI.java index b7794d0692..d5ab6d6c22 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/app/XOAI.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/app/XOAI.java @@ -69,7 +69,7 @@ import static com.lyncode.xoai.dataprovider.core.Granularity.Second; import static org.dspace.xoai.util.ItemUtils.retrieveMetadata; /** - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ @SuppressWarnings("deprecation") public class XOAI { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/controller/DSpaceOAIDataProvider.java b/dspace-oai/src/main/java/org/dspace/xoai/controller/DSpaceOAIDataProvider.java index 1cdbfb829a..89c876306d 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/controller/DSpaceOAIDataProvider.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/controller/DSpaceOAIDataProvider.java @@ -47,7 +47,7 @@ import static org.apache.log4j.Logger.getLogger; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ @Controller public class DSpaceOAIDataProvider diff --git a/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceItem.java b/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceItem.java index 67241ba2ef..8536288740 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceItem.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceItem.java @@ -22,7 +22,7 @@ import java.util.regex.Pattern; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public abstract class DSpaceItem implements Item { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSet.java b/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSet.java index 30adacefbb..a193e707bb 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSet.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSet.java @@ -14,7 +14,7 @@ import com.lyncode.xoai.dataprovider.core.Set; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceSet extends Set { private static final String DefaultName = "undefined"; diff --git a/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSolrItem.java b/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSolrItem.java index c095ffbbec..7f5fd52581 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSolrItem.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/data/DSpaceSolrItem.java @@ -21,7 +21,7 @@ import java.util.Collection; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceSolrItem extends DSpaceItem { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/exceptions/CompilingException.java b/dspace-oai/src/main/java/org/dspace/xoai/exceptions/CompilingException.java index ba7dee60e4..96ff6a0bcd 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/exceptions/CompilingException.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/exceptions/CompilingException.java @@ -10,7 +10,7 @@ package org.dspace.xoai.exceptions; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ @SuppressWarnings("serial") public class CompilingException extends Exception diff --git a/dspace-oai/src/main/java/org/dspace/xoai/exceptions/InvalidMetadataFieldException.java b/dspace-oai/src/main/java/org/dspace/xoai/exceptions/InvalidMetadataFieldException.java index 425f976cbc..4dadc2d3d9 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/exceptions/InvalidMetadataFieldException.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/exceptions/InvalidMetadataFieldException.java @@ -9,7 +9,7 @@ package org.dspace.xoai.exceptions; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class InvalidMetadataFieldException extends Exception { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAtLeastOneMetadataFilter.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAtLeastOneMetadataFilter.java index fbbb4aa533..9b0aabd378 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAtLeastOneMetadataFilter.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAtLeastOneMetadataFilter.java @@ -26,7 +26,7 @@ import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterValue; import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.SimpleType; /** - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceAtLeastOneMetadataFilter extends DSpaceFilter { private static final Logger log = LogManager.getLogger(DSpaceAtLeastOneMetadataFilter.class); diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAuthorizationFilter.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAuthorizationFilter.java index 405c0d9bdb..25996aaaaa 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAuthorizationFilter.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceAuthorizationFilter.java @@ -23,7 +23,7 @@ import org.dspace.xoai.filter.results.SolrFilterResult; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceAuthorizationFilter extends DSpaceFilter { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceFilter.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceFilter.java index 3a7a641e70..8a3694bbf5 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceFilter.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceFilter.java @@ -18,7 +18,7 @@ import org.dspace.xoai.services.api.FieldResolver; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public abstract class DSpaceFilter implements Filter { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceMetadataExistsFilter.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceMetadataExistsFilter.java index 5d5ea12b35..45989cc8bd 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceMetadataExistsFilter.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceMetadataExistsFilter.java @@ -22,11 +22,11 @@ import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.SimpleType; * This filter allows one to retrieve (from the data source) those items * which contains at least one metadata field value defined, it allows * one to define multiple metadata fields to check against. - *

    + *

    * One line summary: At least one metadata field defined * - * @author Ariel J. Lira - * @author Lyncode Development Team + * @author Ariel J. Lira (arieljlira at gmail dot com) + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceMetadataExistsFilter extends DSpaceFilter { private static final Logger log = LogManager diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceSetSpecFilter.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceSetSpecFilter.java index 20f68ecf90..46faff78d5 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceSetSpecFilter.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/DSpaceSetSpecFilter.java @@ -19,7 +19,7 @@ import org.dspace.xoai.services.api.HandleResolver; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceSetSpecFilter extends DSpaceFilter { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/DateFromFilter.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/DateFromFilter.java index 412965a304..0c2a0f466a 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/DateFromFilter.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/DateFromFilter.java @@ -18,7 +18,7 @@ import java.util.Date; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DateFromFilter extends DSpaceFilter { private static final DateProvider dateProvider = new BaseDateProvider(); diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/DateUntilFilter.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/DateUntilFilter.java index fa5f0c1732..cd564e044d 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/DateUntilFilter.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/DateUntilFilter.java @@ -18,7 +18,7 @@ import java.util.Date; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DateUntilFilter extends DSpaceFilter { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/SolrFilterResult.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/SolrFilterResult.java index 72d38b6e53..386d5fb971 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/SolrFilterResult.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/SolrFilterResult.java @@ -12,7 +12,7 @@ import org.apache.log4j.Logger; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class SolrFilterResult { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/data/DSpaceMetadataFilterOperator.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/data/DSpaceMetadataFilterOperator.java index 987124d240..36876c4a99 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/data/DSpaceMetadataFilterOperator.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/data/DSpaceMetadataFilterOperator.java @@ -10,7 +10,7 @@ package org.dspace.xoai.filter.data; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public enum DSpaceMetadataFilterOperator { UNDEF, CONTAINS, EQUAL, GREATER, LOWER, GREATER_OR_EQUAL, LOWER_OR_EQUAL, ENDS_WITH, STARTS_WITH diff --git a/dspace-oai/src/main/java/org/dspace/xoai/filter/results/SolrFilterResult.java b/dspace-oai/src/main/java/org/dspace/xoai/filter/results/SolrFilterResult.java index 9a8f8d8707..63211ecf5c 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/filter/results/SolrFilterResult.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/filter/results/SolrFilterResult.java @@ -12,7 +12,7 @@ import org.apache.log4j.Logger; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class SolrFilterResult { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/MetadataFieldCache.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/MetadataFieldCache.java index 408dc8ecc8..9ce4b0da7b 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/MetadataFieldCache.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/MetadataFieldCache.java @@ -15,7 +15,7 @@ import java.util.Map; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class MetadataFieldCache { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemRepository.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemRepository.java index 7b4fb470f9..091a48a247 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemRepository.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemRepository.java @@ -26,7 +26,7 @@ import java.util.List; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public abstract class DSpaceItemRepository implements ItemRepository { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemSolrRepository.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemSolrRepository.java index 3d52d5ab2c..4fb5e00f3a 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemSolrRepository.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceItemSolrRepository.java @@ -35,7 +35,7 @@ import java.util.regex.Pattern; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceItemSolrRepository extends DSpaceItemRepository { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java index c70b8686ff..408fc6b43b 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java @@ -30,8 +30,8 @@ import java.util.List; /** * - * @author Lyncode Development Team - * @author Domingo Iglesias + * @author Lyncode Development Team (dspace at lyncode dot com) + * @author Domingo Iglesias (diglesias at ub dot edu) */ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceSetRepository.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceSetRepository.java index c6e707b4df..dbda548163 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceSetRepository.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceSetRepository.java @@ -29,7 +29,7 @@ import org.dspace.handle.service.HandleService; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceSetRepository implements SetRepository { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrSearch.java b/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrSearch.java index 2c30b4e0d8..894050bd34 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrSearch.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrSearch.java @@ -20,7 +20,7 @@ import org.dspace.xoai.solr.exceptions.SolrSearchEmptyException; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceSolrSearch { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java b/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java index fbddda9160..5cebef156c 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java @@ -17,7 +17,7 @@ import org.dspace.core.ConfigurationManager; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DSpaceSolrServer { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrException.java b/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrException.java index d4c7e5801b..63a2aa93d8 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrException.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrException.java @@ -9,7 +9,7 @@ package org.dspace.xoai.solr.exceptions; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ @SuppressWarnings("serial") public class DSpaceSolrException extends Exception diff --git a/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrIndexerException.java b/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrIndexerException.java index 5b39851311..c72bbb80c5 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrIndexerException.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/DSpaceSolrIndexerException.java @@ -10,7 +10,7 @@ package org.dspace.xoai.solr.exceptions; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ @SuppressWarnings("serial") public class DSpaceSolrIndexerException extends Exception diff --git a/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/SolrSearchEmptyException.java b/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/SolrSearchEmptyException.java index 5090ac08cc..d1db3e59c3 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/SolrSearchEmptyException.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/solr/exceptions/SolrSearchEmptyException.java @@ -10,7 +10,7 @@ package org.dspace.xoai.solr.exceptions; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ @SuppressWarnings("serial") public class SolrSearchEmptyException extends Exception diff --git a/dspace-oai/src/main/java/org/dspace/xoai/util/DateUtils.java b/dspace-oai/src/main/java/org/dspace/xoai/util/DateUtils.java index 61851c81b8..b269ad7a39 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/util/DateUtils.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/util/DateUtils.java @@ -18,7 +18,7 @@ import java.util.TimeZone; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class DateUtils { diff --git a/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java b/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java index 87506c4b19..316c9dbe93 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java @@ -34,7 +34,7 @@ import org.dspace.core.Context; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ @SuppressWarnings("deprecation") public class ItemUtils diff --git a/dspace-oai/src/main/java/org/dspace/xoai/util/URLUtils.java b/dspace-oai/src/main/java/org/dspace/xoai/util/URLUtils.java index 6295e56ac2..df0fcb9f85 100644 --- a/dspace-oai/src/main/java/org/dspace/xoai/util/URLUtils.java +++ b/dspace-oai/src/main/java/org/dspace/xoai/util/URLUtils.java @@ -15,7 +15,7 @@ import java.io.UnsupportedEncodingException; /** * - * @author Lyncode Development Team + * @author Lyncode Development Team (dspace at lyncode dot com) */ public class URLUtils { diff --git a/dspace-oai/src/test/resources/oai_dc.xsl b/dspace-oai/src/test/resources/oai_dc.xsl index ff127de7ca..ba8a7cadf7 100644 --- a/dspace-oai/src/test/resources/oai_dc.xsl +++ b/dspace-oai/src/test/resources/oai_dc.xsl @@ -7,7 +7,7 @@ tree and available online at http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) > http://www.openarchives.org/OAI/2.0/oai_dc.xsd diff --git a/dspace-rdf/pom.xml b/dspace-rdf/pom.xml index 4402c9ff22..b254ab405d 100644 --- a/dspace-rdf/pom.xml +++ b/dspace-rdf/pom.xml @@ -9,7 +9,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-rest/pom.xml b/dspace-rest/pom.xml index f9f47d937e..c7917fe257 100644 --- a/dspace-rest/pom.xml +++ b/dspace-rest/pom.xml @@ -3,7 +3,7 @@ org.dspace dspace-rest war - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT DSpace REST :: API and Implementation DSpace RESTful Web Services API http://demo.dspace.org @@ -11,7 +11,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-rest/src/main/java/org/dspace/rest/BitstreamResource.java b/dspace-rest/src/main/java/org/dspace/rest/BitstreamResource.java index 0adca4a2bd..724eb536d5 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/BitstreamResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/BitstreamResource.java @@ -79,21 +79,32 @@ public class BitstreamResource extends Resource * bitstream. Server error when something went wrong. * * @param bitstreamId - * Id of bitstream in DSpace. + * Id of bitstream in DSpace. * @param expand - * This string defines which additional optional fields will be added - * to bitstream response. Individual options are separated by commas without - * spaces. The options are: "all", "parent". + * This string defines which additional optional fields will be added + * to bitstream response. Individual options are separated by commas without + * spaces. The options are: "all", "parent". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return If user is allowed to read bitstream, it returns instance of - * bitstream. Otherwise, it throws WebApplicationException with - * response code UNAUTHORIZED. + * bitstream. Otherwise, it throws WebApplicationException with + * response code UNAUTHORIZED. * @throws WebApplicationException - * It can happen on: Bad request, unauthorized, SQL exception - * and context exception(could not create context). + * It can happen on: Bad request, unauthorized, SQL exception + * and context exception(could not create context). */ @GET @Path("/{bitstream_id}") @@ -144,11 +155,11 @@ public class BitstreamResource extends Resource * the bitstream is present. * * @param bitstreamId - * Id of bitstream in DSpace. + * Id of bitstream in DSpace. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. * @return Returns an array of ResourcePolicy objects. */ @GET @@ -194,19 +205,34 @@ public class BitstreamResource extends Resource * code INTERNAL_SERVER_ERROR(500), if there was problem while reading * bitstreams from database. * + * @param expand + * This string defines which additional optional fields will be added + * to bitstream response. Individual options are separated by commas without + * spaces. The options are: "all", "parent". * @param limit - * How many bitstreams will be in the list. Default value is 100. + * How many bitstreams will be in the list. Default value is 100. * @param offset - * On which offset (item) the list starts. Default value is 0. + * On which offset (item) the list starts. Default value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. + * @param request + * Servlet's HTTP request object. * @return Returns an array of bistreams. Array doesn't contain bitstreams for - * which the user doesn't have read permission. + * which the user doesn't have read permission. * @throws WebApplicationException - * Thrown in case of a problem with reading the database or with - * creating a context. + * Thrown in case of a problem with reading the database or with + * creating a context. */ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @@ -277,18 +303,29 @@ public class BitstreamResource extends Resource * a problem with authorization of user logged to DSpace context. * * @param bitstreamId - * Id of the bitstream, whose data will be read. + * Id of the bitstream, whose data will be read. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. + * @param request + * Servlet's HTTP request object. * @return Returns response with data with file content type. It can - * return the NOT_FOUND(404) response code in case of wrong bitstream - * id. Or response code UNAUTHORIZED(401) if user is not - * allowed to read bitstream. + * return the NOT_FOUND(404) response code in case of wrong bitstream + * id. Or response code UNAUTHORIZED(401) if user is not + * allowed to read bitstream. * @throws WebApplicationException - * Thrown if there was a problem: reading the file data; or reading - * the database; or creating the context; or with authorization. + * Thrown if there was a problem: reading the file data; or reading + * the database; or creating the context; or with authorization. */ @GET @Path("/{bitstream_id}/retrieve") @@ -353,14 +390,25 @@ public class BitstreamResource extends Resource * Add bitstream policy to all bundles containing the bitstream. * * @param bitstreamId - * Id of bitstream in DSpace. + * Id of bitstream in DSpace. * @param policy - * Policy to be added. The following attributes are not - * applied: epersonId, + * Policy to be added. The following attributes are not + * applied: epersonId, + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. + * @param request + * Servlet's HTTP request object. * @return Returns ok, if all was ok. Otherwise status code 500. */ @POST @@ -419,20 +467,31 @@ public class BitstreamResource extends Resource * there was a problem with the authorization to edit bitstream metadata. * * @param bitstreamId - * Id of bistream to be updated. + * Id of bistream to be updated. * @param bitstream - * Bitstream with will be placed. It must have filled user - * credentials. + * Bitstream with will be placed. It must have filled user + * credentials. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. + * @param request + * Servlet's HTTP request object. * @return Return response codes: OK(200), NOT_FOUND(404) if bitstream does - * not exist and UNAUTHORIZED(401) if user is not allowed to write - * to bitstream. + * not exist and UNAUTHORIZED(401) if user is not allowed to write + * to bitstream. * @throws WebApplicationException - * Thrown when: Error reading from database; or error - * creating context; or error regarding bitstream authorization. + * Thrown when: Error reading from database; or error + * creating context; or error regarding bitstream authorization. */ @PUT @Path("/{bitstream_id}") @@ -524,20 +583,31 @@ public class BitstreamResource extends Resource * problem. * * @param bitstreamId - * Id of bistream to be updated. + * Id of bistream to be updated. * @param is - * InputStream filled with new data. + * InputStream filled with new data. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. + * @param request + * Servlet's HTTP request object. * @return Return response if bitstream was updated. Response codes: - * OK(200), NOT_FOUND(404) if id of bitstream was bad. And - * UNAUTHORIZED(401) if user is not allowed to update bitstream. + * OK(200), NOT_FOUND(404) if id of bitstream was bad. And + * UNAUTHORIZED(401) if user is not allowed to update bitstream. * @throws WebApplicationException - * This exception can be thrown in this cases: Problem with - * reading or writing to database. Or problem with reading from - * InputStream. + * This exception can be thrown in this cases: Problem with + * reading or writing to database. Or problem with reading from + * InputStream. */ // TODO Change to better logic, without editing database. @PUT @@ -596,19 +666,30 @@ public class BitstreamResource extends Resource * the bitstream or file. IOException, if there was a problem deleting the file. * * @param bitstreamId - * Id of bitstream to be deleted. + * Id of bitstream to be deleted. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. + * @param request + * Servlet's HTTP request object. * @return Return response codes: OK(200), NOT_FOUND(404) if bitstream of - * that id does not exist and UNAUTHORIZED(401) if user is not - * allowed to delete bitstream. + * that id does not exist and UNAUTHORIZED(401) if user is not + * allowed to delete bitstream. * @throws WebApplicationException - * Can be thrown if there was a problem reading or editing - * the database. Or problem deleting the file. Or problem with - * authorization to bitstream and bundles. Or problem with - * creating context. + * Can be thrown if there was a problem reading or editing + * the database. Or problem deleting the file. Or problem with + * authorization to bitstream and bundles. Or problem with + * creating context. */ @DELETE @Path("/{bitstream_id}") @@ -663,13 +744,24 @@ public class BitstreamResource extends Resource * Delete policy. * * @param bitstreamId - * Id of the DSpace bitstream whose policy will be deleted. + * Id of the DSpace bitstream whose policy will be deleted. * @param policyId - * Id of the policy to delete. + * Id of the policy to delete. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into the context. - * The header "rest-dspace-token" with the token passed - * from the login method must be set. + * If you want to access the item as the user logged into the context. + * The header "rest-dspace-token" with the token passed + * from the login method must be set. + * @param request + * Servlet's HTTP request object. * @return It returns Ok, if all was ok. Otherwise status code 500. */ @DELETE @@ -737,9 +829,12 @@ public class BitstreamResource extends Resource * Add policy(org.dspace.rest.common.ResourcePolicy) to bitstream. * @param context Context to create DSpace ResourcePolicy. * @param policy Policy which will be added to bitstream. - * @param dspaceBitstream + * @param dspaceBitstream DSpace Bitstream object. * @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. */ private void addPolicyToBitstream(org.dspace.core.Context context, ResourcePolicy policy, org.dspace.content.Bitstream dspaceBitstream) throws SQLException, AuthorizeException { org.dspace.authorize.ResourcePolicy dspacePolicy = resourcePolicyService.create(context); @@ -760,15 +855,15 @@ public class BitstreamResource extends Resource * whether the user logged into the context has permission to preform the requested action. * * @param context - * Context of actual logged user. + * Context of actual logged user. * @param id - * Id of bitstream in DSpace. + * Id of bitstream in DSpace. * @param action - * Constant from org.dspace.core.Constants. + * Constant from org.dspace.core.Constants. * @return Returns DSpace bitstream. * @throws WebApplicationException - * Is thrown when item with passed id is not exists and if user - * has no permission to do passed action. + * Is thrown when item with passed id is not exists and if user + * has no permission to do passed action. */ private org.dspace.content.Bitstream findBitstream(org.dspace.core.Context context, String id, int action) throws WebApplicationException diff --git a/dspace-rest/src/main/java/org/dspace/rest/CollectionsResource.java b/dspace-rest/src/main/java/org/dspace/rest/CollectionsResource.java index 4fd2965cfe..037d28cd47 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/CollectionsResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/CollectionsResource.java @@ -67,30 +67,41 @@ public class CollectionsResource extends Resource * through expand parameter. * * @param collectionId - * Id of collection in DSpace. + * Id of collection in DSpace. * @param expand - * String in which is what you want to add to returned instance - * of collection. Options are: "all", "parentCommunityList", - * "parentCommunity", "items", "license" and "logo". If you want - * to use multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of collection. Options are: "all", "parentCommunityList", + * "parentCommunity", "items", "license" and "logo". If you want + * to use multiple options, it must be separated by commas. * @param limit - * Limit value for items in list in collection. Default value is - * 100. + * Limit value for items in list in collection. Default value is + * 100. * @param offset - * Offset of start index in list of items of collection. Default - * value is 0. + * Offset of start index in list of items of collection. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return instance of collection. It can also return status code - * NOT_FOUND(404) if id of collection is incorrect or status code - * UNATHORIZED(401) if user has no permission to read collection. + * NOT_FOUND(404) if id of collection is incorrect or status code + * UNATHORIZED(401) if user has no permission to read collection. * @throws WebApplicationException - * It is thrown when was problem with database reading - * (SQLException) or problem with creating - * context(ContextException). It is thrown by NOT_FOUND and - * UNATHORIZED status codes, too. + * It is thrown when was problem with database reading + * (SQLException) or problem with creating + * context(ContextException). It is thrown by NOT_FOUND and + * UNATHORIZED status codes, too. */ @GET @Path("/{collection_id}") @@ -141,26 +152,37 @@ public class CollectionsResource extends Resource * through expand parameter. * * @param expand - * String in which is what you want to add to returned instance - * of collection. Options are: "all", "parentCommunityList", - * "parentCommunity", "items", "license" and "logo". If you want - * to use multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of collection. Options are: "all", "parentCommunityList", + * "parentCommunity", "items", "license" and "logo". If you want + * to use multiple options, it must be separated by commas. * @param limit - * Limit value for items in list in collection. Default value is - * 100. + * Limit value for items in list in collection. Default value is + * 100. * @param offset - * Offset of start index in list of items of collection. Default - * value is 0. + * Offset of start index in list of items of collection. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to collections under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collections as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of collection, on which has logged user permission - * to view. + * to view. * @throws WebApplicationException - * It is thrown when was problem with database reading - * (SQLException) or problem with creating - * context(ContextException). + * It is thrown when was problem with database reading + * (SQLException) or problem with creating + * context(ContextException). */ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @@ -222,30 +244,41 @@ public class CollectionsResource extends Resource * with expand parameter. * * @param collectionId - * Id of collection in DSpace. + * Id of collection in DSpace. * @param expand - * String which define, what additional properties will be in - * returned item. Options are separeted by commas and are: "all", - * "metadata", "parentCollection", "parentCollectionList", - * "parentCommunityList" and "bitstreams". + * String which define, what additional properties will be in + * returned item. Options are separeted by commas and are: "all", + * "metadata", "parentCollection", "parentCollectionList", + * "parentCommunityList" and "bitstreams". * @param limit - * Limit value for items in array. Default value is 100. + * Limit value for items in array. Default value is 100. * @param offset - * Offset of start index in array of items of collection. Default - * value is 0. + * Offset of start index in array of items of collection. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of items, on which has logged user permission to - * read. It can also return status code NOT_FOUND(404) if id of - * collection is incorrect or status code UNATHORIZED(401) if user - * has no permission to read collection. + * read. It can also return status code NOT_FOUND(404) if id of + * collection is incorrect or status code UNATHORIZED(401) if user + * has no permission to read collection. * @throws WebApplicationException - * It is thrown when was problem with database reading - * (SQLException) or problem with creating - * context(ContextException). It is thrown by NOT_FOUND and - * UNATHORIZED status codes, too. + * It is thrown when was problem with database reading + * (SQLException) or problem with creating + * context(ContextException). It is thrown by NOT_FOUND and + * UNATHORIZED status codes, too. */ @GET @Path("/{collection_id}/items") @@ -309,24 +342,35 @@ public class CollectionsResource extends Resource * Create item in collection. Item can be without filled metadata. * * @param collectionId - * Id of collection in which will be item created. + * Id of collection in which will be item created. * @param item - * Item filled only with metadata, other variables are ignored. + * Item filled only with metadata, other variables are ignored. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return status code with item. Return status (OK)200 if item was - * created. NOT_FOUND(404) if id of collection does not exists. - * UNAUTHORIZED(401) if user have not permission to write items in - * collection. + * created. NOT_FOUND(404) if id of collection does not exists. + * UNAUTHORIZED(401) if user have not permission to write items in + * collection. * @throws WebApplicationException - * It is thrown when was problem with database reading or - * writing (SQLException) or problem with creating - * context(ContextException) or problem with authorization to - * collection or IOException or problem with index item into - * browse index. It is thrown by NOT_FOUND and UNATHORIZED - * status codes, too. + * It is thrown when was problem with database reading or + * writing (SQLException) or problem with creating + * context(ContextException) or problem with authorization to + * collection or IOException or problem with index item into + * browse index. It is thrown by NOT_FOUND and UNATHORIZED + * status codes, too. * */ @POST @@ -402,20 +446,31 @@ public class CollectionsResource extends Resource * Update collection. It replace all properties. * * @param collectionId - * Id of collection in DSpace. + * Id of collection in DSpace. * @param collection - * Collection which will replace properties of actual collection. + * Collection which will replace properties of actual collection. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response 200 if was everything all right. Otherwise 400 - * when id of community was incorrect or 401 if was problem with - * permission to write into collection. + * when id of community was incorrect or 401 if was problem with + * permission to write into collection. * @throws WebApplicationException - * It is thrown when was problem with database reading or - * writing. Or problem with authorization to collection. Or - * problem with creating context. + * It is thrown when was problem with database reading or + * writing. Or problem with authorization to collection. Or + * problem with creating context. */ @PUT @Path("/{collection_id}") @@ -474,19 +529,30 @@ public class CollectionsResource extends Resource * Delete collection. * * @param collectionId - * Id of collection which will be deleted. + * Id of collection which will be deleted. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response code OK(200) if was everything all right. - * Otherwise return NOT_FOUND(404) if was id of community or - * collection incorrect. Or (UNAUTHORIZED)401 if was problem with - * permission to community or collection. + * Otherwise return NOT_FOUND(404) if was id of community or + * collection incorrect. Or (UNAUTHORIZED)401 if was problem with + * permission to community or collection. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or writing. Or problem with deleting - * collection caused by IOException or authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or writing. Or problem with deleting + * collection caused by IOException or authorization. */ @DELETE @Path("/{collection_id}") @@ -542,20 +608,34 @@ public class CollectionsResource extends Resource * Delete item in collection. * * @param collectionId - * Id of collection which will be deleted. - * + * Id of collection which will be deleted. * @param itemId - * Id of item in colletion. + * Id of item in colletion. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. + * @param headers + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return It returns status code: OK(200). NOT_FOUND(404) if item or - * collection was not found, UNAUTHORIZED(401) if user is not - * allowed to delete item or permission to write into collection. + * collection was not found, UNAUTHORIZED(401) if user is not + * allowed to delete item or permission to write into collection. * @throws WebApplicationException - * It can be thrown by: SQLException, when was problem with - * database reading or writting. AuthorizeException, when was - * problem with authorization to item or collection. - * IOException, when was problem with removing item. - * ContextException, when was problem with creating context of - * DSpace. + * It can be thrown by: SQLException, when was problem with + * database reading or writting. AuthorizeException, when was + * problem with authorization to item or collection. + * IOException, when was problem with removing item. + * ContextException, when was problem with creating context of + * DSpace. */ @DELETE @Path("/{collection_id}/items/{item_id}") @@ -646,14 +726,15 @@ public class CollectionsResource extends Resource * Search for first collection with passed name. * * @param name - * Name of collection. + * Name of collection. * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. * @return It returns null if collection was not found. Otherwise returns - * first founded collection. + * first founded collection. * @throws WebApplicationException + * A general exception a servlet can throw when it encounters difficulty. */ @POST @Path("/find-collection") @@ -719,15 +800,15 @@ public class CollectionsResource extends Resource * user logged into context has permission to do passed action. * * @param context - * Context of actual logged user. + * Context of actual logged user. * @param id - * Id of collection in DSpace. + * Id of collection in DSpace. * @param action - * Constant from org.dspace.core.Constants. + * Constant from org.dspace.core.Constants. * @return It returns DSpace collection. * @throws WebApplicationException - * Is thrown when item with passed id is not exists and if user - * has no permission to do passed action. + * Is thrown when item with passed id is not exists and if user + * has no permission to do passed action. */ private org.dspace.content.Collection findCollection(org.dspace.core.Context context, String id, int action) throws WebApplicationException diff --git a/dspace-rest/src/main/java/org/dspace/rest/CommunitiesResource.java b/dspace-rest/src/main/java/org/dspace/rest/CommunitiesResource.java index 5c36098881..78ea7e3fd6 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/CommunitiesResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/CommunitiesResource.java @@ -50,21 +50,32 @@ public class CommunitiesResource extends Resource * parameter or method for community collections or subcommunities. * * @param communityId - * Id of community in DSpace. + * Id of community in DSpace. * @param expand - * String in which is what you want to add to returned instance - * of community. Options are: "all", "parentCommunity", - * "collections", "subCommunities" and "logo". If you want to use - * multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of community. Options are: "all", "parentCommunity", + * "collections", "subCommunities" and "logo". If you want to use + * multiple options, it must be separated by commas. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return instance of org.dspace.rest.common.Community. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading. Also if id of community is incorrect - * or logged user into context has no permission to read. + * Thrown if there was a problem with creating context or problem + * with database reading. Also if id of community is incorrect + * or logged user into context has no permission to read. */ @GET @Path("/{community_id}") @@ -114,23 +125,33 @@ public class CommunitiesResource extends Resource * Return all communities in DSpace. * * @param expand - * String in which is what you want to add to returned instance - * of community. Options are: "all", "parentCommunity", - * "collections", "subCommunities" and "logo". If you want to use - * multiple options, it must be separated by commas. - * + * String in which is what you want to add to returned instance + * of community. Options are: "all", "parentCommunity", + * "collections", "subCommunities" and "logo". If you want to use + * multiple options, it must be separated by commas. * @param limit - * Maximum communities in array. Default value is 100. + * Maximum communities in array. Default value is 100. * @param offset - * Index from which will start array of communities. + * Index from which will start array of communities. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of communities. * @throws WebApplicationException - * It can be caused by creating context or while was problem - * with reading community from database(SQLException). + * It can be caused by creating context or while was problem + * with reading community from database(SQLException). */ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @@ -194,24 +215,34 @@ public class CommunitiesResource extends Resource * the root of tree. * * @param expand - * String in which is what you want to add to returned instance - * of community. Options are: "all", "parentCommunity", - * "collections", "subCommunities" and "logo". If you want to use - * multiple options, it must be separated by commas. - * + * String in which is what you want to add to returned instance + * of community. Options are: "all", "parentCommunity", + * "collections", "subCommunities" and "logo". If you want to use + * multiple options, it must be separated by commas. * @param limit - * Maximum communities in array. Default value is 100. + * Maximum communities in array. Default value is 100. * @param offset - * Index from which will start array of communities. Default - * value is 0. + * Index from which will start array of communities. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of top communities. * @throws WebApplicationException - * It can be caused by creating context or while was problem - * with reading community from database(SQLException). + * It can be caused by creating context or while was problem + * with reading community from database(SQLException). */ @GET @Path("/top-communities") @@ -275,25 +306,36 @@ public class CommunitiesResource extends Resource * Return all collections of community. * * @param communityId - * Id of community in DSpace. + * Id of community in DSpace. * @param expand - * String in which is what you want to add to returned instance - * of collection. Options are: "all", "parentCommunityList", - * "parentCommunity", "items", "license" and "logo". If you want - * to use multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of collection. Options are: "all", "parentCommunityList", + * "parentCommunity", "items", "license" and "logo". If you want + * to use multiple options, it must be separated by commas. * @param limit - * Maximum collection in array. Default value is 100. + * Maximum collection in array. Default value is 100. * @param offset - * Index from which will start array of collections. Default - * value is 0. + * Index from which will start array of collections. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of collections of community. * @throws WebApplicationException - * It can be caused by creating context or while was problem - * with reading community from database(SQLException). + * It can be caused by creating context or while was problem + * with reading community from database(SQLException). */ @GET @Path("/{community_id}/collections") @@ -361,25 +403,36 @@ public class CommunitiesResource extends Resource * Return all subcommunities of community. * * @param communityId - * Id of community in DSpace. + * Id of community in DSpace. * @param expand - * String in which is what you want to add to returned instance - * of community. Options are: "all", "parentCommunity", - * "collections", "subCommunities" and "logo". If you want to use - * multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of community. Options are: "all", "parentCommunity", + * "collections", "subCommunities" and "logo". If you want to use + * multiple options, it must be separated by commas. * @param limit - * Maximum communities in array. Default value is 20. + * Maximum communities in array. Default value is 20. * @param offset - * Index from which will start array of communities. Default - * value is 0. + * Index from which will start array of communities. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of subcommunities of community. * @throws WebApplicationException - * It can be caused by creating context or while was problem - * with reading community from database(SQLException). + * It can be caused by creating context or while was problem + * with reading community from database(SQLException). */ @GET @Path("/{community_id}/communities") @@ -449,15 +502,26 @@ public class CommunitiesResource extends Resource * permission only admin. * * @param community - * Community which will be created at top level of communities. + * Community which will be created at top level of communities. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Returns response with handle of community, if was all ok. * @throws WebApplicationException - * It can be thrown by SQLException, AuthorizeException and - * ContextException. + * It can be thrown by SQLException, AuthorizeException and + * ContextException. */ @POST @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @@ -525,20 +589,31 @@ public class CommunitiesResource extends Resource * Create collection in community. * * @param communityId - * Id of community in DSpace. + * Id of community in DSpace. * @param collection - * Collection which will be added into community. + * Collection which will be added into community. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response 200 if was everything all right. Otherwise 400 - * when id of community was incorrect or 401 if was problem with - * permission to write into collection. + * when id of community was incorrect or 401 if was problem with + * permission to write into collection. * @throws WebApplicationException - * It is thrown when was problem with database reading or - * writing. Or problem with authorization to community. Or - * problem with creating context. + * It is thrown when was problem with database reading or + * writing. Or problem with authorization to community. Or + * problem with creating context. */ @POST @Path("/{community_id}/collections") @@ -605,21 +680,32 @@ public class CommunitiesResource extends Resource * Create subcommunity in community. * * @param communityId - * Id of community in DSpace, in which will be created - * subcommunity. + * Id of community in DSpace, in which will be created + * subcommunity. * @param community - * Community which will be added into community. + * Community which will be added into community. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response 200 if was everything all right. Otherwise 400 - * when id of community was incorrect or 401 if was problem with - * permission to write into collection. + * when id of community was incorrect or 401 if was problem with + * permission to write into collection. * @throws WebApplicationException - * It is thrown when was problem with database reading or - * writing. Or problem with authorization to community. Or - * problem with creating context. + * It is thrown when was problem with database reading or + * writing. Or problem with authorization to community. Or + * problem with creating context. */ @POST @Path("/{community_id}/communities") @@ -686,20 +772,31 @@ public class CommunitiesResource extends Resource * handle and expandle items. * * @param communityId - * Id of community in DSpace. + * Id of community in DSpace. * @param community - * Instance of community which will replace actual community in - * DSpace. + * Instance of community which will replace actual community in + * DSpace. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. - * @return Response 200 if was all ok. Otherwise 400 if was id incorrect or - * 401 if logged user has no permission to delete community. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. + * @return Response 200 if was all ok. Otherwise 400 if id was incorrect or + * 401 if logged user has no permission to delete community. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or writing. Or problem with writing to - * community caused by authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or writing. Or problem with writing to + * community caused by authorization. */ @PUT @Path("/{community_id}") @@ -753,18 +850,29 @@ public class CommunitiesResource extends Resource * Delete community from DSpace. It delete it everything with community! * * @param communityId - * Id of community in DSpace. + * Id of community in DSpace. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response code OK(200) if was everything all right. - * Otherwise return NOT_FOUND(404) if was id of community incorrect. - * Or (UNAUTHORIZED)401 if was problem with permission to community. + * Otherwise return NOT_FOUND(404) if was id of community incorrect. + * Or (UNAUTHORIZED)401 if was problem with permission to community. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or deleting. Or problem with deleting - * community caused by IOException or authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or deleting. Or problem with deleting + * community caused by IOException or authorization. */ @DELETE @Path("/{community_id}") @@ -820,21 +928,32 @@ public class CommunitiesResource extends Resource * Delete collection in community. * * @param communityId - * Id of community in DSpace. + * Id of community in DSpace. * @param collectionId - * Id of collection which will be deleted. + * Id of collection which will be deleted. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response code OK(200) if was everything all right. - * Otherwise return NOT_FOUND(404) if was id of community or - * collection incorrect. Or (UNAUTHORIZED)401 if was problem with - * permission to community or collection. + * Otherwise return NOT_FOUND(404) if was id of community or + * collection incorrect. Or (UNAUTHORIZED)401 if was problem with + * permission to community or collection. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or deleting. Or problem with deleting - * collection caused by IOException or authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or deleting. Or problem with deleting + * collection caused by IOException or authorization. */ @DELETE @Path("/{community_id}/collections/{collection_id}") @@ -920,21 +1039,32 @@ public class CommunitiesResource extends Resource * Delete subcommunity in community. * * @param parentCommunityId - * Id of community in DSpace. + * Id of community in DSpace. * @param subcommunityId - * Id of community which will be deleted. + * Id of community which will be deleted. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response code OK(200) if was everything all right. - * Otherwise return NOT_FOUND(404) if was id of community or - * subcommunity incorrect. Or (UNAUTHORIZED)401 if was problem with - * permission to community or subcommunity. + * Otherwise return NOT_FOUND(404) if was id of community or + * subcommunity incorrect. Or (UNAUTHORIZED)401 if was problem with + * permission to community or subcommunity. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or deleting. Or problem with deleting - * subcommunity caused by IOException or authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or deleting. Or problem with deleting + * subcommunity caused by IOException or authorization. */ @DELETE @Path("/{community_id}/communities/{community_id2}") @@ -1023,15 +1153,15 @@ public class CommunitiesResource extends Resource * logged into context has permission to do passed action. * * @param context - * Context of actual logged user. + * Context of actual logged user. * @param id - * Id of community in DSpace. + * Id of community in DSpace. * @param action - * Constant from org.dspace.core.Constants. + * Constant from org.dspace.core.Constants. * @return It returns DSpace collection. * @throws WebApplicationException - * Is thrown when item with passed id is not exists and if user - * has no permission to do passed action. + * Is thrown when item with passed id is not exists and if user + * has no permission to do passed action. */ private org.dspace.content.Community findCommunity(org.dspace.core.Context context, String id, int action) throws WebApplicationException diff --git a/dspace-rest/src/main/java/org/dspace/rest/FilteredCollectionsResource.java b/dspace-rest/src/main/java/org/dspace/rest/FilteredCollectionsResource.java index b0569adb81..5887c9ad39 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/FilteredCollectionsResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/FilteredCollectionsResource.java @@ -32,7 +32,7 @@ import java.util.List; /* * This class provides the items within a collection evaluated against a set of Item Filters. - * + * * @author Terry Brady, Georgetown University */ @Path("/filtered-collections") @@ -45,37 +45,53 @@ public class FilteredCollectionsResource extends Resource { /** * Return array of all collections in DSpace. You can add more properties * through expand parameter. - * + * * @param expand - * String in which is what you want to add to returned instance - * of collection. Options are: "all", "parentCommunityList", - * "parentCommunity", "topCommunity", "items", "license" and "logo". - * If you want to use multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of collection. Options are: "all", "parentCommunityList", + * "parentCommunity", "topCommunity", "items", "license" and "logo". + * If you want to use multiple options, it must be separated by commas. * @param limit - * Limit value for items in list in collection. Default value is - * 100. + * Limit value for items in list in collection. Default value is + * 100. * @param offset - * Offset of start index in list of items of collection. Default - * value is 0. + * Offset of start index in list of items of collection. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param filters + * Comma separated list of Item Filters to use to evaluate against + * the items in a collection + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. + * @param servletContext + * Context of the servlet container. * @param headers - * If you want to access to collections under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collections as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of collection, on which has logged user permission - * to view. + * to view. * @throws WebApplicationException - * It is thrown when was problem with database reading - * (SQLException) or problem with creating - * context(ContextException). + * It is thrown when was problem with database reading + * (SQLException) or problem with creating + * context(ContextException). */ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public org.dspace.rest.common.FilteredCollection[] getCollections(@QueryParam("expand") String expand, - @QueryParam("limit") @DefaultValue("100") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("filters") @DefaultValue("is_item") String filters, @QueryParam("xforwardedfor") String xforwardedfor, - @Context ServletContext servletContext, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("limit") @DefaultValue("100") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("filters") @DefaultValue("is_item") String filters, @QueryParam("xforwardedfor") String xforwardedfor, + @Context ServletContext servletContext, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Reading all filtered collections.(offset=" + offset + ",limit=" + limit + ")"); @@ -86,7 +102,7 @@ public class FilteredCollectionsResource extends Resource { { context = createContext(); if (!configurationService.getBooleanProperty("rest.reporting-authenticate", true)) { - context.turnOffAuthorisationSystem(); + context.turnOffAuthorisationSystem(); } if (!((limit != null) && (limit >= 0) && (offset != null) && (offset >= 0))) @@ -97,7 +113,7 @@ public class FilteredCollectionsResource extends Resource { } List dspaceCollections = collectionService.findAll(context, limit, offset); - for(org.dspace.content.Collection dspaceCollection : dspaceCollections) + for (org.dspace.content.Collection dspaceCollection : dspaceCollections) { if (authorizeService.authorizeActionBoolean(context, dspaceCollection, org.dspace.core.Constants.READ)) { @@ -129,68 +145,92 @@ public class FilteredCollectionsResource extends Resource { /** * Return instance of collection with passed id. You can add more properties * through expand parameter. - * + * * @param collection_id - * Id of collection in DSpace. + * Id of collection in DSpace. * @param expand - * String in which is what you want to add to returned instance - * of collection. Options are: "all", "parentCommunityList", - * "parentCommunity", "topCommunity", "items", "license" and "logo". - * If you want to use multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of collection. Options are: "all", "parentCommunityList", + * "parentCommunity", "topCommunity", "items", "license" and "logo". + * If you want to use multiple options, it must be separated by commas. * @param limit - * Limit value for items in list in collection. Default value is - * 100. + * Limit value for items in list in collection. Default value is + * 100. * @param offset - * Offset of start index in list of items of collection. Default - * value is 0. + * Offset of start index in list of items of collection. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param filters - * Comma separated list of Item Filters to use to evaluate against - * the items in a collection + * Comma separated list of Item Filters to use to evaluate against + * the items in a collection * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. + * @param servletContext + * Context of the servlet container. * @return Return instance of collection. It can also return status code - * NOT_FOUND(404) if id of collection is incorrect or status code - * UNATHORIZED(401) if user has no permission to read collection. + * NOT_FOUND(404) if id of collection is incorrect or status code + * UNATHORIZED(401) if user has no permission to read collection. * @throws WebApplicationException - * It is thrown when was problem with database reading - * (SQLException) or problem with creating - * context(ContextException). It is thrown by NOT_FOUND and - * UNATHORIZED status codes, too. + * It is thrown when was problem with database reading + * (SQLException) or problem with creating + * context(ContextException). It is thrown by NOT_FOUND and + * UNATHORIZED status codes, too. */ @GET @Path("/{collection_id}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public org.dspace.rest.common.FilteredCollection getCollection(@PathParam("collection_id") String collection_id, @QueryParam("expand") String expand, - @QueryParam("limit") @DefaultValue("1000") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, - @QueryParam("filters") @DefaultValue("is_item") String filters, - @Context HttpHeaders headers, @Context HttpServletRequest request, @Context ServletContext servletContext) { + public org.dspace.rest.common.FilteredCollection getCollection(@PathParam("collection_id") String collection_id, @QueryParam("expand") String expand, + @QueryParam("limit") @DefaultValue("1000") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, + @QueryParam("filters") @DefaultValue("is_item") String filters, + @Context HttpHeaders headers, @Context HttpServletRequest request, @Context ServletContext servletContext) + { org.dspace.core.Context context = null; FilteredCollection retColl = new org.dspace.rest.common.FilteredCollection(); - try { + try + { context = createContext(); - if (!configurationService.getBooleanProperty("rest.reporting-authenticate", true)) { - context.turnOffAuthorisationSystem(); + if (!configurationService.getBooleanProperty("rest.reporting-authenticate", true)) + { + context.turnOffAuthorisationSystem(); } org.dspace.content.Collection collection = collectionService.findByIdOrLegacyId(context, collection_id); - if(authorizeService.authorizeActionBoolean(context, collection, org.dspace.core.Constants.READ)) { - writeStats(collection, UsageEvent.Action.VIEW, user_ip, user_agent, xforwarderfor, headers, request, context); - retColl = new org.dspace.rest.common.FilteredCollection(collection, servletContext, filters, expand, context, limit, offset); - } else { + if (authorizeService.authorizeActionBoolean(context, collection, org.dspace.core.Constants.READ)) + { + writeStats(collection, UsageEvent.Action.VIEW, user_ip, + user_agent, xforwardedfor, headers, request, context); + retColl = new org.dspace.rest.common.FilteredCollection( + collection, servletContext, filters, expand, context, limit, offset); + } + else + { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } context.complete(); - } catch (SQLException e) { + } + catch (SQLException e) + { processException(e.getMessage(), context); - } catch (ContextException e) { + } + catch (ContextException e) + { processException(String.format("Could not read collection %d. %s", collection_id, e.getMessage()), context); - } finally { - processFinally(context); + } finally { + processFinally(context); } return retColl; } - } diff --git a/dspace-rest/src/main/java/org/dspace/rest/FilteredItemsResource.java b/dspace-rest/src/main/java/org/dspace/rest/FilteredItemsResource.java index bb1a4c7486..c28b3f0286 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/FilteredItemsResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/FilteredItemsResource.java @@ -61,144 +61,157 @@ public class FilteredItemsResource extends Resource { * through expand parameter. * * @param expand - * String in which is what you want to add to returned instance - * of collection. Options are: "all", "parentCommunityList", - * "parentCommunity", "items", "license" and "logo". If you want - * to use multiple options, it must be separated by commas. + * String in which is what you want to add to returned instance + * of collection. Options are: "all", "parentCommunityList", + * "parentCommunity", "items", "license" and "logo". If you want + * to use multiple options, it must be separated by commas. * @param limit - * Limit value for items in list in collection. Default value is - * 100. + * Limit value for items in list in collection. Default value is + * 100. * @param offset - * Offset of start index in list of items of collection. Default - * value is 0. + * Offset of start index in list of items of collection. Default + * value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param filters - * Comma separated list of Item Filters to use to evaluate against - * the items in a collection - * @param query_field - * List of metadata fields to evaluate in a metadata query. - * Each list value is used in conjunction with a query_op and query_field. - * @param query_op - * List of metadata operators to use in a metadata query. - * Each list value is used in conjunction with a query_field and query_field. - * @param query_val - * List of metadata values to evaluate in a metadata query. - * Each list value is used in conjunction with a query_value and query_op. - * @param collSel - * List of collections to query. + * Comma separated list of Item Filters to use to evaluate against + * the items in a collection + * @param query_field + * List of metadata fields to evaluate in a metadata query. + * Each list value is used in conjunction with a query_op and query_field. + * @param query_op + * List of metadata operators to use in a metadata query. + * Each list value is used in conjunction with a query_field and query_field. + * @param query_val + * List of metadata values to evaluate in a metadata query. + * Each list value is used in conjunction with a query_value and query_op. + * @param collSel + * List of collections to query. * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. + * @param servletContext + * Context of the servlet container. * @return Return instance of collection. It can also return status code - * NOT_FOUND(404) if id of collection is incorrect or status code - * UNATHORIZED(401) if user has no permission to read collection. + * NOT_FOUND(404) if id of collection is incorrect or status code + * UNATHORIZED(401) if user has no permission to read collection. * @throws WebApplicationException - * It is thrown when was problem with database reading - * (SQLException) or problem with creating - * context(ContextException). It is thrown by NOT_FOUND and - * UNATHORIZED status codes, too. + * It is thrown when was problem with database reading + * (SQLException) or problem with creating + * context(ContextException). It is thrown by NOT_FOUND and + * UNATHORIZED status codes, too. */ - @GET + @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public org.dspace.rest.common.ItemFilter getItemQuery(@QueryParam("expand") String expand, - @QueryParam("limit") @DefaultValue("100") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, - @QueryParam("filters") @DefaultValue("is_item,all_filters") String filters, + @QueryParam("limit") @DefaultValue("100") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, + @QueryParam("filters") @DefaultValue("is_item,all_filters") String filters, @QueryParam("query_field[]") @DefaultValue("dc.title") List query_field, @QueryParam("query_op[]") @DefaultValue("exists") List query_op, @QueryParam("query_val[]") @DefaultValue("") List query_val, @QueryParam("collSel[]") @DefaultValue("") List collSel, - @Context HttpHeaders headers, @Context HttpServletRequest request, @Context ServletContext servletContext) { + @Context HttpHeaders headers, @Context HttpServletRequest request, @Context ServletContext servletContext) { org.dspace.core.Context context = null; ItemFilterSet itemFilterSet = new ItemFilterSet(filters, true); ItemFilter result = itemFilterSet.getAllFiltersFilter(); try { context = createContext(); if (!configurationService.getBooleanProperty("rest.reporting-authenticate", true)) { - context.turnOffAuthorisationSystem(); + context.turnOffAuthorisationSystem(); } int index = Math.min(query_field.size(), Math.min(query_op.size(), query_val.size())); List itemFilterQueries = new ArrayList(); for(int i=0; i uuids = getUuidsFromStrings(collSel); - List> listFieldList = getMetadataFieldsList(context, query_field); + List uuids = getUuidsFromStrings(collSel); + List> listFieldList = getMetadataFieldsList(context, query_field); Iterator childItems = itemService.findByMetadataQuery(context, listFieldList, query_op, query_val, uuids, regexClause, offset, limit); int count = itemFilterSet.processSaveItems(context, servletContext, childItems, true, expand); - writeStats(siteService.findSite(context), UsageEvent.Action.VIEW, user_ip, user_agent, xforwarderfor, headers, request, context); - result.annotateQuery(query_field, query_op, query_val); - result.setUnfilteredItemCount(count); - context.complete(); + writeStats(siteService.findSite(context), UsageEvent.Action.VIEW, user_ip, user_agent, xforwardedfor, headers, request, context); + result.annotateQuery(query_field, query_op, query_val); + result.setUnfilteredItemCount(count); + context.complete(); } catch (IOException e) { processException(e.getMessage(), context); } catch (SQLException e) { - processException(e.getMessage(), context); + processException(e.getMessage(), context); } catch (AuthorizeException e) { - processException(e.getMessage(), context); + processException(e.getMessage(), context); } catch (ContextException e) { - processException("Unauthorized filtered item query. " + e.getMessage(), context); - } finally { - processFinally(context); + processException("Unauthorized filtered item query. " + e.getMessage(), context); + } finally { + processFinally(context); } return result; } - - private List> getMetadataFieldsList(org.dspace.core.Context context, List query_field) throws SQLException { - List> listFieldList = new ArrayList>(); - for(String s: query_field) { - ArrayList fields = new ArrayList(); - listFieldList.add(fields); - if (s.equals("*")) { - continue; - } - String schema = ""; - String element = ""; - String qualifier = null; - String[] parts = s.split("\\."); - if (parts.length>0) { - schema = parts[0]; - } - if (parts.length>1) { - element = parts[1]; - } - if (parts.length>2) { - qualifier = parts[2]; - } + + private List> getMetadataFieldsList(org.dspace.core.Context context, List query_field) throws SQLException { + List> listFieldList = new ArrayList>(); + for(String s: query_field) { + ArrayList fields = new ArrayList(); + listFieldList.add(fields); + if (s.equals("*")) { + continue; + } + String schema = ""; + String element = ""; + String qualifier = null; + String[] parts = s.split("\\."); + if (parts.length>0) { + schema = parts[0]; + } + if (parts.length>1) { + element = parts[1]; + } + if (parts.length>2) { + qualifier = parts[2]; + } - if (Item.ANY.equals(qualifier)) { - for(MetadataField mf: metadataFieldService.findFieldsByElementNameUnqualified(context, schema, element)){ - fields.add(mf); - } - } else { - MetadataField mf = metadataFieldService.findByElement(context, schema, element, qualifier); - if (mf != null) { - fields.add(mf); - } - } - } - return listFieldList; - } - - private List getUuidsFromStrings(List collSel) { - List uuids = new ArrayList(); - for(String s: collSel) { - try { - uuids.add(UUID.fromString(s)); - } catch (IllegalArgumentException e) { - log.warn("Invalid collection UUID: " + s); - } - } - return uuids; - } + if (Item.ANY.equals(qualifier)) { + for(MetadataField mf: metadataFieldService.findFieldsByElementNameUnqualified(context, schema, element)){ + fields.add(mf); + } + } else { + MetadataField mf = metadataFieldService.findByElement(context, schema, element, qualifier); + if (mf != null) { + fields.add(mf); + } + } + } + return listFieldList; + } + + private List getUuidsFromStrings(List collSel) { + List uuids = new ArrayList(); + for(String s: collSel) { + try { + uuids.add(UUID.fromString(s)); + } catch (IllegalArgumentException e) { + log.warn("Invalid collection UUID: " + s); + } + } + return uuids; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/FiltersResource.java b/dspace-rest/src/main/java/org/dspace/rest/FiltersResource.java index 64f75b06aa..e597d13b4c 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/FiltersResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/FiltersResource.java @@ -35,15 +35,30 @@ public class FiltersResource /** * Return all Use Case Item Filters in DSpace. * + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. + * @param headers + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of metadata schemas. * @throws WebApplicationException - * It can be caused by creating context or while was problem - * with reading community from database(SQLException). + * It can be caused by creating context or while was problem + * with reading community from database(SQLException). */ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public ItemFilter[] getFilters(@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { diff --git a/dspace-rest/src/main/java/org/dspace/rest/HierarchyResource.java b/dspace-rest/src/main/java/org/dspace/rest/HierarchyResource.java index d7a8d54df6..a2f4ccd885 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/HierarchyResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/HierarchyResource.java @@ -50,44 +50,54 @@ public class HierarchyResource extends Resource { protected ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); /** - * @param headers - * If you want to access to collection under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. + * @param headers + * If you want to access the collection as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return instance of collection. It can also return status code - * NOT_FOUND(404) if id of collection is incorrect or status code + * NOT_FOUND(404) if id of collection is incorrect or status code * @throws UnsupportedEncodingException + * The Character Encoding is not supported. * @throws WebApplicationException - * It is thrown when was problem with database reading - * (SQLException) or problem with creating - * context(ContextException). It is thrown by NOT_FOUND and - * UNATHORIZED status codes, too. + * It is thrown when was problem with database reading + * (SQLException) or problem with creating + * context(ContextException). It is thrown by NOT_FOUND and + * UNATHORIZED status codes, too. */ - @GET + @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public HierarchySite getHierarchy( - @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, - @Context HttpHeaders headers, @Context HttpServletRequest request) throws UnsupportedEncodingException, WebApplicationException { - - org.dspace.core.Context context = null; - HierarchySite repo = new HierarchySite(); - + @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, + @Context HttpHeaders headers, @Context HttpServletRequest request) throws UnsupportedEncodingException, WebApplicationException { + + org.dspace.core.Context context = null; + HierarchySite repo = new HierarchySite(); + try { context = createContext(); if (!configurationService.getBooleanProperty("rest.hierarchy-authenticate", true)) { - context.turnOffAuthorisationSystem(); + context.turnOffAuthorisationSystem(); } Site site = siteService.findSite(context); repo.setId(site.getID().toString()); repo.setName(site.getName()); repo.setHandle(site.getHandle()); - List dspaceCommunities = communityService.findAllTop(context); - processCommunity(context, repo, dspaceCommunities); - } catch (Exception e) { - processException(e.getMessage(), context); - } finally { - if(context != null) { + List dspaceCommunities = communityService.findAllTop(context); + processCommunity(context, repo, dspaceCommunities); + } catch (Exception e) { + processException(e.getMessage(), context); + } finally { + if (context != null) { try { context.complete(); } catch (SQLException e) { @@ -95,39 +105,39 @@ public class HierarchyResource extends Resource { } } } - return repo; - } + return repo; + } - - private void processCommunity(org.dspace.core.Context context, HierarchyCommunity parent, List communities) throws SQLException { - if (communities == null){ - return; - } - if (communities.size() == 0) { - return; - } - List parentComms = new ArrayList(); - parent.setCommunities(parentComms); - for(Community comm: communities) { - if (!authorizeService.authorizeActionBoolean(context, comm, org.dspace.core.Constants.READ)) { - continue; - } - HierarchyCommunity mycomm = new HierarchyCommunity(comm.getID().toString(), comm.getName(), comm.getHandle()); - parentComms.add(mycomm); - List colls = comm.getCollections(); - if (colls.size() > 0) { - List myColls = new ArrayList(); - mycomm.setCollections(myColls); - for(Collection coll: colls) { - if (!authorizeService.authorizeActionBoolean(context, coll, org.dspace.core.Constants.READ)) { - continue; - } - HierarchyCollection mycoll = new HierarchyCollection(coll.getID().toString(), coll.getName(), coll.getHandle()); - myColls.add(mycoll); - } - } - processCommunity(context, mycomm, comm.getSubcommunities()); - } - - } + + private void processCommunity(org.dspace.core.Context context, HierarchyCommunity parent, List communities) throws SQLException { + if (communities == null) { + return; + } + if (communities.size() == 0) { + return; + } + List parentComms = new ArrayList(); + parent.setCommunities(parentComms); + for(Community comm: communities) { + if (!authorizeService.authorizeActionBoolean(context, comm, org.dspace.core.Constants.READ)) { + continue; + } + HierarchyCommunity mycomm = new HierarchyCommunity(comm.getID().toString(), comm.getName(), comm.getHandle()); + parentComms.add(mycomm); + List colls = comm.getCollections(); + if (colls.size() > 0) { + List myColls = new ArrayList(); + mycomm.setCollections(myColls); + for(Collection coll: colls) { + if (!authorizeService.authorizeActionBoolean(context, coll, org.dspace.core.Constants.READ)) { + continue; + } + HierarchyCollection mycoll = new HierarchyCollection(coll.getID().toString(), coll.getName(), coll.getHandle()); + myColls.add(mycoll); + } + } + processCommunity(context, mycomm, comm.getSubcommunities()); + } + + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/ItemsResource.java b/dspace-rest/src/main/java/org/dspace/rest/ItemsResource.java index 5498045564..53f0427d9a 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/ItemsResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/ItemsResource.java @@ -40,9 +40,9 @@ import java.util.List; /** * Class which provide all CRUD methods over items. - * + * * @author Rostislav Novak (Computing and Information Centre, CTU in Prague) - * + * */ // Every DSpace class used without namespace is from package org.dspace.rest.common.*. Otherwise namespace is defined. @SuppressWarnings("deprecation") @@ -63,34 +63,45 @@ public class ItemsResource extends Resource /** * Return item properties without metadata and bitstreams. You can add * additional properties by parameter expand. - * + * * @param itemId - * Id of item in DSpace. + * Id of item in DSpace. * @param expand - * String which define, what additional properties will be in - * returned item. Options are separeted by commas and are: "all", - * "metadata", "parentCollection", "parentCollectionList", - * "parentCommunityList" and "bitstreams". + * String which define, what additional properties will be in + * returned item. Options are separeted by commas and are: "all", + * "metadata", "parentCollection", "parentCollectionList", + * "parentCommunityList" and "bitstreams". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return If user is allowed to read item, it returns item. Otherwise is - * thrown WebApplicationException with response status - * UNAUTHORIZED(401) or NOT_FOUND(404) if was id incorrect. + * thrown WebApplicationException with response status + * UNAUTHORIZED(401) or NOT_FOUND(404) if was id incorrect. * @throws WebApplicationException - * This exception can be throw by NOT_FOUND(bad id of item), - * UNAUTHORIZED, SQLException if wasproblem with reading from - * database and ContextException, if there was problem with - * creating context of DSpace. + * This exception can be throw by NOT_FOUND(bad id of item), + * UNAUTHORIZED, SQLException if wasproblem with reading from + * database and ContextException, if there was problem with + * creating context of DSpace. */ @GET @Path("/{item_id}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Item getItem(@PathParam("item_id") String itemId, @QueryParam("expand") String expand, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Reading item(id=" + itemId + ")."); @@ -129,28 +140,45 @@ public class ItemsResource extends Resource * It returns an array of items in DSpace. You can define how many items in * list will be and from which index will start. Items in list are sorted by * handle, not by id. - * + * + * @param expand + * String which define, what additional properties will be in + * returned item. Options are separeted by commas and are: "all", + * "metadata", "parentCollection", "parentCollectionList", + * "parentCommunityList" and "bitstreams". * @param limit - * How many items in array will be. Default value is 100. + * How many items in array will be. Default value is 100. * @param offset - * On which index will array start. Default value is 0. + * On which index will array start. Default value is 0. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return Return array of items, on which has logged user into context - * permission. + * permission. * @throws WebApplicationException - * It can be thrown by SQLException, when was problem with - * reading items from database or ContextException, when was - * problem with creating context of DSpace. + * It can be thrown by SQLException, when was problem with + * reading items from database or ContextException, when was + * problem with creating context of DSpace. */ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Item[] getItems(@QueryParam("expand") String expand, @QueryParam("limit") @DefaultValue("100") Integer limit, - @QueryParam("offset") @DefaultValue("0") Integer offset, @QueryParam("userIP") String user_ip, - @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, - @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException + @QueryParam("offset") @DefaultValue("0") Integer offset, @QueryParam("userIP") String user_ip, + @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, + @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Reading items.(offset=" + offset + ",limit=" + limit + ")."); @@ -205,28 +233,40 @@ public class ItemsResource extends Resource /** * Returns item metadata in list. - * + * * @param itemId - * Id of item in DSpace. + * Id of item in DSpace. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return Return list of metadata fields if was everything ok. Otherwise it - * throw WebApplication exception with response code NOT_FOUND(404) - * or UNAUTHORIZED(401). + * throw WebApplication exception with response code NOT_FOUND(404) + * or UNAUTHORIZED(401). * @throws WebApplicationException - * It can be thrown by two exceptions: SQLException if was - * problem wtih reading item from database and ContextException, - * if was problem with creating context of DSpace. And can be - * thrown by NOT_FOUND and UNAUTHORIZED too. + * It can be thrown by two exceptions: SQLException if was + * problem wtih reading item from database and ContextException, + * if was problem with creating context of DSpace. And can be + * thrown by NOT_FOUND and UNAUTHORIZED too. */ @GET @Path("/{item_id}/metadata") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MetadataEntry[] getItemMetadata(@PathParam("item_id") String itemId, @QueryParam("userIP") String user_ip, - @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, - @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException + @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, + @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Reading item(id=" + itemId + ") metadata."); @@ -262,31 +302,42 @@ public class ItemsResource extends Resource /** * Return array of bitstreams in item. It can be paged. - * + * * @param itemId - * Id of item in DSpace. + * Id of item in DSpace. * @param limit - * How many items will be in array. + * How many items will be in array. * @param offset - * On which index will start array. + * On which index will start array. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return Return paged array of bitstreams in item. * @throws WebApplicationException - * It can be throw by NOT_FOUND, UNAUTHORIZED, SQLException if - * was problem with reading from database and ContextException - * if was problem with creating context of DSpace. + * It can be throw by NOT_FOUND, UNAUTHORIZED, SQLException if + * was problem with reading from database and ContextException + * if was problem with creating context of DSpace. */ @GET @Path("/{item_id}/bitstreams") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Bitstream[] getItemBitstreams(@PathParam("item_id") String itemId, - @QueryParam("limit") @DefaultValue("20") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("limit") @DefaultValue("20") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Reading item(id=" + itemId + ") bitstreams.(offset=" + offset + ",limit=" + limit + ")"); @@ -332,32 +383,43 @@ public class ItemsResource extends Resource /** * Adding metadata fields to item. If metadata key is in item, it will be * added, NOT REPLACED! - * + * * @param itemId - * Id of item in DSpace. + * Id of item in DSpace. * @param metadata - * List of metadata fields, which will be added into item. + * List of metadata fields, which will be added into item. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return It returns status code OK(200) if all was ok. UNAUTHORIZED(401) - * if user is not allowed to write to item. NOT_FOUND(404) if id of - * item is incorrect. + * if user is not allowed to write to item. NOT_FOUND(404) if id of + * item is incorrect. * @throws WebApplicationException - * It is throw by these exceptions: SQLException, if was problem - * with reading from database or writing to database. - * AuthorizeException, if was problem with authorization to item - * fields. ContextException, if was problem with creating - * context of DSpace. + * It is throw by these exceptions: SQLException, if was problem + * with reading from database or writing to database. + * AuthorizeException, if was problem with authorization to item + * fields. ContextException, if was problem with creating + * context of DSpace. */ @POST @Path("/{item_id}/metadata") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response addItemMetadata(@PathParam("item_id") String itemId, List metadata, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Adding metadata to item(id=" + itemId + ")."); @@ -402,36 +464,59 @@ public class ItemsResource extends Resource /** * Create bitstream in item. - * + * + * @param name + * Btstream name to set. + * @param description + * Btstream description to set. + * @param groupId + * ResourcePolicy group (allowed to READ). + * @param year + * ResourcePolicy start date year. + * @param month + * ResourcePolicy start date month. + * @param day + * ResourcePolicy start date day. * @param itemId - * Id of item in DSpace. + * Id of item in DSpace. * @param inputStream - * Data of bitstream in inputStream. + * Data of bitstream in inputStream. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return Returns bitstream with status code OK(200). If id of item is - * invalid , it returns status code NOT_FOUND(404). If user is not - * allowed to write to item, UNAUTHORIZED(401). + * invalid , it returns status code NOT_FOUND(404). If user is not + * allowed to write to item, UNAUTHORIZED(401). * @throws WebApplicationException - * It is thrown by these exceptions: SQLException, when was - * problem with reading/writing from/to database. - * AuthorizeException, when was problem with authorization to - * item and add bitstream to item. IOException, when was problem - * with creating file or reading from inpustream. - * ContextException. When was problem with creating context of - * DSpace. + * It is thrown by these exceptions: SQLException, when was + * problem with reading/writing from/to database. + * AuthorizeException, when was problem with authorization to + * item and add bitstream to item. IOException, when was problem + * with creating file or reading from inpustream. + * ContextException. When was problem with creating context of + * DSpace. */ // TODO Add option to add bitstream by URI.(for very big files) @POST @Path("/{item_id}/bitstreams") public Bitstream addItemBitstream(@PathParam("item_id") String itemId, InputStream inputStream, - @QueryParam("name") String name, @QueryParam("description") String description, - @QueryParam("groupId") String groupId, @QueryParam("year") Integer year, @QueryParam("month") Integer month, - @QueryParam("day") Integer day, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("name") String name, @QueryParam("description") String description, + @QueryParam("groupId") String groupId, @QueryParam("year") Integer year, @QueryParam("month") Integer month, + @QueryParam("day") Integer day, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Adding bitstream to item(id=" + itemId + ")."); @@ -451,10 +536,10 @@ public class ItemsResource extends Resource org.dspace.content.Bitstream dspaceBitstream = null; List bundles = itemService.getBundles(dspaceItem, org.dspace.core.Constants.CONTENT_BUNDLE_NAME); - if(bundles != null && bundles.size() != 0) - { - bundle = bundles.get(0); // There should be only one bundle ORIGINAL. - } + if(bundles != null && bundles.size() != 0) + { + bundle = bundles.get(0); // There should be only one bundle ORIGINAL. + } if (bundle == null) { log.trace("Creating bundle in item."); @@ -573,32 +658,43 @@ public class ItemsResource extends Resource /** * Replace all metadata in item with new passed metadata. - * + * * @param itemId - * Id of item in DSpace. + * Id of item in DSpace. * @param metadata - * List of metadata fields, which will replace old metadata in - * item. + * List of metadata fields, which will replace old metadata in + * item. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return It returns status code: OK(200). NOT_FOUND(404) if item was not - * found, UNAUTHORIZED(401) if user is not allowed to write to item. + * found, UNAUTHORIZED(401) if user is not allowed to write to item. * @throws WebApplicationException - * It is thrown by: SQLException, when was problem with database - * reading or writting, AuthorizeException when was problem with - * authorization to item and metadata fields. And - * ContextException, when was problem with creating context of - * DSpace. + * It is thrown by: SQLException, when was problem with database + * reading or writting, AuthorizeException when was problem with + * authorization to item and metadata fields. And + * ContextException, when was problem with creating context of + * DSpace. */ @PUT @Path("/{item_id}/metadata") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response updateItemMetadata(@PathParam("item_id") String itemId, MetadataEntry[] metadata, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Updating metadata in item(id=" + itemId + ")."); @@ -658,28 +754,40 @@ public class ItemsResource extends Resource /** * Delete item from DSpace. It delete bitstreams only from item bundle. - * + * * @param itemId - * Id of item which will be deleted. + * Id of item which will be deleted. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return It returns status code: OK(200). NOT_FOUND(404) if item was not - * found, UNAUTHORIZED(401) if user is not allowed to delete item - * metadata. + * found, UNAUTHORIZED(401) if user is not allowed to delete item + * metadata. * @throws WebApplicationException - * It can be thrown by: SQLException, when was problem with - * database reading. AuthorizeException, when was problem with - * authorization to item.(read and delete) IOException, when was - * problem with deleting bitstream file. ContextException, when - * was problem with creating context of DSpace. + * It can be thrown by: SQLException, when was problem with + * database reading. AuthorizeException, when was problem with + * authorization to item.(read and delete) IOException, when was + * problem with deleting bitstream file. ContextException, when + * was problem with creating context of DSpace. */ @DELETE @Path("/{item_id}") public Response deleteItem(@PathParam("item_id") String itemId, @QueryParam("userIP") String user_ip, - @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, - @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException + @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, + @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Deleting item(id=" + itemId + ")."); @@ -725,28 +833,40 @@ public class ItemsResource extends Resource /** * Delete all item metadata. - * + * * @param itemId - * Id of item in DSpace. + * Id of item in DSpace. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return It returns status code: OK(200). NOT_FOUND(404) if item was not - * found, UNAUTHORIZED(401) if user is not allowed to delete item - * metadata. + * found, UNAUTHORIZED(401) if user is not allowed to delete item + * metadata. * @throws WebApplicationException - * Thrown by three exceptions. SQLException, when there was - * a problem reading item from database or editing metadata - * fields. AuthorizeException, when there was a problem with - * authorization to item. And ContextException, when there was a problem - * with creating a DSpace context. + * Thrown by three exceptions. SQLException, when there was + * a problem reading item from database or editing metadata + * fields. AuthorizeException, when there was a problem with + * authorization to item. And ContextException, when there was a problem + * with creating a DSpace context. */ @DELETE @Path("/{item_id}/metadata") public Response deleteItemMetadata(@PathParam("item_id") String itemId, @QueryParam("userIP") String user_ip, - @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, - @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException + @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, + @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Deleting metadata in item(id=" + itemId + ")."); @@ -761,7 +881,7 @@ public class ItemsResource extends Resource log.trace("Deleting metadata."); // TODO Rewrite without deprecated object. Leave there only generated metadata. - + String valueAccessioned = itemService.getMetadataFirstValue(dspaceItem, "dc", "date", "accessioned", org.dspace.content.Item.ANY); String valueAvailable = itemService.getMetadataFirstValue(dspaceItem, "dc", "date", "available", org.dspace.content.Item.ANY); String valueURI = itemService.getMetadataFirstValue(dspaceItem, "dc", "identifier", "uri", org.dspace.content.Item.ANY); @@ -797,31 +917,42 @@ public class ItemsResource extends Resource /** * Delete bitstream from item bundle. - * + * * @param itemId - * Id of item in DSpace. - * @param headers - * If you want to access to item under logged user into context. - * In headers must be set header "rest-dspace-token" with passed - * token from login method. + * Id of item in DSpace. * @param bitstreamId - * Id of bitstream, which will be deleted from bundle. + * Id of bitstream, which will be deleted from bundle. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. + * @param headers + * If you want to access the item as the user logged into the context. + * The value of the "rest-dspace-token" header must be set with passed + * token from login method. + * @param request + * Servlet's HTTP request object. * @return Return status code OK(200) if is all ok. NOT_FOUND(404) if item - * or bitstream was not found. UNAUTHORIZED(401) if user is not - * allowed to delete bitstream. + * or bitstream was not found. UNAUTHORIZED(401) if user is not + * allowed to delete bitstream. * @throws WebApplicationException - * It is thrown, when: Was problem with edditting database, - * SQLException. Or problem with authorization to item, bundle - * or bitstream, AuthorizeException. When was problem with - * deleting file IOException. Or problem with creating context - * of DSpace, ContextException. + * It is thrown, when: Was problem with edditting database, + * SQLException. Or problem with authorization to item, bundle + * or bitstream, AuthorizeException. When was problem with + * deleting file IOException. Or problem with creating context + * of DSpace, ContextException. */ @DELETE @Path("/{item_id}/bitstreams/{bitstream_id}") public Response deleteItemBitstream(@PathParam("item_id") String itemId, @PathParam("bitstream_id") String bitstreamId, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Deleting bitstream in item(id=" + itemId + ")."); @@ -884,28 +1015,44 @@ public class ItemsResource extends Resource /** * Find items by one metadata field. - * + * * @param metadataEntry - * Metadata field to search by. + * Metadata field to search by. + * @param expand + * String which define, what additional properties will be in + * returned item. Options are separeted by commas and are: "all", + * "metadata", "parentCollection", "parentCollectionList", + * "parentCommunityList" and "bitstreams". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access the item as the user logged into context, - * header "rest-dspace-token" must be set to token value retrieved - * from the login method. + * If you want to access the item as the user logged into context, + * header "rest-dspace-token" must be set to token value retrieved + * from the login method. + * @param request + * Servlet's HTTP request object. * @return Return array of found items. * @throws WebApplicationException - * Can be thrown: SQLException - problem with - * database reading. AuthorizeException - problem with - * authorization to item. IOException - problem with - * reading from metadata field. ContextException - - * problem with creating DSpace context. + * Can be thrown: SQLException - problem with + * database reading. AuthorizeException - problem with + * authorization to item. IOException - problem with + * reading from metadata field. ContextException - + * problem with creating DSpace context. */ @POST @Path("/find-by-metadata-field") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Item[] findItemsByMetadataField(MetadataEntry metadataEntry, @QueryParam("expand") String expand, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) - throws WebApplicationException + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + throws WebApplicationException { log.info("Looking for item with metadata(key=" + metadataEntry.getKey() + ",value=" + metadataEntry.getValue() @@ -971,19 +1118,20 @@ public class ItemsResource extends Resource * Find item from DSpace database. It is encapsulation of method * org.dspace.content.Item.find with checking if item exist and if user * logged into context has permission to do passed action. - * + * * @param context - * Context of actual logged user. + * Context of actual logged user. * @param id - * Id of item in DSpace. + * Id of item in DSpace. * @param action - * Constant from org.dspace.core.Constants. + * Constant from org.dspace.core.Constants. * @return It returns DSpace item. * @throws WebApplicationException - * Is thrown when item with passed id is not exists and if user - * has no permission to do passed action. + * Is thrown when item with passed id is not exists and if user + * has no permission to do passed action. */ - private org.dspace.content.Item findItem(org.dspace.core.Context context, String id, int action) throws WebApplicationException + private org.dspace.content.Item findItem(org.dspace.core.Context context, String id, int action) + throws WebApplicationException { org.dspace.content.Item item = null; try diff --git a/dspace-rest/src/main/java/org/dspace/rest/MetadataRegistryResource.java b/dspace-rest/src/main/java/org/dspace/rest/MetadataRegistryResource.java index ea0fd1113d..1d1a99df61 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/MetadataRegistryResource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/MetadataRegistryResource.java @@ -75,19 +75,34 @@ public class MetadataRegistryResource extends Resource * Return all metadata registry items in DSpace. * * @param expand - * String in which is what you want to add to returned instance - * of metadata schema. Options are: "all", "fields". Default value "fields". + * String in which is what you want to add to returned instance + * of metadata schema. Options are: "all", "fields". Default value "fields". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. + * @param headers + * If you want to access the metadata schema as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return array of metadata schemas. * @throws WebApplicationException - * It can be caused by creating context or while was problem - * with reading schema from database(SQLException). + * It can be caused by creating context or while was problem + * with reading schema from database(SQLException). */ @GET @Path("/schema") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MetadataSchema[] getSchemas(@QueryParam("expand") @DefaultValue("fields") String expand, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { @@ -129,26 +144,37 @@ public class MetadataRegistryResource extends Resource * parameter or method for metadata fields. * * @param schemaPrefix - * Prefix for schema in DSpace. + * Prefix for schema in DSpace. * @param expand - * String in which is what you want to add to returned instance - * of metadata schema. Options are: "all", "fields". Default value "fields". + * String in which is what you want to add to returned instance + * of metadata schema. Options are: "all", "fields". Default value "fields". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to metadata schema under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the metadata schema as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return instance of org.dspace.rest.common.MetadataSchema. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading. Also if id/prefix of schema is incorrect - * or logged user into context has no permission to read. + * Thrown if there was a problem with creating context or problem + * with database reading. Also if id/prefix of schema is incorrect + * or logged user into context has no permission to read. */ @GET @Path("/schema/{schema_prefix}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MetadataSchema getSchema(@PathParam("schema_prefix") String schemaPrefix, @QueryParam("expand") @DefaultValue("fields") String expand, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { @@ -163,7 +189,7 @@ public class MetadataRegistryResource extends Resource org.dspace.content.MetadataSchema schema = metadataSchemaService.find(context, schemaPrefix); metadataSchema = new MetadataSchema(schema, expand, context); if (schema == null) { - processException(String.format("Schema not found for index %s", schemaPrefix), context); + processException(String.format("Schema not found for index %s", schemaPrefix), context); } context.complete(); @@ -189,66 +215,88 @@ public class MetadataRegistryResource extends Resource * Returns metadata field with basic properties. * * @param schemaPrefix - * Prefix for schema in DSpace. + * Prefix for schema in DSpace. * @param element - * Unqualified element name for field in the metadata registry. + * Unqualified element name for field in the metadata registry. * @param expand - * String in which is what you want to add to returned instance - * of the metadata field. Options are: "all", "parentSchema". Default value "". + * String in which is what you want to add to returned instance + * of the metadata field. Options are: "all", "parentSchema". Default value "". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return instance of org.dspace.rest.common.MetadataField. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading. Also if id of field is incorrect - * or logged user into context has no permission to read. + * Thrown if there was a problem with creating context or problem + * with database reading. Also if id of field is incorrect + * or logged user into context has no permission to read. */ @GET @Path("/schema/{schema_prefix}/metadata-fields/{element}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MetadataField getMetadataFieldUnqualified(@PathParam("schema_prefix") String schemaPrefix, - @PathParam("element") String element, - @QueryParam("expand") String expand, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + @PathParam("element") String element, + @QueryParam("expand") String expand, + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { - return getMetadataFieldQualified(schemaPrefix, element, "", expand, user_ip, user_agent, xforwarderfor, headers, request); + return getMetadataFieldQualified(schemaPrefix, element, "", expand, user_ip, user_agent, xforwardedfor, headers, request); } /** * Returns metadata field with basic properties. * * @param schemaPrefix - * Prefix for schema in DSpace. + * Prefix for schema in DSpace. * @param element - * Element name for field in the metadata registry. + * Element name for field in the metadata registry. * @param qualifier - * Element name qualifier for field in the metadata registry. + * Element name qualifier for field in the metadata registry. * @param expand - * String in which is what you want to add to returned instance - * of the metadata field. Options are: "all", "parentSchema". Default value "". + * String in which is what you want to add to returned instance + * of the metadata field. Options are: "all", "parentSchema". Default value "". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return instance of org.dspace.rest.common.MetadataField. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading. Also if id of field is incorrect - * or logged user into context has no permission to read. + * Thrown if there was a problem with creating context or problem + * with database reading. Also if id of field is incorrect + * or logged user into context has no permission to read. */ @GET @Path("/schema/{schema_prefix}/metadata-fields/{element}/{qualifier}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MetadataField getMetadataFieldQualified(@PathParam("schema_prefix") String schemaPrefix, - @PathParam("element") String element, - @PathParam("qualifier") @DefaultValue("") String qualifier, - @QueryParam("expand") String expand, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + @PathParam("element") String element, + @PathParam("qualifier") @DefaultValue("") String qualifier, + @QueryParam("expand") String expand, + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { @@ -297,27 +345,38 @@ public class MetadataRegistryResource extends Resource * Returns metadata field with basic properties. * * @param fieldId - * Id of metadata field in DSpace. + * Id of metadata field in DSpace. * @param expand - * String in which is what you want to add to returned instance - * of the metadata field. Options are: "all", "parentSchema". Default value "parentSchema". + * String in which is what you want to add to returned instance + * of the metadata field. Options are: "all", "parentSchema". Default value "parentSchema". + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to community under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the community as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return instance of org.dspace.rest.common.MetadataField. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading. Also if id of field is incorrect - * or logged user into context has no permission to read. + * Thrown if there was a problem with creating context or problem + * with database reading. Also if id of field is incorrect + * or logged user into context has no permission to read. */ @GET @Path("/metadata-fields/{field_id}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MetadataField getMetadataField(@PathParam("field_id") Integer fieldId, - @QueryParam("expand") @DefaultValue("parentSchema") String expand, - @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, - @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) + @QueryParam("expand") @DefaultValue("parentSchema") String expand, + @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, + @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { @@ -364,18 +423,29 @@ public class MetadataRegistryResource extends Resource * Create schema in the schema registry. Creating a schema is restricted to admin users. * * @param schema - * Schema that will be added to the metadata registry. + * Schema that will be added to the metadata registry. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to schema under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the schema as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response 200 if was everything all right. Otherwise 400 - * when id of community was incorrect or 401 if was problem with - * permission to write into collection. - * Returns the schema (schemaId), if was all ok. + * when id of community was incorrect or 401 if was problem with + * permission to write into collection. + * Returns the schema (schemaId), if was all ok. * @throws WebApplicationException - * It can be thrown by SQLException, AuthorizeException and - * ContextException. + * It can be thrown by SQLException, AuthorizeException and + * ContextException. */ @POST @Path("/schema") @@ -432,7 +502,7 @@ public class MetadataRegistryResource extends Resource } catch (NonUniqueMetadataException e) { processException("Could not create new metadata schema, NonUniqueMetadataException. Message: " + e.getMessage(), context); - } + } catch (Exception e) { processException("Could not create new metadata schema, Exception. Class: " + e.getClass(), context); @@ -450,25 +520,38 @@ public class MetadataRegistryResource extends Resource * Create a new metadata field within a schema. * Creating a metadata field is restricted to admin users. * + * @param schemaPrefix + * Prefix for schema in DSpace. * @param field - * Field that will be added to the metadata registry for a schema. + * Field that will be added to the metadata registry for a schema. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to schema under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the schema as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response 200 if was everything all right. Otherwise 400 - * when id of community was incorrect or 401 if was problem with - * permission to write into collection. - * Returns the field (with fieldId), if was all ok. + * when id of community was incorrect or 401 if was problem with + * permission to write into collection. + * Returns the field (with fieldId), if was all ok. * @throws WebApplicationException - * It can be thrown by SQLException, AuthorizeException and - * ContextException. + * It can be thrown by SQLException, AuthorizeException and + * ContextException. */ @POST @Path("/schema/{schema_prefix}/metadata-fields") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MetadataField createMetadataField(@PathParam("schema_prefix") String schemaPrefix, - MetadataField field, @QueryParam("userIP") String user_ip, + MetadataField field, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { @@ -520,7 +603,7 @@ public class MetadataRegistryResource extends Resource } catch (NonUniqueMetadataException e) { processException("Could not create new metadata field, NonUniqueMetadataException. Message: " + e.getMessage(), context); - } + } catch (Exception e) { processException("Could not create new metadata field, Exception. Message: " + e.getMessage(), context); @@ -541,20 +624,31 @@ public class MetadataRegistryResource extends Resource * Update metadata field. Replace all information about community except the id and the containing schema. * * @param fieldId - * Id of the field in the DSpace metdata registry. + * Id of the field in the DSpace metdata registry. * @param field - * Instance of the metadata field which will replace actual metadata field in - * DSpace. + * Instance of the metadata field which will replace actual metadata field in + * DSpace. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to metadata field under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the metadata field as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Response 200 if was all ok. Otherwise 400 if was id incorrect or - * 401 if logged user has no permission to update the metadata field. + * 401 if logged user has no permission to update the metadata field. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or writing. Or problem with writing to - * community caused by authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or writing. Or problem with writing to + * community caused by authorization. */ @PUT @Path("/metadata-fields/{field_id}") @@ -603,10 +697,10 @@ public class MetadataRegistryResource extends Resource } catch (NonUniqueMetadataException e) { processException("Could not update metadata field(id=" + fieldId + "), NonUniqueMetadataException. Message:" + e, context); - } + } catch (IOException e) { processException("Could not update metadata field(id=" + fieldId + "), IOException. Message:" + e, context); - } + } finally { processFinally(context); @@ -620,18 +714,29 @@ public class MetadataRegistryResource extends Resource * Delete metadata field from the DSpace metadata registry * * @param fieldId - * Id of the metadata field in DSpace. + * Id of the metadata field in DSpace. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to metadata field under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the metadata field as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response code OK(200) if was everything all right. - * Otherwise return NOT_FOUND(404) if was id of metadata field is incorrect. - * Or (UNAUTHORIZED)401 if was problem with permission to metadata field. + * Otherwise return NOT_FOUND(404) if was id of metadata field is incorrect. + * Or (UNAUTHORIZED)401 if was problem with permission to metadata field. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or deleting. Or problem with deleting - * metadata field caused by IOException or authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or deleting. Or problem with deleting + * metadata field caused by IOException or authorization. */ @DELETE @Path("/metadata-fields/{field_id}") @@ -686,18 +791,29 @@ public class MetadataRegistryResource extends Resource * Delete metadata schema from the DSpace metadata registry * * @param schemaId - * Id of the metadata schema in DSpace. + * Id of the metadata schema in DSpace. + * @param user_ip + * User's IP address. + * @param user_agent + * User agent string (specifies browser used and its version). + * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers - * If you want to access to metadata schema under logged user into - * context. In headers must be set header "rest-dspace-token" - * with passed token from login method. + * If you want to access the metadata schema as the user logged into the + * context. The value of the "rest-dspace-token" header must be set + * to the token received from the login method response. + * @param request + * Servlet's HTTP request object. * @return Return response code OK(200) if was everything all right. - * Otherwise return NOT_FOUND(404) if was id of metadata schema is incorrect. - * Or (UNAUTHORIZED)401 if was problem with permission to metadata schema. + * Otherwise return NOT_FOUND(404) if was id of metadata schema is incorrect. + * Or (UNAUTHORIZED)401 if was problem with permission to metadata schema. * @throws WebApplicationException - * It is throw when was problem with creating context or problem - * with database reading or deleting. Or problem with deleting - * metadata schema caused by IOException or authorization. + * Thrown if there was a problem with creating context or problem + * with database reading or deleting. Or problem with deleting + * metadata schema caused by IOException or authorization. */ @DELETE @Path("/schema/{schema_id}") diff --git a/dspace-rest/src/main/java/org/dspace/rest/Resource.java b/dspace-rest/src/main/java/org/dspace/rest/Resource.java index 504b44f8b9..3773665ce6 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/Resource.java +++ b/dspace-rest/src/main/java/org/dspace/rest/Resource.java @@ -68,12 +68,14 @@ public class Resource * if there was a problem creating context. * * @return Newly created context with the logged in user unless the specified user was null. - * If user is null, create the context without a logged in user. + * If user is null, create the context without a logged in user. * @throws ContextException - * Thrown in case of a problem creating context. Can be caused by - * SQLException error in creating context or finding the user to - * log in. Can be caused by AuthorizeException if there was a - * problem authorizing the found user. + * Thrown in case of a problem creating context. Can be caused by + * SQLException error in creating context or finding the user to + * log in. Can be caused by AuthorizeException if there was a + * problem authorizing the found user. + * @throws SQLException + * An exception that provides information on a database access error or other errors. */ protected static org.dspace.core.Context createContext() throws ContextException, SQLException { org.dspace.core.Context context = new org.dspace.core.Context(); @@ -95,15 +97,26 @@ public class Resource /** * Records a statistics event about an object used via REST API. * @param dspaceObject - * DSpace object on which a request was performed. + * DSpace object on which a request was performed. * @param action - * Action that was performed. + * Action that was performed. * @param user_ip + * User's IP address. * @param user_agent + * User agent string (specifies browser used and its version). * @param xforwardedfor + * When accessed via a reverse proxy, the application sees the proxy's IP as the + * source of the request. The proxy may be configured to add the + * "X-Forwarded-For" HTTP header containing the original IP of the client + * so that the reverse-proxied application can get the client's IP. * @param headers + * If you want to access the item as the user logged into the + * context. The header "rest-dspace-token" with the token passed + * from the login method must be set. * @param request + * Servlet's HTTP request object. * @param context + * Context which must be aborted. */ protected void writeStats(DSpaceObject dspaceObject, UsageEvent.Action action, String user_ip, String user_agent, String xforwardedfor, HttpHeaders headers, HttpServletRequest request, Context context) @@ -131,11 +144,11 @@ public class Resource * context. * * @param message - * Message, which will be printed to error stream. + * Message, which will be printed to error stream. * @param context - * Context which must be aborted. + * Context which must be aborted. * @throws WebApplicationException - * This exception is throw for user of REST api. + * This exception is throw for user of REST api. */ protected static void processException(String message, org.dspace.core.Context context) throws WebApplicationException { @@ -152,9 +165,9 @@ public class Resource * and abort DSpace context, if was not properly ended. * * @param context - * Context which must be aborted. + * Context which must be aborted. * @throws WebApplicationException - * This exception is throw for user of REST api. + * This exception is thrown for user of REST API. */ protected void processFinally(org.dspace.core.Context context) throws WebApplicationException { @@ -170,7 +183,7 @@ public class Resource * Split string with regex ".". * * @param key - * String which will be splitted. + * String which will be splitted. * @return String array filed with separated string. */ protected String[] mySplit(String key) @@ -203,7 +216,7 @@ public class Resource * org.dspace.core.Constants.{READ,WRITE,DELETE}. * * @param action - * Constant from org.dspace.core.Constants.* + * Constant from org.dspace.core.Constants.* * @return String representation. read or write or delete. */ protected String getActionString(int action) diff --git a/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java b/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java index e43ec9c846..a579e52a8e 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java +++ b/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java @@ -37,9 +37,9 @@ import org.dspace.utils.DSpace; /** * Root of RESTful api. It provides login and logout. Also have method for * printing every method which is provides by RESTful api. - * + * * @author Rostislav Novak (Computing and Information Centre, CTU in Prague) - * + * */ @Path("/") public class RestIndex { @@ -49,80 +49,83 @@ public class RestIndex { /** * Return html page with information about REST api. It contains methods all * methods provide by REST api. - * - * @return HTML page which has information about all methods of REST api. + * + * @param servletContext + * Context of the servlet container. + * @return HTML page which has information about all methods of REST API. */ @GET @Produces(MediaType.TEXT_HTML) - public String sayHtmlHello(@Context ServletContext servletContext) { - // TODO Better graphics, add arguments to all methods. (limit, offset, item and so on) + public String sayHtmlHello(@Context ServletContext servletContext) + { + // TODO Better graphics, add arguments to all methods. (limit, offset, item and so on) return "DSpace REST - index" + "" - + "

    DSpace REST API

    " + - "Server path: " + servletContext.getContextPath() + - "

    Index

    " + - "
      " + - "
    • GET / - Return this page.
    • " + - "
    • GET /test - Return the string \"REST api is running\" for testing purposes.
    • " + - "
    • POST /login - Method for logging into the DSpace RESTful API. You must post User class. Example: {\"email\":\"test@dspace\",\"password\":\"pass\"}. Returns a token which must be included in future requests in the \"rest-dspace-token\" header.
    • " + - "
    • POST /logout - Method for logging out of the DSpace RESTful API. The request must include the \"rest-dspace-token\" token
    • header." + - "
    " + - "

    Communities

    " + - "
      " + - "
    • GET /communities - Return an array of all communities in DSpace.
    • " + - "
    • GET /communities/top-communities - Returns an array of all top-leve communities in DSpace.
    • " + - "
    • GET /communities/{communityId} - Returns a community with the specified ID.
    • " + - "
    • GET /communities/{communityId}/collections - Returns an array of collections of the specified community.
    • " + - "
    • GET /communities/{communityId}/communities - Returns an array of subcommunities of the specified community.
    • " + - "
    • POST /communities - Create a new top-level community. You must post a community.
    • " + - "
    • POST /communities/{communityId}/collections - Create a new collection in the specified community. You must post a collection.
    • " + - "
    • POST /communities/{communityId}/communities - Create a new subcommunity in the specified community. You must post a community.
    • " + - "
    • PUT /communities/{communityId} - Update the specified community.
    • " + - "
    • DELETE /communities/{communityId} - Delete the specified community.
    • " + - "
    • DELETE /communities/{communityId}/collections/{collectionId} - Delete the specified collection in the specified community.
    • " + - "
    • DELETE /communities/{communityId}/communities/{communityId2} - Delete the specified subcommunity (communityId2) in the specified community (communityId).
    • " + - "
    " + - "

    Collections

    " + - "
      " + - "
    • GET /collections - Return all DSpace collections in array.
    • " + - "
    • GET /collections/{collectionId} - Return a collection with the specified ID.
    • " + - "
    • GET /collections/{collectionId}/items - Return all items of the specified collection.
    • " + - "
    • POST /collections/{collectionId}/items - Create an item in the specified collection. You must post an item.
    • " + - "
    • POST /collections/find-collection - Find a collection by name.
    • " + - "
    • PUT /collections/{collectionId}
    • - Update the specified collection. You must post a collection." + - "
    • DELETE /collections/{collectionId} - Delete the specified collection from DSpace.
    • " + - "
    • DELETE /collections/{collectionId}/items/{itemId} - Delete the specified item (itemId) in the specified collection (collectionId).
    • " + - "
    " + - "

    Items

    " + - "
      " + - "
    • GET /items - Return a list of items.
    • " + - "
    • GET /items/{item id} - Return the specified item.
    • " + - "
    • GET /items/{item id}/metadata - Return metadata of the specified item.
    • " + - "
    • GET /items/{item id}/bitstreams - Return bitstreams of the specified item.
    • " + - "
    • POST /items/find-by-metadata-field - Find items by the specified metadata value.
    • " + - "
    • POST /items/{item id}/metadata - Add metadata to the specified item.
    • " + - "
    • POST /items/{item id}/bitstreams - Add a bitstream to the specified item.
    • " + - "
    • PUT /items/{item id}/metadata - Update metadata in the specified item.
    • " + - "
    • DELETE /items/{item id} - Delete the specified item.
    • " + - "
    • DELETE /items/{item id}/metadata - Clear metadata of the specified item.
    • " + - "
    • DELETE /items/{item id}/bitstreams/{bitstream id} - Delete the specified bitstream of the specified item.
    • " + - "
    " + - "

    Bitstreams

    " + - "
      " + - "
    • GET /bitstreams - Return all bitstreams in DSpace.
    • " + - "
    • GET /bitstreams/{bitstream id} - Return the specified bitstream.
    • " + - "
    • GET /bitstreams/{bitstream id}/policy - Return policies of the specified bitstream.
    • " + - "
    • GET /bitstreams/{bitstream id}/retrieve - Return the contents of the specified bitstream.
    • " + - "
    • POST /bitstreams/{bitstream id}/policy - Add a policy to the specified bitstream.
    • " + - "
    • PUT /bitstreams/{bitstream id}/data - Update the contents of the specified bitstream.
    • " + - "
    • PUT /bitstreams/{bitstream id} - Update metadata of the specified bitstream.
    • " + - "
    • DELETE /bitstreams/{bitstream id} - Delete the specified bitstream from DSpace.
    • " + - "
    • DELETE /bitstreams/{bitstream id}/policy/{policy_id} - Delete the specified bitstream policy.
    • " + - "
    " + - "

    Hierarchy

    " + - "
      " + - "
    • GET /hierarchy - Return hierarchy of communities and collections in tree form. Each object is minimally populated (name, handle, id) for efficient retrieval.
    • " + - "
    " + + + "

    DSpace REST API

    " + + "Server path: " + servletContext.getContextPath() + + "

    Index

    " + + "
      " + + "
    • GET / - Return this page.
    • " + + "
    • GET /test - Return the string \"REST api is running\" for testing purposes.
    • " + + "
    • POST /login - Method for logging into the DSpace RESTful API. You must post User class. Example: {\"email\":\"test@dspace\",\"password\":\"pass\"}. Returns a token which must be included in future requests in the \"rest-dspace-token\" header.
    • " + + "
    • POST /logout - Method for logging out of the DSpace RESTful API. The request must include the \"rest-dspace-token\" token
    • header." + + "
    " + + "

    Communities

    " + + "
      " + + "
    • GET /communities - Return an array of all communities in DSpace.
    • " + + "
    • GET /communities/top-communities - Returns an array of all top-leve communities in DSpace.
    • " + + "
    • GET /communities/{communityId} - Returns a community with the specified ID.
    • " + + "
    • GET /communities/{communityId}/collections - Returns an array of collections of the specified community.
    • " + + "
    • GET /communities/{communityId}/communities - Returns an array of subcommunities of the specified community.
    • " + + "
    • POST /communities - Create a new top-level community. You must post a community.
    • " + + "
    • POST /communities/{communityId}/collections - Create a new collection in the specified community. You must post a collection.
    • " + + "
    • POST /communities/{communityId}/communities - Create a new subcommunity in the specified community. You must post a community.
    • " + + "
    • PUT /communities/{communityId} - Update the specified community.
    • " + + "
    • DELETE /communities/{communityId} - Delete the specified community.
    • " + + "
    • DELETE /communities/{communityId}/collections/{collectionId} - Delete the specified collection in the specified community.
    • " + + "
    • DELETE /communities/{communityId}/communities/{communityId2} - Delete the specified subcommunity (communityId2) in the specified community (communityId).
    • " + + "
    " + + "

    Collections

    " + + "
      " + + "
    • GET /collections - Return all DSpace collections in array.
    • " + + "
    • GET /collections/{collectionId} - Return a collection with the specified ID.
    • " + + "
    • GET /collections/{collectionId}/items - Return all items of the specified collection.
    • " + + "
    • POST /collections/{collectionId}/items - Create an item in the specified collection. You must post an item.
    • " + + "
    • POST /collections/find-collection - Find a collection by name.
    • " + + "
    • PUT /collections/{collectionId}
    • - Update the specified collection. You must post a collection." + + "
    • DELETE /collections/{collectionId} - Delete the specified collection from DSpace.
    • " + + "
    • DELETE /collections/{collectionId}/items/{itemId} - Delete the specified item (itemId) in the specified collection (collectionId).
    • " + + "
    " + + "

    Items

    " + + "
      " + + "
    • GET /items - Return a list of items.
    • " + + "
    • GET /items/{item id} - Return the specified item.
    • " + + "
    • GET /items/{item id}/metadata - Return metadata of the specified item.
    • " + + "
    • GET /items/{item id}/bitstreams - Return bitstreams of the specified item.
    • " + + "
    • POST /items/find-by-metadata-field - Find items by the specified metadata value.
    • " + + "
    • POST /items/{item id}/metadata - Add metadata to the specified item.
    • " + + "
    • POST /items/{item id}/bitstreams - Add a bitstream to the specified item.
    • " + + "
    • PUT /items/{item id}/metadata - Update metadata in the specified item.
    • " + + "
    • DELETE /items/{item id} - Delete the specified item.
    • " + + "
    • DELETE /items/{item id}/metadata - Clear metadata of the specified item.
    • " + + "
    • DELETE /items/{item id}/bitstreams/{bitstream id} - Delete the specified bitstream of the specified item.
    • " + + "
    " + + "

    Bitstreams

    " + + "
      " + + "
    • GET /bitstreams - Return all bitstreams in DSpace.
    • " + + "
    • GET /bitstreams/{bitstream id} - Return the specified bitstream.
    • " + + "
    • GET /bitstreams/{bitstream id}/policy - Return policies of the specified bitstream.
    • " + + "
    • GET /bitstreams/{bitstream id}/retrieve - Return the contents of the specified bitstream.
    • " + + "
    • POST /bitstreams/{bitstream id}/policy - Add a policy to the specified bitstream.
    • " + + "
    • PUT /bitstreams/{bitstream id}/data - Update the contents of the specified bitstream.
    • " + + "
    • PUT /bitstreams/{bitstream id} - Update metadata of the specified bitstream.
    • " + + "
    • DELETE /bitstreams/{bitstream id} - Delete the specified bitstream from DSpace.
    • " + + "
    • DELETE /bitstreams/{bitstream id}/policy/{policy_id} - Delete the specified bitstream policy.
    • " + + "
    " + + "

    Hierarchy

    " + + "
      " + + "
    • GET /hierarchy - Return hierarchy of communities and collections in tree form. Each object is minimally populated (name, handle, id) for efficient retrieval.
    • " + + "
    " + "

    Metadata and Schema Registry

    " + "
      " + "
    • GET /registries/schema - Return the list of metadata schemas in the registry
    • " + @@ -147,10 +150,10 @@ public class RestIndex { "
    " + " "; } - + /** * Method only for testing whether the REST API is running. - * + * * @return String "REST api is running." */ @GET @@ -162,7 +165,7 @@ public class RestIndex { /** * Method to login a user into REST API. - * + * * @return Returns response code OK and a token. Otherwise returns response * code FORBIDDEN(403). */ @@ -175,56 +178,61 @@ public class RestIndex { return Response.ok().build(); } - @GET - @Path("/shibboleth-login") - @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Response shibbolethLogin() - { - //If you can get here, you are authenticated, the actual login is handled by spring security - return Response.ok().build(); - } + @GET + @Path("/shibboleth-login") + @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public Response shibbolethLogin() + { + //If you can get here, you are authenticated, the actual login is handled by spring security + return Response.ok().build(); + } - @GET - @Path("/login-shibboleth") - @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Response shibbolethLoginEndPoint() - { - org.dspace.core.Context context = null; - try { - context = Resource.createContext(); - AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); - Iterator authenticationMethodIterator = authenticationService.authenticationMethodIterator(); - while(authenticationMethodIterator.hasNext()) + @GET + @Path("/login-shibboleth") + @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public Response shibbolethLoginEndPoint() + { + org.dspace.core.Context context = null; + try + { + context = Resource.createContext(); + AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); + Iterator authenticationMethodIterator = authenticationService.authenticationMethodIterator(); + while (authenticationMethodIterator.hasNext()) { AuthenticationMethod authenticationMethod = authenticationMethodIterator.next(); - if(authenticationMethod instanceof ShibAuthentication) - { - //TODO: Perhaps look for a better way of handling this ? - org.dspace.services.model.Request currentRequest = new DSpace().getRequestService().getCurrentRequest(); - String loginPageURL = authenticationMethod.loginPageURL(context, currentRequest.getHttpServletRequest(), currentRequest.getHttpServletResponse()); - if(StringUtils.isNotBlank(loginPageURL)) - { - currentRequest.getHttpServletResponse().sendRedirect(loginPageURL); - } - } + if (authenticationMethod instanceof ShibAuthentication) + { + //TODO: Perhaps look for a better way of handling this ? + org.dspace.services.model.Request currentRequest = new DSpace().getRequestService().getCurrentRequest(); + String loginPageURL = authenticationMethod.loginPageURL(context, currentRequest.getHttpServletRequest(), currentRequest.getHttpServletResponse()); + if (StringUtils.isNotBlank(loginPageURL)) + { + currentRequest.getHttpServletResponse().sendRedirect(loginPageURL); + } + } + } + context.abort(); + } + catch (ContextException | SQLException | IOException e) + { + Resource.processException("Shibboleth endpoint error: " + e.getMessage(), context); + } + finally + { + if (context != null && context.isValid()) + { + context.abort(); } - context.abort(); - } catch (ContextException | SQLException | IOException e) { - Resource.processException("Shibboleth endpoint error: " + e.getMessage(), context); - } finally { - if(context != null && context.isValid()) - { - context.abort(); - } - } - return Response.ok().build(); - } + } + return Response.ok().build(); + } /** * Method to logout a user from DSpace REST API. Removes the token and user from * TokenHolder. - * + * * @param headers * Request header which contains the header named * "rest-dspace-token" containing the token as value. @@ -242,46 +250,54 @@ public class RestIndex { /** * Method to check current status of the service and logged in user. - * + * * okay: true | false * authenticated: true | false * epersonEMAIL: user@example.com * epersonNAME: John Doe * @param headers - * Request header which contains the header named - * "rest-dspace-token" containing the token as value. - * @return status + * Request header which contains the header named + * "rest-dspace-token" containing the token as value. + * @return status the Status object with information about REST API + * @throws UnsupportedEncodingException + * The Character Encoding is not supported. */ @GET @Path("/status") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Status status(@Context HttpHeaders headers) throws UnsupportedEncodingException { + public Status status(@Context HttpHeaders headers) + throws UnsupportedEncodingException + { org.dspace.core.Context context = null; - try { + try + { context = Resource.createContext(); EPerson ePerson = context.getCurrentUser(); - if(ePerson != null) { + if (ePerson != null) + { //DB EPerson needed since token won't have full info, need context EPerson dbEPerson = epersonService.findByEmail(context, ePerson.getEmail()); Status status = new Status(dbEPerson.getEmail(), dbEPerson.getFullName()); return status; } - - } catch (ContextException e) + } + catch (ContextException e) { Resource.processException("Status context error: " + e.getMessage(), context); - } catch (SQLException e) { + } + catch (SQLException e) + { Resource.processException("Status eperson db lookup error: " + e.getMessage(), context); - } finally { + } + finally + { context.abort(); } //fallback status, unauth return new Status(); } - - } diff --git a/dspace-rest/src/main/java/org/dspace/rest/RestReports.java b/dspace-rest/src/main/java/org/dspace/rest/RestReports.java index f5ed031dab..96612e9d16 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/RestReports.java +++ b/dspace-rest/src/main/java/org/dspace/rest/RestReports.java @@ -30,9 +30,9 @@ import org.dspace.services.factory.DSpaceServicesFactory; /** * Root of RESTful api. It provides login and logout. Also have method for * printing every method which is provides by RESTful api. - * + * * @author Terry Brady, Georgetown University - * + * */ @Path("/reports") public class RestReports { @@ -44,46 +44,52 @@ public class RestReports { /** * Return html page with information about REST api. It contains methods all * methods provide by REST api. - * + * * @return HTML page which has information about all methods of REST api. */ @GET @Produces(MediaType.APPLICATION_XML) public Report[] reportIndex() - throws WebApplicationException { - ArrayList reports = new ArrayList(); - List propNames = configurationService.getPropertyKeys("rest"); - for(String propName: propNames) { - if (propName.startsWith(REST_RPT_URL)) { - String nickname = propName.substring(REST_RPT_URL.length()); - String url = configurationService.getProperty(propName); - reports.add(new Report(nickname, url)); - } - } - return reports.toArray(new Report[0]); - } - - @Path("/{report_nickname}") - @GET - public Response customReport(@PathParam("report_nickname") String report_nickname, @Context UriInfo uriInfo) - throws WebApplicationException { - URI uri = null; - if (!report_nickname.isEmpty()){ - log.info(String.format("Seeking report %s", report_nickname)); - String url = configurationService.getProperty(REST_RPT_URL + report_nickname); - - log.info(String.format("URL for report %s found: [%s]", report_nickname, url)); - if (!url.isEmpty()) { - uri = uriInfo.getBaseUriBuilder().path(url).build(""); - log.info(String.format("URI for report %s", uri)); - } - } - - if (uri != null) { - return Response.temporaryRedirect(uri).build(); - } - - return Response.noContent().build(); + throws WebApplicationException + { + ArrayList reports = new ArrayList(); + List propNames = configurationService.getPropertyKeys("rest"); + for (String propName: propNames) + { + if (propName.startsWith(REST_RPT_URL)) + { + String nickname = propName.substring(REST_RPT_URL.length()); + String url = configurationService.getProperty(propName); + reports.add(new Report(nickname, url)); + } + } + return reports.toArray(new Report[0]); } + @Path("/{report_nickname}") + @GET + public Response customReport(@PathParam("report_nickname") String report_nickname, @Context UriInfo uriInfo) + throws WebApplicationException + { + URI uri = null; + if (!report_nickname.isEmpty()) + { + log.info(String.format("Seeking report %s", report_nickname)); + String url = configurationService.getProperty(REST_RPT_URL + report_nickname); + + log.info(String.format("URL for report %s found: [%s]", report_nickname, url)); + if (!url.isEmpty()) + { + uri = uriInfo.getBaseUriBuilder().path(url).build(""); + log.info(String.format("URI for report %s", uri)); + } + } + + if (uri != null) + { + return Response.temporaryRedirect(uri).build(); + } + + return Response.noContent().build(); + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/authentication/DSpaceAuthenticationProvider.java b/dspace-rest/src/main/java/org/dspace/rest/authentication/DSpaceAuthenticationProvider.java index 200365f448..8a114ef224 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/authentication/DSpaceAuthenticationProvider.java +++ b/dspace-rest/src/main/java/org/dspace/rest/authentication/DSpaceAuthenticationProvider.java @@ -28,7 +28,7 @@ import java.util.ArrayList; import java.util.List; /** - * The core authentication & authorization provider, this provider is called when logging in & will process + * The core authentication and authorization provider. This provider is called when logging in. * * @author Roeland Dillen (roeland at atmire dot com) * @author kevinvandevelde at atmire.com @@ -106,4 +106,4 @@ public class DSpaceAuthenticationProvider implements AuthenticationProvider { public boolean supports(Class authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); } -} \ No newline at end of file +} diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/Bitstream.java b/dspace-rest/src/main/java/org/dspace/rest/common/Bitstream.java index 30ba98abad..aee814569b 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/Bitstream.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/Bitstream.java @@ -47,27 +47,34 @@ public class Bitstream extends DSpaceObject { private String retrieveLink; private CheckSum checkSum; private Integer sequenceId; - + private ResourcePolicy[] policies = null; - + public Bitstream() { } - public Bitstream(org.dspace.content.Bitstream bitstream, ServletContext servletContext, String expand, Context context) throws SQLException{ + public Bitstream(org.dspace.content.Bitstream bitstream, ServletContext servletContext, String expand, Context context) + throws SQLException + { super(bitstream, servletContext); setup(bitstream, servletContext, expand, context); } - public void setup(org.dspace.content.Bitstream bitstream, ServletContext servletContext, String expand, Context context) throws SQLException{ + public void setup(org.dspace.content.Bitstream bitstream, ServletContext servletContext, String expand, Context context) + throws SQLException + { List expandFields = new ArrayList(); - if(expand != null) { + if (expand != null) + { expandFields = Arrays.asList(expand.split(",")); } //A logo bitstream might not have a bundle... - if(bitstream.getBundles() != null & bitstream.getBundles().size() >= 0) { - if(bitstreamService.getParentObject(context, bitstream).getType() == Constants.ITEM) { + if (bitstream.getBundles() != null & bitstream.getBundles().size() >= 0) + { + if (bitstreamService.getParentObject(context, bitstream).getType() == Constants.ITEM) + { bundleName = bitstream.getBundles().get(0).getName(); } } @@ -84,76 +91,86 @@ public class Bitstream extends DSpaceObject { checkSum.setValue(bitstream.getChecksum()); this.setCheckSum(checkSum); - if(expandFields.contains("parent") || expandFields.contains("all")) { + if (expandFields.contains("parent") || expandFields.contains("all")) + { parentObject = new DSpaceObject(bitstreamService.getParentObject(context, bitstream), servletContext); - } else { + } + else + { this.addExpand("parent"); } - if(expandFields.contains("policies") || expandFields.contains("all")) { + if (expandFields.contains("policies") || expandFields.contains("all")) + { // Find policies without context. - List tempPolicies = new ArrayList(); - List bundles = bitstream.getBundles(); - for (Bundle bundle : bundles) { - List bitstreamsPolicies = bundleService.getBitstreamPolicies(context, bundle); - for (org.dspace.authorize.ResourcePolicy policy : bitstreamsPolicies) { - if(policy.getdSpaceObject().equals(bitstream)) { + List tempPolicies = new ArrayList(); + List bundles = bitstream.getBundles(); + for (Bundle bundle : bundles) + { + List bitstreamsPolicies = bundleService.getBitstreamPolicies(context, bundle); + for (org.dspace.authorize.ResourcePolicy policy : bitstreamsPolicies) + { + if (policy.getdSpaceObject().equals(bitstream)) + { tempPolicies.add(new ResourcePolicy(policy)); } - } - } - - policies = tempPolicies.toArray(new ResourcePolicy[0]); - } else { + } + } + + policies = tempPolicies.toArray(new ResourcePolicy[0]); + } + else + { this.addExpand("policies"); } - if(!expandFields.contains("all")) { + if (!expandFields.contains("all")) + { this.addExpand("all"); } } public Integer getSequenceId() { - return sequenceId; - } + return sequenceId; + } - public void setSequenceId(Integer sequenceId) { - this.sequenceId = sequenceId; - } + public void setSequenceId(Integer sequenceId) { + this.sequenceId = sequenceId; + } - public String getBundleName() { + public String getBundleName() { return bundleName; } public void setBundleName(String bundleName) { - this.bundleName = bundleName; - } + this.bundleName = bundleName; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public void setFormat(String format) { - this.format = format; - } + public void setFormat(String format) { + this.format = format; + } - public void setMimeType(String mimeType) { - this.mimeType = mimeType; - } + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } - public void setSizeBytes(Long sizeBytes) { - this.sizeBytes = sizeBytes; - } + public void setSizeBytes(Long sizeBytes) { + this.sizeBytes = sizeBytes; + } - public void setParentObject(DSpaceObject parentObject) { - this.parentObject = parentObject; - } + public void setParentObject(DSpaceObject parentObject) { + this.parentObject = parentObject; + } - public void setRetrieveLink(String retrieveLink) { - this.retrieveLink = retrieveLink; - } + public void setRetrieveLink(String retrieveLink) { + this.retrieveLink = retrieveLink; + } - public String getDescription() { + public String getDescription() { return description; } @@ -176,22 +193,20 @@ public class Bitstream extends DSpaceObject { public DSpaceObject getParentObject() { return parentObject; } - + public CheckSum getCheckSum() { - return checkSum; - } - + return checkSum; + } + public void setCheckSum(CheckSum checkSum) { - this.checkSum = checkSum; - } + this.checkSum = checkSum; + } - public ResourcePolicy[] getPolicies() { - return policies; - } + public ResourcePolicy[] getPolicies() { + return policies; + } - public void setPolicies(ResourcePolicy[] policies) { - this.policies = policies; - } - - + public void setPolicies(ResourcePolicy[] policies) { + this.policies = policies; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/CheckSum.java b/dspace-rest/src/main/java/org/dspace/rest/common/CheckSum.java index 2c716f6b9d..829275c8ea 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/CheckSum.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/CheckSum.java @@ -14,26 +14,26 @@ import javax.xml.bind.annotation.XmlValue; @XmlType public class CheckSum{ - String checkSumAlgorithm; - String value; - - public CheckSum(){} + String checkSumAlgorithm; + String value; - @XmlAttribute(name="checkSumAlgorithm") - public String getCheckSumAlgorith() { - return checkSumAlgorithm; - } + public CheckSum(){} - public void setCheckSumAlgorith(String checkSumAlgorith) { - this.checkSumAlgorithm = checkSumAlgorith; - } + @XmlAttribute(name="checkSumAlgorithm") + public String getCheckSumAlgorith() { + return checkSumAlgorithm; + } - @XmlValue - public String getValue() { - return value; - } + public void setCheckSumAlgorith(String checkSumAlgorith) { + this.checkSumAlgorithm = checkSumAlgorith; + } - public void setValue(String value) { - this.value = value; - } -} \ No newline at end of file + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/Collection.java b/dspace-rest/src/main/java/org/dspace/rest/common/Collection.java index e77bc0b16f..3e80d598b7 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/Collection.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/Collection.java @@ -54,14 +54,19 @@ public class Collection extends DSpaceObject { public Collection(){} - public Collection(org.dspace.content.Collection collection, ServletContext servletContext, String expand, Context context, Integer limit, Integer offset) throws SQLException, WebApplicationException{ + public Collection(org.dspace.content.Collection collection, ServletContext servletContext, String expand, Context context, Integer limit, Integer offset) + throws SQLException, WebApplicationException + { super(collection, servletContext); setup(collection, servletContext, expand, context, limit, offset); } - private void setup(org.dspace.content.Collection collection, ServletContext servletContext, String expand, Context context, Integer limit, Integer offset) throws SQLException{ + private void setup(org.dspace.content.Collection collection, ServletContext servletContext, String expand, Context context, Integer limit, Integer offset) + throws SQLException + { List expandFields = new ArrayList(); - if(expand != null) { + if (expand != null) + { expandFields = Arrays.asList(expand.split(",")); } @@ -69,55 +74,78 @@ public class Collection extends DSpaceObject { this.setIntroductoryText(collectionService.getMetadata(collection, org.dspace.content.Collection.INTRODUCTORY_TEXT)); this.setShortDescription(collectionService.getMetadata(collection, org.dspace.content.Collection.SHORT_DESCRIPTION)); this.setSidebarText(collectionService.getMetadata(collection, org.dspace.content.Collection.SIDEBAR_TEXT)); - - if(expandFields.contains("parentCommunityList") || expandFields.contains("all")) { + + if (expandFields.contains("parentCommunityList") || expandFields.contains("all")) + { List parentCommunities = communityService.getAllParents(context, collection); - for(org.dspace.content.Community parentCommunity : parentCommunities) { + for (org.dspace.content.Community parentCommunity : parentCommunities) + { this.addParentCommunityList(new Community(parentCommunity, servletContext, null, context)); } - } else { + } + else + { this.addExpand("parentCommunityList"); } - if(expandFields.contains("parentCommunity") | expandFields.contains("all")) { - org.dspace.content.Community parentCommunity = (org.dspace.content.Community) collectionService.getParentObject(context, collection); - this.setParentCommunity(new Community(parentCommunity, servletContext, null, context)); - } else { + if (expandFields.contains("parentCommunity") | expandFields.contains("all")) + { + org.dspace.content.Community parentCommunity = + (org.dspace.content.Community) collectionService + .getParentObject(context, collection); + this.setParentCommunity(new Community( + parentCommunity, servletContext, null, context)); + } + else + { this.addExpand("parentCommunity"); } //TODO: Item paging. limit, offset/page - if(expandFields.contains("items") || expandFields.contains("all")) { - Iterator childItems = itemService.findByCollection(context, collection, limit, offset); + if (expandFields.contains("items") || expandFields.contains("all")) + { + Iterator childItems = + itemService.findByCollection(context, collection, limit, offset); items = new ArrayList(); - while(childItems.hasNext()) { + while (childItems.hasNext()) + { org.dspace.content.Item item = childItems.next(); - if(itemService.isItemListedForUser(context, item)) { + if (itemService.isItemListedForUser(context, item)) + { items.add(new Item(item, servletContext, null, context)); } } - } else { + } + else + { this.addExpand("items"); } - if(expandFields.contains("license") || expandFields.contains("all")) { + if (expandFields.contains("license") || expandFields.contains("all")) + { setLicense(collectionService.getLicense(collection)); - } else { + } + else + { this.addExpand("license"); } - if(expandFields.contains("logo") || expandFields.contains("all")) { - if(collection.getLogo() != null) { + if (expandFields.contains("logo") || expandFields.contains("all")) + { + if (collection.getLogo() != null) + { this.logo = new Bitstream(collection.getLogo(), servletContext, null, context); } } - else { - this.addExpand("logo"); + else + { + this.addExpand("logo"); } - if(!expandFields.contains("all")) { + if (!expandFields.contains("all")) + { this.addExpand("all"); } @@ -145,18 +173,18 @@ public class Collection extends DSpaceObject { } public List getItems() { - return items; - } + return items; + } - public void setItems(List items) { - this.items = items; - } + public void setItems(List items) { + this.items = items; + } - public void setParentCommunityList(List parentCommunityList) { - this.parentCommunityList = parentCommunityList; - } + public void setParentCommunityList(List parentCommunityList) { + this.parentCommunityList = parentCommunityList; + } - public List getParentCommunityList() { + public List getParentCommunityList() { return parentCommunityList; } @@ -172,35 +200,35 @@ public class Collection extends DSpaceObject { this.license = license; } - public String getCopyrightText() { - return copyrightText; - } + public String getCopyrightText() { + return copyrightText; + } - public void setCopyrightText(String copyrightText) { - this.copyrightText = copyrightText; - } + public void setCopyrightText(String copyrightText) { + this.copyrightText = copyrightText; + } - public String getIntroductoryText() { - return introductoryText; - } + public String getIntroductoryText() { + return introductoryText; + } - public void setIntroductoryText(String introductoryText) { - this.introductoryText = introductoryText; - } + public void setIntroductoryText(String introductoryText) { + this.introductoryText = introductoryText; + } - public String getShortDescription() { - return shortDescription; - } + public String getShortDescription() { + return shortDescription; + } - public void setShortDescription(String shortDescription) { - this.shortDescription = shortDescription; - } + public void setShortDescription(String shortDescription) { + this.shortDescription = shortDescription; + } - public String getSidebarText() { - return sidebarText; - } + public String getSidebarText() { + return sidebarText; + } - public void setSidebarText(String sidebarText) { - this.sidebarText = sidebarText; - } + public void setSidebarText(String sidebarText) { + this.sidebarText = sidebarText; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/Community.java b/dspace-rest/src/main/java/org/dspace/rest/common/Community.java index 6b46fa6245..42372735eb 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/Community.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/Community.java @@ -53,14 +53,18 @@ public class Community extends DSpaceObject{ public Community(){} - public Community(org.dspace.content.Community community, ServletContext servletContext, String expand, Context context) throws SQLException, WebApplicationException{ + public Community(org.dspace.content.Community community, ServletContext servletContext, String expand, Context context) + throws SQLException, WebApplicationException + { super(community, servletContext); setup(community,servletContext, expand, context); } - private void setup(org.dspace.content.Community community, ServletContext servletContext, String expand, Context context) throws SQLException{ + private void setup(org.dspace.content.Community community, ServletContext servletContext, String expand, Context context) + throws SQLException + { List expandFields = new ArrayList(); - if(expand != null) { + if (expand != null) { expandFields = Arrays.asList(expand.split(",")); } @@ -70,54 +74,77 @@ public class Community extends DSpaceObject{ this.setSidebarText(communityService.getMetadata(community, org.dspace.content.Community.SIDEBAR_TEXT)); this.setCountItems(itemService.countItems(context, community)); - if(expandFields.contains("parentCommunity") || expandFields.contains("all")) { + if (expandFields.contains("parentCommunity") || expandFields.contains("all")) + { org.dspace.content.Community parentCommunity = (org.dspace.content.Community) communityService.getParentObject(context, community); - if(parentCommunity != null) { + if (parentCommunity != null) + { setParentCommunity(new Community(parentCommunity,servletContext, null, context)); } - } else { + } + else + { this.addExpand("parentCommunity"); } - if(expandFields.contains("collections") || expandFields.contains("all")) { + if (expandFields.contains("collections") || expandFields.contains("all")) + { List collections = community.getCollections(); List restCollections = new ArrayList<>(); - for(org.dspace.content.Collection collection : collections) { - if(authorizeService.authorizeActionBoolean(context, collection, org.dspace.core.Constants.READ)) { + for (org.dspace.content.Collection collection : collections) + { + if (authorizeService.authorizeActionBoolean(context, collection, org.dspace.core.Constants.READ)) + { restCollections.add(new Collection(collection,servletContext, null, context, null, null)); - } else { + } + else + { log.info("Omitted restricted collection: " + collection.getID() + " _ " + collection.getName()); } } setCollections(restCollections); - } else { + } + else + { this.addExpand("collections"); } - if(expandFields.contains("subCommunities") || expandFields.contains("all")) { + if (expandFields.contains("subCommunities") || expandFields.contains("all")) + { List communities = community.getSubcommunities(); subcommunities = new ArrayList(); - for(org.dspace.content.Community subCommunity : communities) { - if(authorizeService.authorizeActionBoolean(context, subCommunity, org.dspace.core.Constants.READ)) { - subcommunities.add(new Community(subCommunity, servletContext, null, context)); - } else { + for (org.dspace.content.Community subCommunity : communities) + { + if (authorizeService.authorizeActionBoolean(context, subCommunity, org.dspace.core.Constants.READ)) + { + subcommunities.add(new Community(subCommunity, servletContext, null, context)); + } + else + { log.info("Omitted restricted subCommunity: " + subCommunity.getID() + " _ " + subCommunity.getName()); } } - } else { + } + else + { this.addExpand("subCommunities"); } - if(expandFields.contains("logo") || expandFields.contains("all")) { - if(community.getLogo() != null) { + if (expandFields.contains("logo") || expandFields.contains("all")) + { + if (community.getLogo() != null) + { logo = new Bitstream(community.getLogo(),servletContext, null, context); } - } else { + } + else + { this.addExpand("logo"); } - if(!expandFields.contains("all")) { + if (!expandFields.contains("all")) + { this.addExpand("all"); } } @@ -188,12 +215,11 @@ public class Community extends DSpaceObject{ // Renamed because of xml annotation exception with this attribute and getSubCommunities. @XmlElement(name = "subcommunities", required = true) - public List getSubcommunities() { - return subcommunities; - } - - public void setSubcommunities(List subcommunities) { - this.subcommunities = subcommunities; - } - + public List getSubcommunities() { + return subcommunities; + } + + public void setSubcommunities(List subcommunities) { + this.subcommunities = subcommunities; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/FilteredCollection.java b/dspace-rest/src/main/java/org/dspace/rest/common/FilteredCollection.java index 563b30f03a..e8d22ec5a2 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/FilteredCollection.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/FilteredCollection.java @@ -56,14 +56,26 @@ public class FilteredCollection extends DSpaceObject { * Evaluate a collection against of set of Item Filters * @param collection * DSpace Collection to evaluate + * @param servletContext + * Context of the servlet container. * @param filters * String representing a list of filters * @param expand + * String in which is what you want to add to returned instance + * of collection. Options are: "all", "parentCommunityList", + * "parentCommunity", "items", "license" and "logo". If you want + * to use multiple options, it must be separated by commas. * @param context + * The relevant DSpace Context. * @param limit + * Limit value for items in list in collection. Default value is 100. * @param offset + * Offset of start index in list of items of collection. Default + * value is 0. * @throws SQLException + * An exception that provides information on a database access error or other errors. * @throws WebApplicationException + * Runtime exception for applications. */ public FilteredCollection(org.dspace.content.Collection collection, ServletContext servletContext, String filters, String expand, Context context, Integer limit, Integer offset) throws SQLException, WebApplicationException{ super(collection, servletContext); @@ -72,11 +84,11 @@ public class FilteredCollection extends DSpaceObject { private void setup(org.dspace.content.Collection collection, ServletContext servletContext, String expand, Context context, Integer limit, Integer offset, String filters) throws SQLException{ List expandFields = new ArrayList(); - if(expand != null) { + if (expand != null) { expandFields = Arrays.asList(expand.split(",")); } - if(expandFields.contains("parentCommunityList") || expandFields.contains("all")) { + if (expandFields.contains("parentCommunityList") || expandFields.contains("all")) { List parentCommunities = communityService.getAllParents(context, collection); List parentCommunityList = new ArrayList(); for(org.dspace.content.Community parentCommunity : parentCommunities) { @@ -87,14 +99,14 @@ public class FilteredCollection extends DSpaceObject { this.addExpand("parentCommunityList"); } - if(expandFields.contains("parentCommunity") | expandFields.contains("all")) { + if (expandFields.contains("parentCommunity") | expandFields.contains("all")) { org.dspace.content.Community parentCommunity = collection.getCommunities().get(0); this.setParentCommunity(new Community(parentCommunity, servletContext, null, context)); } else { this.addExpand("parentCommunity"); } - if(expandFields.contains("topCommunity") | expandFields.contains("all")) { + if (expandFields.contains("topCommunity") | expandFields.contains("all")) { List parentCommunities = communityService.getAllParents(context, collection); if (parentCommunities.size() > 0) { org.dspace.content.Community topCommunity = parentCommunities.get(parentCommunities.size()-1); @@ -111,12 +123,12 @@ public class FilteredCollection extends DSpaceObject { this.setNumberItemsProcessed(0); if (itemFilters.size() > 0) { - Iterator childItems = itemService.findByCollection(context, collection, limit, offset); + Iterator childItems = itemService.findByCollection(context, collection, limit, offset); int numProc = itemFilterSet.processSaveItems(context, servletContext, childItems, items, reportItems, expand); this.setNumberItemsProcessed(numProc); } - if(!expandFields.contains("all")) { + if (!expandFields.contains("all")) { this.addExpand("all"); } this.setNumberItems(itemService.countItems(context, collection)); @@ -155,26 +167,26 @@ public class FilteredCollection extends DSpaceObject { public List getItems() { - return items; - } + return items; + } + + public void setItems(List items) { + this.items = items; + } + + public void setParentCommunityList(List parentCommunityList) { + this.parentCommunityList = parentCommunityList; + } - public void setItems(List items) { - this.items = items; - } - - public void setParentCommunityList(List parentCommunityList) { - this.parentCommunityList = parentCommunityList; - } - - public List getParentCommunityList() { + public List getParentCommunityList() { return parentCommunityList; } - public List getItemFilters() { - return itemFilters; - } - - public void setItemFilters(List itemFilters) { - this.itemFilters = itemFilters; - } + public List getItemFilters() { + return itemFilters; + } + + public void setItemFilters(List itemFilters) { + this.itemFilters = itemFilters; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/HierarchyCommunity.java b/dspace-rest/src/main/java/org/dspace/rest/common/HierarchyCommunity.java index 5415e43b87..32de1cf578 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/HierarchyCommunity.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/HierarchyCommunity.java @@ -16,31 +16,31 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "community") public class HierarchyCommunity extends HierarchyObject { - private List communities = new ArrayList(); - private List collections = new ArrayList(); + private List communities = new ArrayList(); + private List collections = new ArrayList(); public HierarchyCommunity(){ } - + public HierarchyCommunity(String id, String name, String handle){ - super(id, name, handle); + super(id, name, handle); } - + @XmlElement(name = "community") public List getCommunities() { - return communities; - } + return communities; + } - public void setCommunities(List communities) { - this.communities = communities; - } + public void setCommunities(List communities) { + this.communities = communities; + } - @XmlElement(name = "collection") + @XmlElement(name = "collection") public List getCollections() { - return collections; - } + return collections; + } - public void setCollections(List collections) { - this.collections = collections; - } + public void setCollections(List collections) { + this.collections = collections; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/Item.java b/dspace-rest/src/main/java/org/dspace/rest/common/Item.java index 3587e3f2f3..e794b1ec0b 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/Item.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/Item.java @@ -57,28 +57,44 @@ public class Item extends DSpaceObject { public Item(){} - public Item(org.dspace.content.Item item, ServletContext servletContext, String expand, Context context) throws SQLException, WebApplicationException{ + public Item(org.dspace.content.Item item, ServletContext servletContext, String expand, Context context) + throws SQLException, WebApplicationException + { super(item, servletContext); setup(item, servletContext, expand, context); } - private void setup(org.dspace.content.Item item, ServletContext servletContext, String expand, Context context) throws SQLException{ + private void setup(org.dspace.content.Item item, ServletContext servletContext, String expand, Context context) + throws SQLException + { List expandFields = new ArrayList(); - if(expand != null) { + if (expand != null) + { expandFields = Arrays.asList(expand.split(",")); } - if(expandFields.contains("metadata") || expandFields.contains("all")) { + if (expandFields.contains("metadata") || expandFields.contains("all")) + { metadata = new ArrayList(); - List metadataValues = itemService.getMetadata(item, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY); + List metadataValues = itemService.getMetadata( + item, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, + org.dspace.content.Item.ANY, org.dspace.content.Item.ANY); - for (MetadataValue metadataValue : metadataValues) { + for (MetadataValue metadataValue : metadataValues) + { MetadataField metadataField = metadataValue.getMetadataField(); - if (!metadataExposureService.isHidden(context, metadataField.getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) { - metadata.add(new MetadataEntry(metadataField.toString('.'), metadataValue.getValue(), metadataValue.getLanguage())); + if (!metadataExposureService.isHidden(context, + metadataField.getMetadataSchema().getName(), + metadataField.getElement(), + metadataField.getQualifier())) + { + metadata.add(new MetadataEntry(metadataField.toString('.'), + metadataValue.getValue(), metadataValue.getLanguage())); } } - } else { + } + else + { this.addExpand("metadata"); } @@ -86,56 +102,79 @@ public class Item extends DSpaceObject { this.setWithdrawn(Boolean.toString(item.isWithdrawn())); this.setLastModified(item.getLastModified().toString()); - if(expandFields.contains("parentCollection") || expandFields.contains("all")) { - if (item.getOwningCollection() != null) { - this.parentCollection = new Collection(item.getOwningCollection(), servletContext, null, context, null, null); - } else { + if (expandFields.contains("parentCollection") || expandFields.contains("all")) + { + if (item.getOwningCollection() != null) + { + this.parentCollection = new Collection(item.getOwningCollection(), + servletContext, null, context, null, null); + } + else + { this.addExpand("parentCollection"); } - } else { + } + else + { this.addExpand("parentCollection"); } - if(expandFields.contains("parentCollectionList") || expandFields.contains("all")) { + if (expandFields.contains("parentCollectionList") || expandFields.contains("all")) + { this.parentCollectionList = new ArrayList(); List collections = item.getCollections(); - for(org.dspace.content.Collection collection : collections) { - this.parentCollectionList.add(new Collection(collection, servletContext, null, context, null, null)); + for (org.dspace.content.Collection collection : collections) + { + this.parentCollectionList.add(new Collection(collection, + servletContext, null, context, null, null)); } - } else { + } + else + { this.addExpand("parentCollectionList"); } - if(expandFields.contains("parentCommunityList") || expandFields.contains("all")) { + if (expandFields.contains("parentCommunityList") || expandFields.contains("all")) + { this.parentCommunityList = new ArrayList(); List communities = itemService.getCommunities(context, item); - for(org.dspace.content.Community community : communities) { + for (org.dspace.content.Community community : communities) + { this.parentCommunityList.add(new Community(community, servletContext, null, context)); } - } else { + } + else + { this.addExpand("parentCommunityList"); } //TODO: paging - offset, limit - if(expandFields.contains("bitstreams") || expandFields.contains("all")) { + if (expandFields.contains("bitstreams") || expandFields.contains("all")) + { bitstreams = new ArrayList(); List bundles = item.getBundles(); - for(Bundle bundle : bundles) { + for (Bundle bundle : bundles) + { List itemBitstreams = bundle.getBitstreams(); - for(org.dspace.content.Bitstream itemBitstream : itemBitstreams) { - if(authorizeService.authorizeActionBoolean(context, itemBitstream, org.dspace.core.Constants.READ)) { + for (org.dspace.content.Bitstream itemBitstream : itemBitstreams) + { + if (authorizeService.authorizeActionBoolean(context, itemBitstream, org.dspace.core.Constants.READ)) + { bitstreams.add(new Bitstream(itemBitstream, servletContext, null, context)); } } } - } else { + } + else + { this.addExpand("bitstreams"); } - if(!expandFields.contains("all")) { + if (!expandFields.contains("all")) + { this.addExpand("all"); } } @@ -184,24 +223,24 @@ public class Item extends DSpaceObject { return parentCommunityList; } - public void setParentCollection(Collection parentCollection) { - this.parentCollection = parentCollection; - } + public void setParentCollection(Collection parentCollection) { + this.parentCollection = parentCollection; + } - public void setParentCollectionList(List parentCollectionList) { - this.parentCollectionList = parentCollectionList; - } + public void setParentCollectionList(List parentCollectionList) { + this.parentCollectionList = parentCollectionList; + } - public void setParentCommunityList(List parentCommunityList) { - this.parentCommunityList = parentCommunityList; - } + public void setParentCommunityList(List parentCommunityList) { + this.parentCommunityList = parentCommunityList; + } - @XmlElement(required = true) - public void setMetadata(List metadata) { - this.metadata = metadata; - } + @XmlElement(required = true) + public void setMetadata(List metadata) { + this.metadata = metadata; + } - public void setBitstreams(List bitstreams) { - this.bitstreams = bitstreams; - } + public void setBitstreams(List bitstreams) { + this.bitstreams = bitstreams; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilter.java b/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilter.java index d16e013725..baaded9c20 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilter.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilter.java @@ -51,33 +51,46 @@ public class ItemFilter { public static final String ALL_FILTERS = "all_filters"; public static final String ALL = "all"; - - public static List getItemFilters(String filters, boolean saveItems) { - LinkedHashMap availableTests = new LinkedHashMap(); - for(ItemFilterList plugobj: (ItemFilterList[]) CoreServiceFactory.getInstance().getPluginService().getPluginSequence(ItemFilterList.class)) { - for(ItemFilterTest defFilter: plugobj.getFilters()) { - availableTests.put(defFilter.getName(), defFilter); - } - } - List itemFilters = new ArrayList(); - ItemFilter allFilters = new ItemFilter(ItemFilter.ALL_FILTERS, "Matches all specified filters", - "This filter includes all items that matched ALL specified filters", ItemFilterDefs.CAT_ITEM, saveItems); - if (filters.equals(ALL)) { - for(ItemFilterTest itemFilterDef: availableTests.values()) { + public static List getItemFilters(String filters, boolean saveItems) + { + LinkedHashMap availableTests = new LinkedHashMap(); + for (ItemFilterList plugobj: + (ItemFilterList[]) CoreServiceFactory.getInstance() + .getPluginService().getPluginSequence(ItemFilterList.class)) + { + for (ItemFilterTest defFilter: plugobj.getFilters()) + { + availableTests.put(defFilter.getName(), defFilter); + } + } + List itemFilters = new ArrayList(); + ItemFilter allFilters = new ItemFilter(ItemFilter.ALL_FILTERS, "Matches all specified filters", + "This filter includes all items that matched ALL specified filters", + ItemFilterDefs.CAT_ITEM, saveItems); + + if (filters.equals(ALL)) + { + for (ItemFilterTest itemFilterDef: availableTests.values()) + { itemFilters.add(new ItemFilter(itemFilterDef, saveItems)); - } + } itemFilters.add(allFilters); - } else { - for(String filter: Arrays.asList(filters.split(","))) { - if (filter.equals(ItemFilter.ALL_FILTERS)) { + } + else + { + for (String filter: Arrays.asList(filters.split(","))) + { + if (filter.equals(ItemFilter.ALL_FILTERS)) + { continue; } - + ItemFilterTest itemFilterDef; itemFilterDef = availableTests.get(filter); - if (itemFilterDef == null) { - continue; + if (itemFilterDef == null) + { + continue; } itemFilters.add(new ItemFilter(itemFilterDef, saveItems)); } @@ -85,24 +98,31 @@ public class ItemFilter { } return itemFilters; } - - public static ItemFilter getAllFiltersFilter(List itemFilters) { - for(ItemFilter itemFilter: itemFilters) { - if (itemFilter.getFilterName().equals(ALL_FILTERS)) { + + public static ItemFilter getAllFiltersFilter(List itemFilters) + { + for (ItemFilter itemFilter: itemFilters) + { + if (itemFilter.getFilterName().equals(ALL_FILTERS)) + { itemFilter.initCount(); return itemFilter; } } return null; } - - public ItemFilter(ItemFilterTest itemFilterTest, boolean saveItems) throws WebApplicationException{ + + public ItemFilter(ItemFilterTest itemFilterTest, boolean saveItems) + throws WebApplicationException + { this.itemFilterTest = itemFilterTest; this.saveItems = saveItems; - setup(itemFilterTest.getName(), itemFilterTest.getTitle(), itemFilterTest.getDescription(), itemFilterTest.getCategory()); + setup(itemFilterTest.getName(), itemFilterTest.getTitle(), + itemFilterTest.getDescription(), itemFilterTest.getCategory()); } - - public ItemFilter(String name, String title, String description, String category, boolean saveItems) throws WebApplicationException{ + + public ItemFilter(String name, String title, String description, String category, boolean saveItems) + throws WebApplicationException{ this.saveItems = saveItems; setup(name, title, description, category); } @@ -114,33 +134,41 @@ public class ItemFilter { this.setCategory(category); } - private void initCount() { - if (itemCount == null) { + private void initCount() + { + if (itemCount == null) + { itemCount = 0; - } - if (unfilteredItemCount == null) { + } + if (unfilteredItemCount == null) + { unfilteredItemCount = 0; - } - } - + } + } + public boolean hasItemTest() { return itemFilterTest != null; } - - public void addItem(org.dspace.rest.common.Item restItem) { + + public void addItem(org.dspace.rest.common.Item restItem) + { initCount(); - if (saveItems){ - items.add(restItem); + if (saveItems) + { + items.add(restItem); } itemCount++; } - - public boolean testItem(Context context, org.dspace.content.Item item, org.dspace.rest.common.Item restItem) { + + public boolean testItem(Context context, org.dspace.content.Item item, org.dspace.rest.common.Item restItem) + { initCount(); - if (itemFilterTest == null) { + if (itemFilterTest == null) + { return false; } - if (itemFilterTest.testItem(context, item)) { + if (itemFilterTest.testItem(context, item)) + { addItem(restItem); return true; } @@ -155,7 +183,7 @@ public class ItemFilter { public void setFilterName(String name) { this.filterName = name; } - + @XmlAttribute(name="title") public String getTitle() { return title; @@ -188,25 +216,29 @@ public class ItemFilter { return queryAnnotation; } - public void annotateQuery(List query_field, List query_op, List query_val) throws SQLException { + public void annotateQuery(List query_field, List query_op, List query_val) + throws SQLException + { int index = Math.min(query_field.size(), Math.min(query_op.size(), query_val.size())); StringBuilder sb = new StringBuilder(); - for(int i=0; i items) { - this.items = items; - } + public void setItems(List items) { + this.items = items; + } public List getItemFilterQueries() { return itemFilterQueries; @@ -245,16 +277,19 @@ public class ItemFilter { this.itemFilterQueries = itemFilterQueries; } - public void initMetadataList(List show_fields) { - if (show_fields != null) { + public void initMetadataList(List show_fields) + { + if (show_fields != null) + { List returnFields = new ArrayList(); - for(String field: show_fields) { + for (String field: show_fields) + { returnFields.add(new MetadataEntry(field, null, null)); } - setMetadata(returnFields); + setMetadata(returnFields); } } - + public List getMetadata() { return metadata; } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilterQuery.java b/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilterQuery.java index f7adb0bc0e..a576645a30 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilterQuery.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/ItemFilterQuery.java @@ -34,9 +34,11 @@ public class ItemFilterQuery { * @param operation * Operation to perform on a metadata field * @param value + Query value. * @throws WebApplicationException + Runtime exception for applications. */ - public ItemFilterQuery(String field, String operation, String value) throws WebApplicationException{ + public ItemFilterQuery(String field, String operation, String value) throws WebApplicationException { setup(field, operation, value); } diff --git a/dspace-rest/src/main/java/org/dspace/rest/common/ResourcePolicy.java b/dspace-rest/src/main/java/org/dspace/rest/common/ResourcePolicy.java index d731bf90b5..e81ecf703e 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/common/ResourcePolicy.java +++ b/dspace-rest/src/main/java/org/dspace/rest/common/ResourcePolicy.java @@ -15,169 +15,170 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "resourcepolicy") public class ResourcePolicy{ - - public enum Action { - READ, WRITE, DELETE; - } - - private Integer id; - private Action action; - private String epersonId; //UUID - private String groupId; //UUID - private String resourceId; //UUID - private String resourceType; - private String rpDescription; - private String rpName; - private String rpType; - private Date startDate; - private Date endDate; - - public ResourcePolicy() {} - - public ResourcePolicy(org.dspace.authorize.ResourcePolicy dspacePolicy) { - this.id = dspacePolicy.getID(); - - switch(dspacePolicy.getAction()) { - case org.dspace.core.Constants.READ: - this.action = Action.READ; - break; - case org.dspace.core.Constants.WRITE: - this.action = Action.WRITE; - break; - case org.dspace.core.Constants.DELETE: - this.action = Action.DELETE; - break; - } + + public enum Action { + READ, WRITE, DELETE; + } + + private Integer id; + private Action action; + private String epersonId; //UUID + private String groupId; //UUID + private String resourceId; //UUID + private String resourceType; + private String rpDescription; + private String rpName; + private String rpType; + private Date startDate; + private Date endDate; + + public ResourcePolicy() {} + + public ResourcePolicy(org.dspace.authorize.ResourcePolicy dspacePolicy) { + this.id = dspacePolicy.getID(); + + switch (dspacePolicy.getAction()) { + case org.dspace.core.Constants.READ: + this.action = Action.READ; + break; + case org.dspace.core.Constants.WRITE: + this.action = Action.WRITE; + break; + case org.dspace.core.Constants.DELETE: + this.action = Action.DELETE; + break; + } - this.epersonId = dspacePolicy.getEPerson().getID().toString(); - this.groupId = dspacePolicy.getGroup().getID().toString(); - this.resourceId = dspacePolicy.getdSpaceObject().getID().toString(); - this.rpDescription = dspacePolicy.getRpDescription(); - this.rpName = dspacePolicy.getRpName(); - this.rpType = dspacePolicy.getRpType(); - this.startDate = dspacePolicy.getStartDate(); - this.endDate = dspacePolicy.getEndDate(); - switch(dspacePolicy.getdSpaceObject().getType()) { - case org.dspace.core.Constants.BITSTREAM: - this.resourceType = "bitstream"; - break; - case org.dspace.core.Constants.ITEM: - this.resourceType = "item"; - break; - case org.dspace.core.Constants.COLLECTION: - this.resourceType = "collection"; - break; - case org.dspace.core.Constants.COMMUNITY: - this.resourceType = "community"; - break; - case org.dspace.core.Constants.BUNDLE: - this.resourceType = "bundle"; - break; - default: - this.resourceType = ""; - break; - } - } + this.epersonId = dspacePolicy.getEPerson().getID().toString(); + this.groupId = dspacePolicy.getGroup().getID().toString(); + this.resourceId = dspacePolicy.getdSpaceObject().getID().toString(); + this.rpDescription = dspacePolicy.getRpDescription(); + this.rpName = dspacePolicy.getRpName(); + this.rpType = dspacePolicy.getRpType(); + this.startDate = dspacePolicy.getStartDate(); + this.endDate = dspacePolicy.getEndDate(); + switch (dspacePolicy.getdSpaceObject().getType()) + { + case org.dspace.core.Constants.BITSTREAM: + this.resourceType = "bitstream"; + break; + case org.dspace.core.Constants.ITEM: + this.resourceType = "item"; + break; + case org.dspace.core.Constants.COLLECTION: + this.resourceType = "collection"; + break; + case org.dspace.core.Constants.COMMUNITY: + this.resourceType = "community"; + break; + case org.dspace.core.Constants.BUNDLE: + this.resourceType = "bundle"; + break; + default: + this.resourceType = ""; + break; + } + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Action getAction() { - return action; - } - - @JsonIgnore - public int getActionInt(){ - switch(action) { - case READ: - return org.dspace.core.Constants.READ; - case WRITE: - return org.dspace.core.Constants.WRITE; - case DELETE: - return org.dspace.core.Constants.DELETE; - } - return org.dspace.core.Constants.READ; - } + public Action getAction() { + return action; + } + + @JsonIgnore + public int getActionInt() + { + switch (action) { + case READ: + return org.dspace.core.Constants.READ; + case WRITE: + return org.dspace.core.Constants.WRITE; + case DELETE: + return org.dspace.core.Constants.DELETE; + } + return org.dspace.core.Constants.READ; + } - public void setAction(Action action) { - this.action = action; - } + public void setAction(Action action) { + this.action = action; + } - public String getEpersonId() { - return epersonId; - } + public String getEpersonId() { + return epersonId; + } - public void setEpersonId(String epersonId) { - this.epersonId = epersonId; - } + public void setEpersonId(String epersonId) { + this.epersonId = epersonId; + } - public String getGroupId() { - return groupId; - } + public String getGroupId() { + return groupId; + } - public void setGroupId(String groupId) { - this.groupId = groupId; - } + public void setGroupId(String groupId) { + this.groupId = groupId; + } - public String getResourceId() { - return resourceId; - } + public String getResourceId() { + return resourceId; + } - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } - public String getResourceType() { - return resourceType; - } + public String getResourceType() { + return resourceType; + } - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } - public String getRpDescription() { - return rpDescription; - } + public String getRpDescription() { + return rpDescription; + } - public void setRpDescription(String rpDescription) { - this.rpDescription = rpDescription; - } + public void setRpDescription(String rpDescription) { + this.rpDescription = rpDescription; + } - public String getRpName() { - return rpName; - } + public String getRpName() { + return rpName; + } - public void setRpName(String rpName) { - this.rpName = rpName; - } + public void setRpName(String rpName) { + this.rpName = rpName; + } - public String getRpType() { - return rpType; - } + public String getRpType() { + return rpType; + } - public void setRpType(String rpType) { - this.rpType = rpType; - } + public void setRpType(String rpType) { + this.rpType = rpType; + } - public Date getStartDate() { - return startDate; - } + public Date getStartDate() { + return startDate; + } - public void setStartDate(Date startDate) { - this.startDate = startDate; - } + public void setStartDate(Date startDate) { + this.startDate = startDate; + } - public Date getEndDate() { - return endDate; - } + public Date getEndDate() { + return endDate; + } - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - + public void setEndDate(Date endDate) { + this.endDate = endDate; + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefs.java b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefs.java index 8440b86dd3..70350695f6 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefs.java +++ b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefs.java @@ -17,133 +17,133 @@ import org.dspace.core.Context; */ public class ItemFilterDefs implements ItemFilterList { - public static final String CAT_ITEM = "Item Property Filters"; - public static final String CAT_BASIC = "Basic Bitstream Filters"; - public static final String CAT_MIME = "Bitstream Filters by MIME Type"; - - public static final String[] MIMES_PDF = {"application/pdf"}; + public static final String CAT_ITEM = "Item Property Filters"; + public static final String CAT_BASIC = "Basic Bitstream Filters"; + public static final String CAT_MIME = "Bitstream Filters by MIME Type"; + + public static final String[] MIMES_PDF = {"application/pdf"}; public static final String[] MIMES_JPG = {"image/jpeg"}; - - - private enum EnumItemFilterDefs implements ItemFilterTest { - is_item("Is Item - always true", null, CAT_ITEM) { - public boolean testItem(Context context, Item item) { - return true; - } - }, - is_withdrawn("Withdrawn Items", null, CAT_ITEM) { - public boolean testItem(Context context, Item item) { - return item.isWithdrawn(); - } - }, - is_not_withdrawn("Available Items - Not Withdrawn", null, CAT_ITEM) { - public boolean testItem(Context context, Item item) { - return !item.isWithdrawn(); - } - }, - is_discoverable("Discoverable Items - Not Private", null, CAT_ITEM) { - public boolean testItem(Context context, Item item) { - return item.isDiscoverable(); - } - }, - is_not_discoverable("Not Discoverable - Private Item", null, CAT_ITEM) { - public boolean testItem(Context context, Item item) { - return !item.isDiscoverable(); - } - }, - has_multiple_originals("Item has Multiple Original Bitstreams", null, CAT_BASIC) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countOriginalBitstream(item) > 1; - } - }, - has_no_originals("Item has No Original Bitstreams", null, CAT_BASIC) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countOriginalBitstream(item) == 0; - } - }, - has_one_original("Item has One Original Bitstream", null, CAT_BASIC) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countOriginalBitstream(item) == 1; - } - }, - has_doc_original("Item has a Doc Original Bitstream (PDF, Office, Text, HTML, XML, etc)", null, CAT_MIME) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()) > 0; - } - }, - has_image_original("Item has an Image Original Bitstream", null, CAT_MIME) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image") > 0; - } - }, - has_unsupp_type("Has Other Bitstream Types (not Doc or Image)", null, ItemFilterDefs.CAT_MIME) { - public boolean testItem(Context context, Item item) { - int bitCount = ItemFilterUtil.countOriginalBitstream(item); - if (bitCount == 0) { - return false; - } - int docCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); - int imgCount = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image"); - return (bitCount - docCount - imgCount) > 0; - } - }, - has_mixed_original("Item has multiple types of Original Bitstreams (Doc, Image, Other)", null, CAT_MIME) { - public boolean testItem(Context context, Item item) { - int countBit = ItemFilterUtil.countOriginalBitstream(item); - if (countBit <= 1) return false; - int countDoc = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); - if (countDoc > 0) { - return countDoc != countBit; - } - int countImg = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image"); - if (countImg > 0) { - return countImg != countBit; - } - return false; - } - }, - has_pdf_original("Item has a PDF Original Bitstream", null, CAT_MIME) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countOriginalBitstreamMime(context, item, MIMES_PDF) > 0; - } - }, - has_jpg_original("Item has JPG Original Bitstream", null, CAT_MIME) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countOriginalBitstreamMime(context, item, MIMES_JPG) > 0; - } - }, - ; - - private String title = null; - private String description = null; - private EnumItemFilterDefs(String title, String description, String category) { - this.title = title; - this.description = description; - this.category = category; - } - - private EnumItemFilterDefs() { - this(null, null, null); - } - - public String getName() { - return name(); - } - public String getTitle() { - return title; - } - public String getDescription() { - return description; - } - private String category = null; - public String getCategory() { - return category; - } - } + + + private enum EnumItemFilterDefs implements ItemFilterTest { + is_item("Is Item - always true", null, CAT_ITEM) { + public boolean testItem(Context context, Item item) { + return true; + } + }, + is_withdrawn("Withdrawn Items", null, CAT_ITEM) { + public boolean testItem(Context context, Item item) { + return item.isWithdrawn(); + } + }, + is_not_withdrawn("Available Items - Not Withdrawn", null, CAT_ITEM) { + public boolean testItem(Context context, Item item) { + return !item.isWithdrawn(); + } + }, + is_discoverable("Discoverable Items - Not Private", null, CAT_ITEM) { + public boolean testItem(Context context, Item item) { + return item.isDiscoverable(); + } + }, + is_not_discoverable("Not Discoverable - Private Item", null, CAT_ITEM) { + public boolean testItem(Context context, Item item) { + return !item.isDiscoverable(); + } + }, + has_multiple_originals("Item has Multiple Original Bitstreams", null, CAT_BASIC) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.countOriginalBitstream(item) > 1; + } + }, + has_no_originals("Item has No Original Bitstreams", null, CAT_BASIC) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.countOriginalBitstream(item) == 0; + } + }, + has_one_original("Item has One Original Bitstream", null, CAT_BASIC) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.countOriginalBitstream(item) == 1; + } + }, + has_doc_original("Item has a Doc Original Bitstream (PDF, Office, Text, HTML, XML, etc)", null, CAT_MIME) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()) > 0; + } + }, + has_image_original("Item has an Image Original Bitstream", null, CAT_MIME) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image") > 0; + } + }, + has_unsupp_type("Has Other Bitstream Types (not Doc or Image)", null, ItemFilterDefs.CAT_MIME) { + public boolean testItem(Context context, Item item) { + int bitCount = ItemFilterUtil.countOriginalBitstream(item); + if (bitCount == 0) { + return false; + } + int docCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); + int imgCount = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image"); + return (bitCount - docCount - imgCount) > 0; + } + }, + has_mixed_original("Item has multiple types of Original Bitstreams (Doc, Image, Other)", null, CAT_MIME) { + public boolean testItem(Context context, Item item) { + int countBit = ItemFilterUtil.countOriginalBitstream(item); + if (countBit <= 1) return false; + int countDoc = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); + if (countDoc > 0) { + return countDoc != countBit; + } + int countImg = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image"); + if (countImg > 0) { + return countImg != countBit; + } + return false; + } + }, + has_pdf_original("Item has a PDF Original Bitstream", null, CAT_MIME) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.countOriginalBitstreamMime(context, item, MIMES_PDF) > 0; + } + }, + has_jpg_original("Item has JPG Original Bitstream", null, CAT_MIME) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.countOriginalBitstreamMime(context, item, MIMES_JPG) > 0; + } + }, + ; + + private String title = null; + private String description = null; + private EnumItemFilterDefs(String title, String description, String category) { + this.title = title; + this.description = description; + this.category = category; + } + + private EnumItemFilterDefs() { + this(null, null, null); + } + + public String getName() { + return name(); + } + public String getTitle() { + return title; + } + public String getDescription() { + return description; + } + private String category = null; + public String getCategory() { + return category; + } + } - public ItemFilterDefs() { - } - public ItemFilterTest[] getFilters() { - return EnumItemFilterDefs.values(); - } + public ItemFilterDefs() { + } + public ItemFilterTest[] getFilters() { + return EnumItemFilterDefs.values(); + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMeta.java b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMeta.java index 175c075b0b..d1da2148eb 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMeta.java +++ b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMeta.java @@ -27,136 +27,136 @@ public class ItemFilterDefsMeta implements ItemFilterList { static Logger log = Logger.getLogger(ItemFilterDefsMeta.class); public static final String CAT_META_GEN = "General Metadata Filters"; - public static final String CAT_META_SPEC = "Specific Metadata Filters"; - public static final String CAT_MOD = "Recently Modified"; - private enum EnumItemFilterDefs implements ItemFilterTest { - has_no_title("Has no dc.title", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - return itemService.getMetadataByMetadataString(item, "dc.title").size() == 0; - } - }, - has_no_uri("Has no dc.identifier.uri", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - return itemService.getMetadataByMetadataString(item, "dc.identifier.uri").size() == 0; - } - }, - has_mult_uri("Has multiple dc.identifier.uri", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - return itemService.getMetadataByMetadataString(item, "dc.identifier.uri").size() > 1; - } - }, - has_compound_subject("Has compound subject", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-compound-subject"); - return ItemFilterUtil.hasMetadataMatch(item, "dc.subject.*", Pattern.compile(regex)); - } - }, - has_compound_author("Has compound author", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-compound-author"); - return ItemFilterUtil.hasMetadataMatch(item, "dc.creator,dc.contributor.author", Pattern.compile(regex)); - } - }, - has_empty_metadata("Has empty metadata", null, CAT_META_GEN) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile("^\\s*$")); - } - }, - has_unbreaking_metadata("Has unbreaking metadata", null, CAT_META_GEN) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-unbreaking"); - return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); - } - }, - has_long_metadata("Has long metadata field", null, CAT_META_GEN) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-long"); - return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); - } - }, - has_xml_entity("Has XML entity in metadata", null, CAT_META_GEN) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-xml-entity"); - return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); - } - }, - has_non_ascii("Has non-ascii in metadata", null, CAT_META_GEN) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-non-ascii"); - return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); - } - }, - has_desc_url("Has url in description", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-url"); - return ItemFilterUtil.hasMetadataMatch(item, "dc.description.*", Pattern.compile(regex)); - } - }, - has_fulltext_provenance("Has fulltext in provenance", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-fulltext"); - return ItemFilterUtil.hasMetadataMatch(item, "dc.description.provenance", Pattern.compile(regex)); - } - }, - no_fulltext_provenance("Doesn't have fulltext in provenance", null, CAT_META_SPEC) { - public boolean testItem(Context context, Item item) { - String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-fulltext"); - return !ItemFilterUtil.hasMetadataMatch(item, "dc.description.provenance", Pattern.compile(regex)); - } - }, - mod_last_day("Modified in last 1 day", null, CAT_MOD) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.recentlyModified(item, 1); - } - }, - mod_last_7_days("Modified in last 7 days", null, CAT_MOD) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.recentlyModified(item, 7); - } - }, - mod_last_30_days("Modified in last 30 days", null, CAT_MOD) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.recentlyModified(item, 30); - } - }, - mod_last_90_days("Modified in last 60 days", null, CAT_MOD) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.recentlyModified(item, 60); - } - }, - ; - - private String title = null; - private String description = null; - private EnumItemFilterDefs(String title, String description, String category) { - this.title = title; - this.description = description; - this.category = category; - } - - private EnumItemFilterDefs() { - this(null, null, null); - } - - public String getName() { - return name(); - } - public String getTitle() { - return title; - } - public String getDescription() { - return description; - } - - private String category = null; - public String getCategory() { - return category; - } - } + public static final String CAT_META_SPEC = "Specific Metadata Filters"; + public static final String CAT_MOD = "Recently Modified"; + private enum EnumItemFilterDefs implements ItemFilterTest { + has_no_title("Has no dc.title", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + return itemService.getMetadataByMetadataString(item, "dc.title").size() == 0; + } + }, + has_no_uri("Has no dc.identifier.uri", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + return itemService.getMetadataByMetadataString(item, "dc.identifier.uri").size() == 0; + } + }, + has_mult_uri("Has multiple dc.identifier.uri", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + return itemService.getMetadataByMetadataString(item, "dc.identifier.uri").size() > 1; + } + }, + has_compound_subject("Has compound subject", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-compound-subject"); + return ItemFilterUtil.hasMetadataMatch(item, "dc.subject.*", Pattern.compile(regex)); + } + }, + has_compound_author("Has compound author", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-compound-author"); + return ItemFilterUtil.hasMetadataMatch(item, "dc.creator,dc.contributor.author", Pattern.compile(regex)); + } + }, + has_empty_metadata("Has empty metadata", null, CAT_META_GEN) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile("^\\s*$")); + } + }, + has_unbreaking_metadata("Has unbreaking metadata", null, CAT_META_GEN) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-unbreaking"); + return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); + } + }, + has_long_metadata("Has long metadata field", null, CAT_META_GEN) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-long"); + return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); + } + }, + has_xml_entity("Has XML entity in metadata", null, CAT_META_GEN) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-xml-entity"); + return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); + } + }, + has_non_ascii("Has non-ascii in metadata", null, CAT_META_GEN) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-non-ascii"); + return ItemFilterUtil.hasMetadataMatch(item, "*", Pattern.compile(regex)); + } + }, + has_desc_url("Has url in description", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-url"); + return ItemFilterUtil.hasMetadataMatch(item, "dc.description.*", Pattern.compile(regex)); + } + }, + has_fulltext_provenance("Has fulltext in provenance", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-fulltext"); + return ItemFilterUtil.hasMetadataMatch(item, "dc.description.provenance", Pattern.compile(regex)); + } + }, + no_fulltext_provenance("Doesn't have fulltext in provenance", null, CAT_META_SPEC) { + public boolean testItem(Context context, Item item) { + String regex = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("rest.report-regex-fulltext"); + return !ItemFilterUtil.hasMetadataMatch(item, "dc.description.provenance", Pattern.compile(regex)); + } + }, + mod_last_day("Modified in last 1 day", null, CAT_MOD) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.recentlyModified(item, 1); + } + }, + mod_last_7_days("Modified in last 7 days", null, CAT_MOD) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.recentlyModified(item, 7); + } + }, + mod_last_30_days("Modified in last 30 days", null, CAT_MOD) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.recentlyModified(item, 30); + } + }, + mod_last_90_days("Modified in last 60 days", null, CAT_MOD) { + public boolean testItem(Context context, Item item) { + return ItemFilterUtil.recentlyModified(item, 60); + } + }, + ; - public ItemFilterDefsMeta() { - } - public ItemFilterTest[] getFilters() { - return EnumItemFilterDefs.values(); - } + private String title = null; + private String description = null; + private EnumItemFilterDefs(String title, String description, String category) { + this.title = title; + this.description = description; + this.category = category; + } + + private EnumItemFilterDefs() { + this(null, null, null); + } + + public String getName() { + return name(); + } + public String getTitle() { + return title; + } + public String getDescription() { + return description; + } + + private String category = null; + public String getCategory() { + return category; + } + } + + public ItemFilterDefsMeta() { + } + public ItemFilterTest[] getFilters() { + return EnumItemFilterDefs.values(); + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMisc.java b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMisc.java index a4de9b1a29..e154708694 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMisc.java +++ b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsMisc.java @@ -21,165 +21,210 @@ import org.dspace.services.factory.DSpaceServicesFactory; */ public class ItemFilterDefsMisc implements ItemFilterList { - public static final String CAT_MISC = "Bitstream Bundle Filters"; - public static final String CAT_MIME_SUPP = "Supported MIME Type Filters"; - private enum EnumItemFilterDefs implements ItemFilterTest { - has_only_supp_image_type("Item Image Bitstreams are Supported", null, CAT_MIME_SUPP) { - public boolean testItem(Context context, Item item) { - int imageCount = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image/"); - if (imageCount == 0) { - return false; - } - int suppImageCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedImageMimeTypes()); - return (imageCount == suppImageCount); - } - }, - has_unsupp_image_type("Item has Image Bitstream that is Unsupported", null, CAT_MIME_SUPP) { - public boolean testItem(Context context, Item item) { - int imageCount = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image/"); - if (imageCount == 0) { - return false; - } - int suppImageCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedImageMimeTypes()); - return (imageCount - suppImageCount) > 0; - } - }, - has_only_supp_doc_type("Item Document Bitstreams are Supported", null, CAT_MIME_SUPP) { - public boolean testItem(Context context, Item item) { - int docCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); - if (docCount == 0) { - return false; - } - int suppDocCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedDocumentMimeTypes()); - return docCount == suppDocCount; - } - }, - has_unsupp_doc_type("Item has Document Bitstream that is Unsupported", null, CAT_MIME_SUPP) { - public boolean testItem(Context context, Item item) { - int docCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); - if (docCount == 0) { - return false; - } - int suppDocCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedDocumentMimeTypes()); - return (docCount - suppDocCount) > 0; - } - }, - has_small_pdf("Has unusually small PDF", null, ItemFilterDefs.CAT_MIME) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countBitstreamSmallerThanMinSize(context, BundleName.ORIGINAL, item, ItemFilterDefs.MIMES_PDF, "rest.report-pdf-min-size") > 0; - } - }, - has_large_pdf("Has unusually large PDF", null, ItemFilterDefs.CAT_MIME) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countBitstreamLargerThanMaxSize(context, BundleName.ORIGINAL, item, ItemFilterDefs.MIMES_PDF, "rest.report-pdf-max-size") > 0; - } - }, - has_unsupported_bundle("Has bitstream in an unsuppored bundle", null, CAT_MISC) { - public boolean testItem(Context context, Item item) { - String[] bundleList = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-supp-bundles"); - return ItemFilterUtil.hasUnsupportedBundle(item, bundleList); - } - }, - has_small_thumbnail("Has unusually small thumbnail", null, CAT_MISC) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countBitstreamSmallerThanMinSize(context, BundleName.THUMBNAIL, item, ItemFilterDefs.MIMES_JPG, "rest.report-thumbnail-min-size") > 0; - } - }, - has_doc_without_text("Has document bitstream without TEXT item", null, ItemFilterDefs.CAT_MIME) { - public boolean testItem(Context context, Item item) { - int countDoc = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); - if (countDoc == 0) { - return false; - } - int countText = ItemFilterUtil.countBitstream(BundleName.TEXT, item); - return countDoc > countText; - } - }, - has_original_without_thumbnail("Has original bitstream without thumbnail", null, CAT_MISC) { - public boolean testItem(Context context, Item item) { - int countBit = ItemFilterUtil.countOriginalBitstream(item); - if (countBit == 0) { - return false; - } - int countThumb = ItemFilterUtil.countBitstream(BundleName.THUMBNAIL, item); - return countBit > countThumb; - } - }, - has_invalid_thumbnail_name("Has invalid thumbnail name (assumes one thumbnail for each original)", null, CAT_MISC) { - public boolean testItem(Context context, Item item) { - List originalNames = ItemFilterUtil.getBitstreamNames(BundleName.ORIGINAL, item); - List thumbNames = ItemFilterUtil.getBitstreamNames(BundleName.THUMBNAIL, item); - if (thumbNames.size() != originalNames.size()) { - return false; - } - for(String name: originalNames) { - if (!thumbNames.contains(name+".jpg")) { - return true; - } - } - return false; - } - }, - has_non_generated_thumb("Has non generated thumbnail", null, CAT_MISC) { - public boolean testItem(Context context, Item item) { - String[] generatedThumbDesc = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-gen-thumbnail-desc"); - int countThumb = ItemFilterUtil.countBitstream(BundleName.THUMBNAIL, item); - if (countThumb == 0) { - return false; - } - int countGen = ItemFilterUtil.countBitstreamByDesc(BundleName.THUMBNAIL, item, generatedThumbDesc); - return (countThumb > countGen); - } - }, - no_license("Doesn't have a license", null, CAT_MISC) { - public boolean testItem(Context context, Item item) { - return ItemFilterUtil.countBitstream(BundleName.LICENSE, item) == 0; - } - }, - has_license_documentation("Has documentation in the license bundle", null, CAT_MISC) { - public boolean testItem(Context context, Item item) { - List names = ItemFilterUtil.getBitstreamNames(BundleName.LICENSE, item); - for(String name: names) { - if (!name.equals("license.txt")) { - return true; - } - } - return false; - } - }, - ; - - private String title = null; - private String description = null; - private EnumItemFilterDefs(String title, String description, String category) { - this.title = title; - this.description = description; - this.category = category; - } - - private EnumItemFilterDefs() { - this(null, null, null); - } - - public String getName() { - return name(); - } - public String getTitle() { - return title; - } - public String getDescription() { - return description; - } - - private String category = null; - public String getCategory() { - return category; - } - } + public static final String CAT_MISC = "Bitstream Bundle Filters"; + public static final String CAT_MIME_SUPP = "Supported MIME Type Filters"; + private enum EnumItemFilterDefs implements ItemFilterTest + { + has_only_supp_image_type("Item Image Bitstreams are Supported", null, CAT_MIME_SUPP) + { + public boolean testItem(Context context, Item item) + { + int imageCount = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image/"); + if (imageCount == 0) + { + return false; + } + int suppImageCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedImageMimeTypes()); + return (imageCount == suppImageCount); + } + }, + has_unsupp_image_type("Item has Image Bitstream that is Unsupported", null, CAT_MIME_SUPP) + { + public boolean testItem(Context context, Item item) + { + int imageCount = ItemFilterUtil.countOriginalBitstreamMimeStartsWith(context, item, "image/"); + if (imageCount == 0) + { + return false; + } + int suppImageCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedImageMimeTypes()); + return (imageCount - suppImageCount) > 0; + } + }, + has_only_supp_doc_type("Item Document Bitstreams are Supported", null, CAT_MIME_SUPP) + { + public boolean testItem(Context context, Item item) + { + int docCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); + if (docCount == 0) + { + return false; + } + int suppDocCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedDocumentMimeTypes()); + return docCount == suppDocCount; + } + }, + has_unsupp_doc_type("Item has Document Bitstream that is Unsupported", null, CAT_MIME_SUPP) + { + public boolean testItem(Context context, Item item) + { + int docCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); + if (docCount == 0) + { + return false; + } + int suppDocCount = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getSupportedDocumentMimeTypes()); + return (docCount - suppDocCount) > 0; + } + }, + has_small_pdf("Has unusually small PDF", null, ItemFilterDefs.CAT_MIME) + { + public boolean testItem(Context context, Item item) + { + return ItemFilterUtil.countBitstreamSmallerThanMinSize(context, BundleName.ORIGINAL, item, ItemFilterDefs.MIMES_PDF, "rest.report-pdf-min-size") > 0; + } + }, + has_large_pdf("Has unusually large PDF", null, ItemFilterDefs.CAT_MIME) + { + public boolean testItem(Context context, Item item) + { + return ItemFilterUtil.countBitstreamLargerThanMaxSize(context, BundleName.ORIGINAL, item, ItemFilterDefs.MIMES_PDF, "rest.report-pdf-max-size") > 0; + } + }, + has_unsupported_bundle("Has bitstream in an unsuppored bundle", null, CAT_MISC) + { + public boolean testItem(Context context, Item item) + { + String[] bundleList = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-supp-bundles"); + return ItemFilterUtil.hasUnsupportedBundle(item, bundleList); + } + }, + has_small_thumbnail("Has unusually small thumbnail", null, CAT_MISC) + { + public boolean testItem(Context context, Item item) + { + return ItemFilterUtil.countBitstreamSmallerThanMinSize(context, BundleName.THUMBNAIL, item, ItemFilterDefs.MIMES_JPG, "rest.report-thumbnail-min-size") > 0; + } + }, + has_doc_without_text("Has document bitstream without TEXT item", null, ItemFilterDefs.CAT_MIME) + { + public boolean testItem(Context context, Item item) + { + int countDoc = ItemFilterUtil.countOriginalBitstreamMime(context, item, ItemFilterUtil.getDocumentMimeTypes()); + if (countDoc == 0) + { + return false; + } + int countText = ItemFilterUtil.countBitstream(BundleName.TEXT, item); + return countDoc > countText; + } + }, + has_original_without_thumbnail("Has original bitstream without thumbnail", null, CAT_MISC) + { + public boolean testItem(Context context, Item item) + { + int countBit = ItemFilterUtil.countOriginalBitstream(item); + if (countBit == 0) + { + return false; + } + int countThumb = ItemFilterUtil.countBitstream(BundleName.THUMBNAIL, item); + return countBit > countThumb; + } + }, + has_invalid_thumbnail_name("Has invalid thumbnail name (assumes one thumbnail for each original)", null, CAT_MISC) + { + public boolean testItem(Context context, Item item) + { + List originalNames = ItemFilterUtil.getBitstreamNames(BundleName.ORIGINAL, item); + List thumbNames = ItemFilterUtil.getBitstreamNames(BundleName.THUMBNAIL, item); + if (thumbNames.size() != originalNames.size()) + { + return false; + } + for (String name: originalNames) + { + if (!thumbNames.contains(name+".jpg")) + { + return true; + } + } + return false; + } + }, + has_non_generated_thumb("Has non generated thumbnail", null, CAT_MISC) + { + public boolean testItem(Context context, Item item) + { + String[] generatedThumbDesc = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-gen-thumbnail-desc"); + int countThumb = ItemFilterUtil.countBitstream(BundleName.THUMBNAIL, item); + if (countThumb == 0) + { + return false; + } + int countGen = ItemFilterUtil.countBitstreamByDesc(BundleName.THUMBNAIL, item, generatedThumbDesc); + return (countThumb > countGen); + } + }, + no_license("Doesn't have a license", null, CAT_MISC) + { + public boolean testItem(Context context, Item item) + { + return ItemFilterUtil.countBitstream(BundleName.LICENSE, item) == 0; + } + }, + has_license_documentation("Has documentation in the license bundle", null, CAT_MISC) + { + public boolean testItem(Context context, Item item) + { + List names = ItemFilterUtil.getBitstreamNames(BundleName.LICENSE, item); + for (String name: names) + { + if (!name.equals("license.txt")) + { + return true; + } + } + return false; + } + }, + ; + + private String title = null; + private String description = null; - public ItemFilterDefsMisc() { - } - public ItemFilterTest[] getFilters() { - return EnumItemFilterDefs.values(); - } + private EnumItemFilterDefs(String title, String description, String category) + { + this.title = title; + this.description = description; + this.category = category; + } + + private EnumItemFilterDefs() { + this(null, null, null); + } + + public String getName() { + return name(); + } + public String getTitle() { + return title; + } + public String getDescription() { + return description; + } + + private String category = null; + + public String getCategory() { + return category; + } + } + + public ItemFilterDefsMisc() { + } + + public ItemFilterTest[] getFilters() { + return EnumItemFilterDefs.values(); + } } diff --git a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsPerm.java b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsPerm.java index b0a3650190..c2ded2a9f8 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsPerm.java +++ b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterDefsPerm.java @@ -25,102 +25,131 @@ import org.dspace.rest.filter.ItemFilterUtil.BundleName; */ public class ItemFilterDefsPerm implements ItemFilterList { protected static AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - public static final String CAT_PERM = "Perimission Filters"; - private static Logger log = Logger.getLogger(ItemFilterDefsPerm.class); - public ItemFilterDefsPerm(){ - } - public enum EnumItemFilterPermissionDefs implements ItemFilterTest { - has_restricted_original("Item has Restricted Original Bitstream", - "Item has at least one original bitstream that is not accessible to Anonymous user", CAT_PERM) { - public boolean testItem(Context context, Item item) { - try { - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(BundleName.ORIGINAL)) { - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - if (!authorizeService.authorizeActionBoolean(getAnonContext(), bit, org.dspace.core.Constants.READ)) { - return true; - } - } - } - } catch (SQLException e) { - ItemFilterDefsPerm.log.warn("SQL Exception testing original bitstream access " + e.getMessage(), e); - } - return false; - } - }, - has_restricted_thumbnail("Item has Restricted Thumbnail", - "Item has at least one thumbnail that is not accessible to Anonymous user", CAT_PERM) { - public boolean testItem(Context context, Item item) { - try { - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(BundleName.THUMBNAIL)) { - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - if (!authorizeService.authorizeActionBoolean(getAnonContext(), bit, org.dspace.core.Constants.READ)) { - return true; - } - } - } - } catch (SQLException e) { - ItemFilterDefsPerm.log.warn("SQL Exception testing thumbnail bitstream access " + e.getMessage(), e); - } - return false; - } - }, - has_restricted_metadata("Item has Restricted Metadata", - "Item has metadata that is not accessible to Anonymous user", CAT_PERM) { - public boolean testItem(Context context, Item item) { - try { - return !authorizeService.authorizeActionBoolean(getAnonContext(), item, org.dspace.core.Constants.READ); - } catch (SQLException e) { - ItemFilterDefsPerm.log.warn("SQL Exception testing item metadata access " + e.getMessage(), e); - return false; - } - } - }, - ; - - private static Context anonContext; - private static Context getAnonContext() { - if (anonContext == null) { - anonContext = new Context(); - } - return anonContext; - } - - - private String title = null; - private String description = null; - private EnumItemFilterPermissionDefs(String title, String description, String category) { - this.title = title; - this.description = description; - this.category = category; - } - - private EnumItemFilterPermissionDefs() { - this(null, null, null); - } - - public String getName() { - return name(); - } - public String getTitle() { - return title; - } - public String getDescription() { - return description; - } - private String category = null; - public String getCategory() { - return category; - } - } + public static final String CAT_PERM = "Perimission Filters"; + private static Logger log = Logger.getLogger(ItemFilterDefsPerm.class); - @Override - public ItemFilterTest[] getFilters() { - return EnumItemFilterPermissionDefs.values(); - } -} \ No newline at end of file + public ItemFilterDefsPerm() { + } + + public enum EnumItemFilterPermissionDefs implements ItemFilterTest + { + has_restricted_original("Item has Restricted Original Bitstream", + "Item has at least one original bitstream that is not accessible to Anonymous user", CAT_PERM) + { + public boolean testItem(Context context, Item item) + { + try + { + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(BundleName.ORIGINAL)) + { + continue; + } + for (Bitstream bit: bundle.getBitstreams()) + { + if (!authorizeService.authorizeActionBoolean(getAnonContext(), bit, org.dspace.core.Constants.READ)) + { + return true; + } + } + } + } + catch (SQLException e) + { + ItemFilterDefsPerm.log.warn("SQL Exception testing original bitstream access " + e.getMessage(), e); + } + return false; + } + }, + has_restricted_thumbnail("Item has Restricted Thumbnail", + "Item has at least one thumbnail that is not accessible to Anonymous user", CAT_PERM) + { + public boolean testItem(Context context, Item item) + { + try + { + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(BundleName.THUMBNAIL)) + { + continue; + } + for (Bitstream bit: bundle.getBitstreams()) + { + if (!authorizeService.authorizeActionBoolean(getAnonContext(), bit, org.dspace.core.Constants.READ)) + { + return true; + } + } + } + } + catch (SQLException e) + { + ItemFilterDefsPerm.log.warn("SQL Exception testing thumbnail bitstream access " + e.getMessage(), e); + } + return false; + } + }, + has_restricted_metadata("Item has Restricted Metadata", + "Item has metadata that is not accessible to Anonymous user", CAT_PERM) + { + public boolean testItem(Context context, Item item) + { + try + { + return !authorizeService.authorizeActionBoolean(getAnonContext(), item, org.dspace.core.Constants.READ); + } + catch (SQLException e) + { + ItemFilterDefsPerm.log.warn("SQL Exception testing item metadata access " + e.getMessage(), e); + return false; + } + } + }, + ; + + private static Context anonContext; + private static Context getAnonContext() + { + if (anonContext == null) { + anonContext = new Context(); + } + return anonContext; + } + + + private String title = null; + private String description = null; + private EnumItemFilterPermissionDefs(String title, String description, String category) + { + this.title = title; + this.description = description; + this.category = category; + } + + private EnumItemFilterPermissionDefs() { + this(null, null, null); + } + + public String getName() { + return name(); + } + public String getTitle() { + return title; + } + public String getDescription() { + return description; + } + + private String category = null; + public String getCategory() { + return category; + } + } + + @Override + public ItemFilterTest[] getFilters() { + return EnumItemFilterPermissionDefs.values(); + } +} diff --git a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterSet.java b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterSet.java index b038a076bd..edd667f572 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterSet.java +++ b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterSet.java @@ -39,10 +39,10 @@ public class ItemFilterSet { * Construct a set of Item Filters identified by a list string. * * @param filterList - * Comma separated list of filter names to include - * @see org.dspace.rest.common#ItemFilter.ALL to retrieve all filters + * Comma separated list of filter names to include. + * Use {@link org.dspace.rest.common.ItemFilter#ALL} to retrieve all filters. * @param reportItems - * If true, return item details. If false, return only counts of items. + * If true, return item details. If false, return only counts of items. */ public ItemFilterSet(String filterList, boolean reportItems) { log.debug(String.format("Create ItemFilterSet: %s", filterList)); @@ -83,7 +83,8 @@ public class ItemFilterSet { } /** - * Get all of the Item Filters initialized into the Item Filter Sest + * Get all of the Item Filters initialized into the Item Filter Set + * * @return a list of Item Filters initialized into the Item Filter Set */ public List getItemFilters() { @@ -93,6 +94,11 @@ public class ItemFilterSet { /** * Evaluate a set of Items against the Item Filters in the Item Filter Set * Current DSpace Context + * + * @param context + * Current DSpace Context + * @param servletContext + * Context of the servlet container. * @param childItems * Collection of Items to Evaluate * @param save @@ -102,7 +108,9 @@ public class ItemFilterSet { * @return * The number of items evaluated * @throws WebApplicationException + * Runtime exception for applications. * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public int processSaveItems(Context context, ServletContext servletContext, Iterator childItems, boolean save, String expand) throws WebApplicationException, SQLException { return processSaveItems(context, servletContext, childItems, new ArrayList(), save, expand); @@ -110,7 +118,11 @@ public class ItemFilterSet { /** * Evaluate a set of Items against the Item Filters in the Item Filter Set + * + * @param context * Current DSpace Context + * @param servletContext + * Context of the servlet container. * @param childItems * Collection of Items to Evaluate * @param items @@ -122,7 +134,9 @@ public class ItemFilterSet { * @return * The number of items evaluated * @throws WebApplicationException + * Runtime exception for applications. * @throws SQLException + * An exception that provides information on a database access error or other errors. */ public int processSaveItems(Context context, ServletContext servletContext, Iterator childItems, List items, boolean save, String expand) throws WebApplicationException, SQLException { int count = 0; diff --git a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterUtil.java b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterUtil.java index 15f5b398a3..2a71be5db0 100644 --- a/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterUtil.java +++ b/dspace-rest/src/main/java/org/dspace/rest/filter/ItemFilterUtil.java @@ -27,230 +27,311 @@ import com.ibm.icu.util.Calendar; public class ItemFilterUtil { protected static ItemService itemService = ContentServiceFactory.getInstance().getItemService(); static Logger log = Logger.getLogger(ItemFilterUtil.class); - public enum BundleName{ORIGINAL,TEXT,LICENSE,THUMBNAIL;} - - static String[] getDocumentMimeTypes() { - return DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-mime-document"); - } - - static String[] getSupportedDocumentMimeTypes() { - return DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-mime-document-supported"); - } + public enum BundleName{ORIGINAL,TEXT,LICENSE,THUMBNAIL;} - static String[] getSupportedImageMimeTypes() { - return DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-mime-document-image"); - } + static String[] getDocumentMimeTypes() { + return DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-mime-document"); + } - static int countOriginalBitstream(Item item) { - return countBitstream(BundleName.ORIGINAL, item); - } - static int countBitstream(BundleName bundleName, Item item) { - int count = 0; - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(bundleName.name())){ - continue; - } - count += bundle.getBitstreams().size(); + static String[] getSupportedDocumentMimeTypes() { + return DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-mime-document-supported"); + } + + static String[] getSupportedImageMimeTypes() { + return DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("rest.report-mime-document-image"); + } + + static int countOriginalBitstream(Item item) { + return countBitstream(BundleName.ORIGINAL, item); + } + + static int countBitstream(BundleName bundleName, Item item) + { + int count = 0; + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(bundleName.name())) + { + continue; + } + count += bundle.getBitstreams().size(); } - return count; - } + return count; + } - static List getBitstreamNames(BundleName bundleName, Item item) { - ArrayList names = new ArrayList(); - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(bundleName.name())){ - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - names.add(bit.getName()); - } - } - return names; - } - - - static int countOriginalBitstreamMime(Context context, Item item, String[] mimeList) { - return countBitstreamMime(context, BundleName.ORIGINAL, item, mimeList); - } - static int countBitstreamMime(Context context, BundleName bundleName, Item item, String[] mimeList) { - int count = 0; - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(bundleName.name())){ - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - for(String mime: mimeList) { - try { - if (bit.getFormat(context).getMIMEType().equals(mime.trim())) { - count++; - } - } catch (SQLException e) { - log.error("Get format error for bitstream " + bit.getName()); - } - } + static List getBitstreamNames(BundleName bundleName, Item item) + { + ArrayList names = new ArrayList(); + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(bundleName.name())) + { + continue; + } + for (Bitstream bit: bundle.getBitstreams()) + { + names.add(bit.getName()); } } - return count; - } + return names; + } - static int countBitstreamByDesc(BundleName bundleName, Item item, String[] descList) { - int count = 0; - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(bundleName.name())){ - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - for(String desc: descList) { - String bitDesc = bit.getDescription(); - if (bitDesc == null) { - continue; - } - if (bitDesc.equals(desc.trim())) { - count++; + + static int countOriginalBitstreamMime(Context context, Item item, String[] mimeList) { + return countBitstreamMime(context, BundleName.ORIGINAL, item, mimeList); + } + + static int countBitstreamMime(Context context, BundleName bundleName, Item item, String[] mimeList) + { + int count = 0; + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(bundleName.name())) + { + continue; + } + for (Bitstream bit: bundle.getBitstreams()) + { + for (String mime: mimeList) + { + try + { + if (bit.getFormat(context).getMIMEType().equals(mime.trim())) + { + count++; + } } - } + catch (SQLException e) + { + log.error("Get format error for bitstream " + bit.getName()); + } + } } } - return count; - } + return count; + } - static int countBitstreamSmallerThanMinSize(Context context, BundleName bundleName, Item item, String[] mimeList, String prop) { - long size = DSpaceServicesFactory.getInstance().getConfigurationService().getLongProperty(prop); - int count = 0; - try { - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(bundleName.name())){ - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - for(String mime: mimeList) { - if (bit.getFormat(context).getMIMEType().equals(mime.trim())) { - if (bit.getSize() < size) { - count++; - } - } - } + static int countBitstreamByDesc(BundleName bundleName, Item item, String[] descList) + { + int count = 0; + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(bundleName.name())) + { + continue; + } + for (Bitstream bit: bundle.getBitstreams()) + { + for (String desc: descList) + { + String bitDesc = bit.getDescription(); + if (bitDesc == null) + { + continue; + } + if (bitDesc.equals(desc.trim())) + { + count++; + } } } - } catch (SQLException e) { } - return count; - } - - static int countBitstreamLargerThanMaxSize(Context context, BundleName bundleName, Item item, String[] mimeList, String prop) { - long size = DSpaceServicesFactory.getInstance().getConfigurationService().getLongProperty(prop); - int count = 0; - try { - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(bundleName.name())){ - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - for(String mime: mimeList) { - if (bit.getFormat(context).getMIMEType().equals(mime.trim())) { - if (bit.getSize() > size) { - count++; - } - } - } + return count; + } + + static int countBitstreamSmallerThanMinSize(Context context, BundleName bundleName, Item item, String[] mimeList, String prop) + { + long size = DSpaceServicesFactory.getInstance().getConfigurationService().getLongProperty(prop); + int count = 0; + try + { + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(bundleName.name())) + { + continue; } - } - } catch (SQLException e) { - } - return count; - } - - static int countOriginalBitstreamMimeStartsWith(Context context, Item item, String prefix) { - return countBitstreamMimeStartsWith(context, BundleName.ORIGINAL, item, prefix); - } - static int countBitstreamMimeStartsWith(Context context, BundleName bundleName, Item item, String prefix) { - int count = 0; - try { - for(Bundle bundle: item.getBundles()){ - if (!bundle.getName().equals(bundleName.name())){ - continue; - } - for(Bitstream bit: bundle.getBitstreams()) { - if (bit.getFormat(context).getMIMEType().startsWith(prefix)) { - count++; + for (Bitstream bit: bundle.getBitstreams()) + { + for (String mime: mimeList) + { + if (bit.getFormat(context).getMIMEType().equals(mime.trim())) + { + if (bit.getSize() < size) + { + count++; + } + } } } } } catch (SQLException e) { } - return count; - } + return count; + } - static boolean hasUnsupportedBundle(Item item, String[] bundleList) { - if (bundleList == null) { - return false; - } - ArrayList bundles = new ArrayList(); - for(String bundleName: bundleList) { - bundles.add(bundleName.trim()); - } - for(Bundle bundle: item.getBundles()) { - if (!bundles.contains(bundle.getName())) { - return true; - } - } - return false; - } - static boolean hasOriginalBitstreamMime(Context context, Item item, String[] mimeList) { - return hasBitstreamMime(context, BundleName.ORIGINAL, item, mimeList); - } - static boolean hasBitstreamMime(Context context, BundleName bundleName, Item item, String[] mimeList) { - return countBitstreamMime(context, bundleName, item, mimeList) > 0; - } + static int countBitstreamLargerThanMaxSize(Context context, BundleName bundleName, Item item, String[] mimeList, String prop) + { + long size = DSpaceServicesFactory.getInstance().getConfigurationService().getLongProperty(prop); + int count = 0; + try + { + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(bundleName.name())) + { + continue; + } + for (Bitstream bit: bundle.getBitstreams()) + { + for (String mime: mimeList) + { + if (bit.getFormat(context).getMIMEType().equals(mime.trim())) + { + if (bit.getSize() > size) + { + count++; + } + } + } + } + } + } + catch (SQLException e) + { + } + return count; + } - static boolean hasMetadataMatch(Item item, String fieldList, Pattern regex) { - if (fieldList.equals("*")) { - for(MetadataValue md: itemService.getMetadata(item, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY)){ - if (regex.matcher(md.getValue()).matches()) { - return true; - } - } - } else { - for(String field: fieldList.split(",")) { - for(MetadataValue md: itemService.getMetadataByMetadataString(item, field.trim())){ - if (regex.matcher(md.getValue()).matches()) { - return true; - } - } - } - } - - return false; - } + static int countOriginalBitstreamMimeStartsWith(Context context, Item item, String prefix) { + return countBitstreamMimeStartsWith(context, BundleName.ORIGINAL, item, prefix); + } - static boolean hasOnlyMetadataMatch(Item item, String fieldList, Pattern regex) { - boolean matches = false; - if (fieldList.equals("*")) { - for(MetadataValue md: itemService.getMetadata(item, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY)){ - if (regex.matcher(md.getValue()).matches()) { - matches = true; - } else { - return false; - } - } - } else { - for(String field: fieldList.split(",")) { - for(MetadataValue md: itemService.getMetadataByMetadataString(item, field.trim())){ - if (regex.matcher(md.getValue()).matches()) { - matches = true; - } else { - return false; - } - } - } - } - return matches; - } + static int countBitstreamMimeStartsWith(Context context, BundleName bundleName, Item item, String prefix) + { + int count = 0; + try + { + for (Bundle bundle: item.getBundles()) + { + if (!bundle.getName().equals(bundleName.name())) + { + continue; + } + for (Bitstream bit: bundle.getBitstreams()) + { + if (bit.getFormat(context).getMIMEType().startsWith(prefix)) + { + count++; + } + } + } + } + catch (SQLException e) + { + } + return count; + } - static boolean recentlyModified(Item item, int days) { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DATE, -days); - return cal.getTime().before(item.getLastModified()); - } + static boolean hasUnsupportedBundle(Item item, String[] bundleList) + { + if (bundleList == null) + { + return false; + } + ArrayList bundles = new ArrayList(); + for (String bundleName: bundleList) + { + bundles.add(bundleName.trim()); + } + for (Bundle bundle: item.getBundles()) + { + if (!bundles.contains(bundle.getName())) + { + return true; + } + } + return false; + } + + static boolean hasOriginalBitstreamMime(Context context, Item item, String[] mimeList) { + return hasBitstreamMime(context, BundleName.ORIGINAL, item, mimeList); + } + + static boolean hasBitstreamMime(Context context, BundleName bundleName, Item item, String[] mimeList) { + return countBitstreamMime(context, bundleName, item, mimeList) > 0; + } + + static boolean hasMetadataMatch(Item item, String fieldList, Pattern regex) + { + if (fieldList.equals("*")) + { + for (MetadataValue md: itemService.getMetadata(item, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY)) + { + if (regex.matcher(md.getValue()).matches()) + { + return true; + } + } + } + else + { + for (String field: fieldList.split(",")) + { + for (MetadataValue md: itemService.getMetadataByMetadataString(item, field.trim())) + { + if (regex.matcher(md.getValue()).matches()) + { + return true; + } + } + } + } + + return false; + } + + static boolean hasOnlyMetadataMatch(Item item, String fieldList, Pattern regex) + { + boolean matches = false; + if (fieldList.equals("*")) + { + for (MetadataValue md: itemService.getMetadata(item, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY)) + { + if (regex.matcher(md.getValue()).matches()) + { + matches = true; + } + else + { + return false; + } + } + } + else + { + for (String field: fieldList.split(",")) + { + for (MetadataValue md: itemService.getMetadataByMetadataString(item, field.trim())) + { + if (regex.matcher(md.getValue()).matches()) + { + matches = true; + } + else + { + return false; + } + } + } + } + return matches; + } + + static boolean recentlyModified(Item item, int days) { + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.DATE, -days); + return cal.getTime().before(item.getLastModified()); + } } diff --git a/dspace-rest/src/main/java/org/dspace/utils/DSpaceWebapp.java b/dspace-rest/src/main/java/org/dspace/utils/DSpaceWebapp.java index d8392b00a2..6faa68ded4 100644 --- a/dspace-rest/src/main/java/org/dspace/utils/DSpaceWebapp.java +++ b/dspace-rest/src/main/java/org/dspace/utils/DSpaceWebapp.java @@ -13,7 +13,7 @@ import org.dspace.app.util.AbstractDSpaceWebapp; /** * An MBean to identify this web application. * - * @author Bram Luyten + * @author Bram Luyten (bram at atmire dot com) */ public class DSpaceWebapp extends AbstractDSpaceWebapp diff --git a/dspace-services/pom.xml b/dspace-services/pom.xml index c9c21e63c5..dc1e298da1 100644 --- a/dspace-services/pom.xml +++ b/dspace-services/pom.xml @@ -9,7 +9,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT diff --git a/dspace-solr/pom.xml b/dspace-solr/pom.xml index ec096e4149..020fedfe50 100644 --- a/dspace-solr/pom.xml +++ b/dspace-solr/pom.xml @@ -20,7 +20,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-solr/src/main/java/org/dspace/solr/filters/LocalHostRestrictionFilter.java b/dspace-solr/src/main/java/org/dspace/solr/filters/LocalHostRestrictionFilter.java index 723aee5313..05b0761917 100644 --- a/dspace-solr/src/main/java/org/dspace/solr/filters/LocalHostRestrictionFilter.java +++ b/dspace-solr/src/main/java/org/dspace/solr/filters/LocalHostRestrictionFilter.java @@ -20,46 +20,51 @@ import javax.servlet.http.HttpServletResponse; public class LocalHostRestrictionFilter implements Filter { - private boolean enabled = true; + private boolean enabled = true; - public LocalHostRestrictionFilter() { - // TODO Auto-generated constructor stub - } + public LocalHostRestrictionFilter() { + // TODO Auto-generated constructor stub + } - public void destroy() { - // TODO Auto-generated method stub + public void destroy() { + // TODO Auto-generated method stub - } + } - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) + throws IOException, ServletException + { - if(enabled){ - InetAddress ia = InetAddress.getLocalHost(); - String localAddr = ia.getHostAddress(); - String remoteAddr = request.getRemoteAddr(); + if (enabled){ + InetAddress ia = InetAddress.getLocalHost(); + String localAddr = ia.getHostAddress(); + String remoteAddr = request.getRemoteAddr(); - if(!(localAddr.equals(remoteAddr) || remoteAddr.equals("127.0.0.1") || remoteAddr.startsWith("0:0:0:0:0:0:0:1"))) - { - ((HttpServletResponse)response).sendError(403); - return; - } + if (!(localAddr.equals(remoteAddr) || + remoteAddr.equals("127.0.0.1") || + remoteAddr.startsWith("0:0:0:0:0:0:0:1"))) + { + ((HttpServletResponse)response).sendError(403); + return; + } - } + } - chain.doFilter(request, response); - } - - /** - * - */ - public void init(FilterConfig arg0) throws ServletException { - String restrict = arg0.getServletContext().getInitParameter("LocalHostRestrictionFilter.localhost"); - if("false".equalsIgnoreCase(restrict)) - { - enabled = false; - } - - } + chain.doFilter(request, response); + } + /** + * + */ + public void init(FilterConfig arg0) + throws ServletException + { + String restrict = arg0.getServletContext().getInitParameter( + "LocalHostRestrictionFilter.localhost"); + if ("false".equalsIgnoreCase(restrict)) + { + enabled = false; + } + } } diff --git a/dspace-sword/pom.xml b/dspace-sword/pom.xml index d6f331adfd..78c126c7d3 100644 --- a/dspace-sword/pom.xml +++ b/dspace-sword/pom.xml @@ -15,7 +15,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-sword/src/main/java/org/dspace/sword/ATOMCollectionGenerator.java b/dspace-sword/src/main/java/org/dspace/sword/ATOMCollectionGenerator.java index b7c0777c9c..bb5d555a93 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/ATOMCollectionGenerator.java +++ b/dspace-sword/src/main/java/org/dspace/sword/ATOMCollectionGenerator.java @@ -22,9 +22,10 @@ public abstract class ATOMCollectionGenerator protected SWORDService swordService; /** - * Create a new ATOM collection generator using the given sword service. + * Create a new ATOM collection generator using the given SWORD service. * * @param service + * SWORD service */ public ATOMCollectionGenerator(SWORDService service) { @@ -35,7 +36,10 @@ public abstract class ATOMCollectionGenerator * Build the ATOM Collection which represents the given DSpace Object. * * @param dso + * target DSpace object + * @return ATOM collection representing the DSpace object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public abstract Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException; diff --git a/dspace-sword/src/main/java/org/dspace/sword/BitstreamEntryGenerator.java b/dspace-sword/src/main/java/org/dspace/sword/BitstreamEntryGenerator.java index 2b21455a4f..c65800522d 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/BitstreamEntryGenerator.java +++ b/dspace-sword/src/main/java/org/dspace/sword/BitstreamEntryGenerator.java @@ -36,6 +36,7 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry * a bitstream * * @param service + * SWORD service */ protected BitstreamEntryGenerator(SWORDService service) { diff --git a/dspace-sword/src/main/java/org/dspace/sword/CollectionCollectionGenerator.java b/dspace-sword/src/main/java/org/dspace/sword/CollectionCollectionGenerator.java index 7c8b69bdf3..4a2bfc91eb 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/CollectionCollectionGenerator.java +++ b/dspace-sword/src/main/java/org/dspace/sword/CollectionCollectionGenerator.java @@ -25,15 +25,17 @@ import java.util.List; public class CollectionCollectionGenerator extends ATOMCollectionGenerator { /** logger */ - private static Logger log = Logger - .getLogger(CollectionCollectionGenerator.class); + private static Logger log = + Logger.getLogger(CollectionCollectionGenerator.class); - protected CollectionService collectionService = ContentServiceFactory - .getInstance().getCollectionService(); + protected CollectionService collectionService = + ContentServiceFactory.getInstance().getCollectionService(); /** - * Construct an object taking the sword service instance an argument + * Construct an object taking the SWORD service instance an argument + * * @param service + * SWORD service implementation */ public CollectionCollectionGenerator(SWORDService service) { @@ -44,8 +46,11 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator /** * Build the collection for the given DSpaceObject. In this implementation, * if the object is not a DSpace Collection, it will throw an exception. + * * @param dso + * target DSpace object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException @@ -53,9 +58,9 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator if (!(dso instanceof org.dspace.content.Collection)) { log.error( - "buildCollection passed argument which is not of type Collection"); + "buildCollection passed argument which is not of type Collection"); throw new DSpaceSWORDException( - "Incorrect ATOMCollectionGenerator instantiated"); + "Incorrect ATOMCollectionGenerator instantiated"); } // get the things we need out of the service diff --git a/dspace-sword/src/main/java/org/dspace/sword/CollectionDepositor.java b/dspace-sword/src/main/java/org/dspace/sword/CollectionDepositor.java index 067cab68dc..e08a0d1028 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/CollectionDepositor.java +++ b/dspace-sword/src/main/java/org/dspace/sword/CollectionDepositor.java @@ -43,17 +43,17 @@ public class CollectionDepositor extends Depositor /** logger */ private static Logger log = Logger.getLogger(CollectionDepositor.class); - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); - protected BundleService bundleService = ContentServiceFactory.getInstance() - .getBundleService(); + protected BundleService bundleService = + ContentServiceFactory.getInstance().getBundleService(); - protected BitstreamService bitstreamService = ContentServiceFactory - .getInstance().getBitstreamService(); + protected BitstreamService bitstreamService = + ContentServiceFactory.getInstance().getBitstreamService(); - protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory - .getInstance().getBitstreamFormatService(); + protected BitstreamFormatService bitstreamFormatService = + ContentServiceFactory.getInstance().getBitstreamFormatService(); /** * The DSpace Collection we are depositing into @@ -66,8 +66,11 @@ public class CollectionDepositor extends Depositor * this constructor will throw an Exception * * @param swordService + * SWORD service * @param dso + * target DSpace object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public CollectionDepositor(SWORDService swordService, DSpaceObject dso) throws DSpaceSWORDException @@ -77,8 +80,8 @@ public class CollectionDepositor extends Depositor if (!(dso instanceof Collection)) { throw new DSpaceSWORDException( - "You tried to initialise the collection depositor with something" + - "other than a collection object"); + "You tried to initialise the collection depositor with something" + + "other than a collection object"); } this.collection = (Collection) dso; @@ -90,8 +93,10 @@ public class CollectionDepositor extends Depositor * Perform a deposit, using the supplied SWORD Deposit object. * * @param deposit - * @throws SWORDErrorException + * deposit request + * @throws SWORDErrorException on generic SWORD exception * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public DepositResult doDeposit(Deposit deposit) throws SWORDErrorException, DSpaceSWORDException @@ -110,29 +115,29 @@ public class CollectionDepositor extends Depositor collection)) { log.error("Unacceptable content type detected: " + - deposit.getContentType() + " for collection " + - collection.getID()); + deposit.getContentType() + " for collection " + + collection.getID()); throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT, - "Unacceptable content type in deposit request: " + - deposit.getContentType()); + "Unacceptable content type in deposit request: " + + deposit.getContentType()); } // determine if this is an acceptable packaging type for the deposit // if not, we throw a 415 HTTP error (Unsupported Media Type, ERROR_CONTENT) - if (!swordConfig - .isSupportedMediaType(deposit.getPackaging(), this.collection)) + if (!swordConfig.isSupportedMediaType( + deposit.getPackaging(), this.collection)) { log.error("Unacceptable packaging type detected: " + - deposit.getPackaging() + "for collection" + - collection.getID()); + deposit.getPackaging() + "for collection" + + collection.getID()); throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT, - "Unacceptable packaging type in deposit request: " + - deposit.getPackaging()); + "Unacceptable packaging type in deposit request: " + + deposit.getPackaging()); } // Obtain the relevant ingester from the factory - SWORDIngester si = SWORDIngesterFactory - .getInstance(context, deposit, collection); + SWORDIngester si = SWORDIngesterFactory.getInstance( + context, deposit, collection); swordService.message("Loaded ingester: " + si.getClass().getName()); // do the deposit @@ -146,15 +151,15 @@ public class CollectionDepositor extends Depositor if (swordConfig.isKeepOriginal()) { swordService.message( - "DSpace will store an original copy of the deposit, " + - "as well as ingesting the item into the archive"); + "DSpace will store an original copy of the deposit, " + + "as well as ingesting the item into the archive"); // in order to be allowed to add the file back to the item, we need to ignore authorisations // for a moment context.turnOffAuthorisationSystem(); - String bundleName = ConfigurationManager - .getProperty("sword-server", "bundle.name"); + String bundleName = ConfigurationManager.getProperty( + "sword-server", "bundle.name"); if (bundleName == null || "".equals(bundleName)) { bundleName = "SWORD"; @@ -173,8 +178,8 @@ public class CollectionDepositor extends Depositor } if (swordBundle == null) { - swordBundle = bundleService - .create(context, item, bundleName); + swordBundle = bundleService.create( + context, item, bundleName); } String fn = swordService.getFilename(context, deposit, true); @@ -184,8 +189,8 @@ public class CollectionDepositor extends Depositor try { fis = new FileInputStream(deposit.getFile()); - bitstream = bitstreamService - .create(context, swordBundle, fis); + bitstream = bitstreamService.create( + context, swordBundle, fis); } finally { @@ -198,8 +203,8 @@ public class CollectionDepositor extends Depositor bitstream.setName(context, fn); bitstream.setDescription(context, "SWORD deposit package"); - BitstreamFormat bf = bitstreamFormatService - .findByMIMEType(context, deposit.getContentType()); + BitstreamFormat bf = bitstreamFormatService.findByMIMEType( + context, deposit.getContentType()); if (bf != null) { bitstreamService.setFormat(context, bitstream, bf); @@ -210,7 +215,7 @@ public class CollectionDepositor extends Depositor itemService.update(context, item); swordService.message("Original package stored as " + fn + - ", in item bundle " + swordBundle); + ", in item bundle " + swordBundle); // now reset the context ignore authorisation context.restoreAuthSystemState(); @@ -241,7 +246,9 @@ public class CollectionDepositor extends Depositor * to abort the database connection, so no changes are written. * * @param result + * deposit result to undo * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public void undoDeposit(DepositResult result) throws DSpaceSWORDException { diff --git a/dspace-sword/src/main/java/org/dspace/sword/CollectionLocation.java b/dspace-sword/src/main/java/org/dspace/sword/CollectionLocation.java index 3dd44eda98..5a36d4f6cc 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/CollectionLocation.java +++ b/dspace-sword/src/main/java/org/dspace/sword/CollectionLocation.java @@ -42,8 +42,10 @@ public class CollectionLocation * unless configuration changes are made to DSpace * * @param collection + * collection to query * @return The Deposit URL * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getLocation(Collection collection) throws DSpaceSWORDException @@ -59,6 +61,7 @@ public class CollectionLocation * @param location the URL to resolve to a collection * @return The collection to which the url resolves * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public Collection getCollection(Context context, String location) throws DSpaceSWORDException @@ -85,7 +88,7 @@ public class CollectionLocation if (!(dso instanceof Collection)) { throw new DSpaceSWORDException( - "The deposit URL does not resolve to a valid collection"); + "The deposit URL does not resolve to a valid collection"); } return (Collection) dso; @@ -94,7 +97,7 @@ public class CollectionLocation { log.error("Caught exception:", e); throw new DSpaceSWORDException( - "There was a problem resolving the collection", e); + "There was a problem resolving the collection", e); } } @@ -113,12 +116,13 @@ public class CollectionLocation * * @return the base URL for sword deposit * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ private String getBaseUrl() throws DSpaceSWORDException { - String depositUrl = ConfigurationManager - .getProperty("sword-server", "deposit.url"); + String depositUrl = ConfigurationManager.getProperty( + "sword-server", "deposit.url"); if (depositUrl == null || "".equals(depositUrl)) { String dspaceUrl = ConfigurationManager @@ -126,7 +130,7 @@ public class CollectionLocation if (dspaceUrl == null || "".equals(dspaceUrl)) { throw new DSpaceSWORDException( - "Unable to construct deposit urls, due to missing/invalid config in sword.deposit.url and/or dspace.baseUrl"); + "Unable to construct deposit urls, due to missing/invalid config in sword.deposit.url and/or dspace.baseUrl"); } try @@ -138,8 +142,8 @@ public class CollectionLocation catch (MalformedURLException e) { throw new DSpaceSWORDException( - "Unable to construct deposit urls, due to invalid dspace.baseUrl " + - e.getMessage(), e); + "Unable to construct deposit urls, due to invalid dspace.baseUrl " + + e.getMessage(), e); } } diff --git a/dspace-sword/src/main/java/org/dspace/sword/DSpaceATOMEntry.java b/dspace-sword/src/main/java/org/dspace/sword/DSpaceATOMEntry.java index 409f06ce3c..1c027de0a6 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/DSpaceATOMEntry.java +++ b/dspace-sword/src/main/java/org/dspace/sword/DSpaceATOMEntry.java @@ -49,9 +49,10 @@ public abstract class DSpaceATOMEntry protected Deposit deposit = null; /** - * Create a new atom entry object around the given service + * Create a new ATOM entry object around the given service * * @param service + * SWORD service implementation */ protected DSpaceATOMEntry(SWORDService service) { @@ -77,7 +78,10 @@ public abstract class DSpaceATOMEntry * of the Bitstream. * * @param dso + * target DSpace object + * @return SWORD entry for the given DSpace object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public SWORDEntry getSWORDEntry(DSpaceObject dso) throws DSpaceSWORDException @@ -94,7 +98,7 @@ public abstract class DSpaceATOMEntry else { throw new DSpaceSWORDException( - "Can only recover a sword entry for a bitstream via this method"); + "Can only recover a sword entry for a bitstream via this method"); } this.constructEntry(); @@ -112,6 +116,8 @@ public abstract class DSpaceATOMEntry * @param result the result of the deposit operation * @param deposit the original deposit request * @return the SWORDEntry for the item + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public SWORDEntry getSWORDEntry(DepositResult result, Deposit deposit) throws DSpaceSWORDException @@ -133,6 +139,7 @@ public abstract class DSpaceATOMEntry * Construct the entry * * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ protected void constructEntry() throws DSpaceSWORDException @@ -197,8 +204,8 @@ public abstract class DSpaceATOMEntry */ protected void addGenerator() { - boolean identify = ConfigurationManager - .getBooleanProperty("sword-server", "identify-version"); + boolean identify = ConfigurationManager.getBooleanProperty( + "sword-server", "identify-version"); SWORDUrlManager urlManager = swordService.getUrlManager(); String softwareUri = urlManager.getGeneratorUrl(); if (identify) @@ -262,6 +269,8 @@ public abstract class DSpaceATOMEntry * Add all the subject classifications from the bibliographic * metadata. * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addCategories() throws DSpaceSWORDException; @@ -269,6 +278,8 @@ public abstract class DSpaceATOMEntry * Set the content type that DSpace received. This is just * "application/zip" in this default implementation. * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addContentElement() throws DSpaceSWORDException; @@ -278,18 +289,25 @@ public abstract class DSpaceATOMEntry * passed handle is used. It is set in the form that * they can be used to access the resource over http (i.e. * a real URL). + * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addIdentifier() throws DSpaceSWORDException; /** * Add links associated with this item. * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addLinks() throws DSpaceSWORDException; /** * Add the date of publication from the bibliographic metadata * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addPublishDate() throws DSpaceSWORDException; @@ -297,24 +315,32 @@ public abstract class DSpaceATOMEntry * Add rights information. This attaches an href to the URL * of the item's licence file * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addRights() throws DSpaceSWORDException; /** * Add the summary/abstract from the bibliographic metadata * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addSummary() throws DSpaceSWORDException; /** * Add the title from the bibliographic metadata * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addTitle() throws DSpaceSWORDException; /** * Add the date that this item was last updated * + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ abstract void addLastUpdatedDate() throws DSpaceSWORDException; } diff --git a/dspace-sword/src/main/java/org/dspace/sword/DepositManager.java b/dspace-sword/src/main/java/org/dspace/sword/DepositManager.java index e8520af921..d177baf0d9 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/DepositManager.java +++ b/dspace-sword/src/main/java/org/dspace/sword/DepositManager.java @@ -48,6 +48,7 @@ public class DepositManager * the SWORD service implementation * * @param service + * SWORD service */ public DepositManager(SWORDService service) { @@ -70,17 +71,17 @@ public class DepositManager if (dso instanceof Collection) { CollectionService collectionService = ContentServiceFactory - .getInstance().getCollectionService(); + .getInstance().getCollectionService(); swordService.message( - "Location resolves to collection with handle: " + - dso.getHandle() + - " and name: " + - collectionService.getName((Collection) dso)); + "Location resolves to collection with handle: " + + dso.getHandle() + + " and name: " + + collectionService.getName((Collection) dso)); } else if (dso instanceof Item) { swordService.message("Location resolves to item with handle: " + - dso.getHandle()); + dso.getHandle()); } return dso; @@ -91,8 +92,13 @@ public class DepositManager * the deposit process. The returned DepositRequest can be * used then to assemble the SWORD response. * + * @param deposit + * deposit request * @return the response to the deposit request * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception + * @throws SWORDAuthenticationException Thrown if the authentication fails */ public DepositResponse deposit(Deposit deposit) throws DSpaceSWORDException, SWORDErrorException, @@ -120,22 +126,21 @@ public class DepositManager { oboEmail = swordContext.getOnBehalfOf().getEmail(); } - log.info(LogManager - .getHeader(context, "deposit_failed_authorisation", - "user=" + - swordContext.getAuthenticated().getEmail() + - ",on_behalf_of=" + oboEmail)); + log.info(LogManager.getHeader(context, + "deposit_failed_authorisation", + "user=" + swordContext.getAuthenticated().getEmail() + + ",on_behalf_of=" + oboEmail)); throw new SWORDAuthenticationException( - "Cannot submit to the given collection with this context"); + "Cannot submit to the given collection with this context"); } // make a note of the authentication in the verbose string swordService.message("Authenticated user: " + - swordContext.getAuthenticated().getEmail()); + swordContext.getAuthenticated().getEmail()); if (swordContext.getOnBehalfOf() != null) { swordService.message("Depositing on behalf of: " + - swordContext.getOnBehalfOf().getEmail()); + swordContext.getOnBehalfOf().getEmail()); } // determine which deposit engine we initialise @@ -143,22 +148,22 @@ public class DepositManager if (dso instanceof Collection) { swordService.message( - "Initialising depositor for an Item in a Collection"); + "Initialising depositor for an Item in a Collection"); dep = new CollectionDepositor(swordService, dso); } else if (dso instanceof Item) { swordService.message( - "Initialising depositor for a Bitstream in an Item"); + "Initialising depositor for a Bitstream in an Item"); dep = new ItemDepositor(swordService, dso); } if (dep == null) { log.error( - "The specified deposit target does not exist, or is not a collection or an item"); + "The specified deposit target does not exist, or is not a collection or an item"); throw new DSpaceSWORDException( - "Deposit target is not a collection or an item"); + "Deposit target is not a collection or an item"); } DepositResult result = null; @@ -201,21 +206,20 @@ public class DepositManager DSpaceATOMEntry dsatom = null; if (result.getItem() != null) { - swordService - .message("Initialising ATOM entry generator for an Item"); + swordService.message("Initialising ATOM entry generator for an Item"); dsatom = new ItemEntryGenerator(swordService); } else if (result.getBitstream() != null) { swordService.message( - "Initialising ATOM entry generator for a Bitstream"); + "Initialising ATOM entry generator for a Bitstream"); dsatom = new BitstreamEntryGenerator(swordService); } if (dsatom == null) { log.error("The deposit failed, see exceptions for explanation"); throw new DSpaceSWORDException( - "Result of deposit did not yield an Item or a Bitstream"); + "Result of deposit did not yield an Item or a Bitstream"); } SWORDEntry entry = dsatom.getSWORDEntry(result, deposit); @@ -225,17 +229,17 @@ public class DepositManager { dep.undoDeposit(result); swordService.message( - "NoOp Requested: Removed all traces of submission"); + "NoOp Requested: Removed all traces of submission"); } entry.setNoOp(deposit.isNoOp()); Date finish = new Date(); long delta = finish.getTime() - start.getTime(); - swordService - .message("Total time for deposit processing: " + delta + " ms"); + swordService.message( + "Total time for deposit processing: " + delta + " ms"); entry.setVerboseDescription( - swordService.getVerboseDescription().toString()); + swordService.getVerboseDescription().toString()); response.setEntry(entry); @@ -243,10 +247,11 @@ public class DepositManager } /** - * Store original package on disk and companion file containing SWORD headers as found in the deposit object - * Also write companion file with header info from the deposit object. + * Store original package on disk and companion file containing SWORD + * headers as found in the deposit object + * Also write companion file with header info from the deposit object. * - * @param deposit + * @param deposit the original deposit request */ private void storePackageAsFile(Deposit deposit) throws IOException { @@ -256,26 +261,26 @@ public class DepositManager if (!dir.exists() || !dir.isDirectory()) { throw new IOException( - "Directory does not exist for writing packages on ingest error."); + "Directory does not exist for writing packages on ingest error."); } String filenameBase = - "sword-" + deposit.getUsername() + "-" + (new Date()).getTime(); + "sword-" + deposit.getUsername() + "-" + (new Date()).getTime(); File packageFile = new File(path, filenameBase); File headersFile = new File(path, filenameBase + "-headers"); InputStream is = new BufferedInputStream( - new FileInputStream(deposit.getFile())); + new FileInputStream(deposit.getFile())); OutputStream fos = new BufferedOutputStream( - new FileOutputStream(packageFile)); + new FileOutputStream(packageFile)); Utils.copy(is, fos); fos.close(); is.close(); //write companion file with headers PrintWriter pw = new PrintWriter( - new BufferedWriter(new FileWriter(headersFile))); + new BufferedWriter(new FileWriter(headersFile))); pw.println("Content-Disposition=" + deposit.getContentDisposition()); pw.println("Content-Type=" + deposit.getContentType()); diff --git a/dspace-sword/src/main/java/org/dspace/sword/Depositor.java b/dspace-sword/src/main/java/org/dspace/sword/Depositor.java index 34cfa28a98..cf47281d25 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/Depositor.java +++ b/dspace-sword/src/main/java/org/dspace/sword/Depositor.java @@ -19,17 +19,19 @@ import org.purl.sword.base.SWORDErrorException; public abstract class Depositor { /** - * The sword service implementation + * The SWORD service implementation */ protected SWORDService swordService; /** - * Construct a new Depositor with the given sword service on the given + * Construct a new Depositor with the given SWORD service on the given * dspace object. It is anticipated that extensions of this class will * specialise in certain kinds of dspace object * * @param swordService + * SWORD service * @param dso + * DSpace object */ public Depositor(SWORDService swordService, DSpaceObject dso) { @@ -37,11 +39,14 @@ public abstract class Depositor } /** - * Execute the deposit process with the given sword deposit. + * Execute the deposit process with the given SWORD deposit. * * @param deposit - * @throws SWORDErrorException + * deposit request + * @return deposit result + * @throws SWORDErrorException on generic SWORD exception * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public abstract DepositResult doDeposit(Deposit deposit) throws SWORDErrorException, DSpaceSWORDException; @@ -50,7 +55,9 @@ public abstract class Depositor * Undo any changes to the archive effected by the deposit * * @param result + * deposit result * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public abstract void undoDeposit(DepositResult result) throws DSpaceSWORDException; diff --git a/dspace-sword/src/main/java/org/dspace/sword/MediaEntryManager.java b/dspace-sword/src/main/java/org/dspace/sword/MediaEntryManager.java index 426228aa5a..7faed279eb 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/MediaEntryManager.java +++ b/dspace-sword/src/main/java/org/dspace/sword/MediaEntryManager.java @@ -21,7 +21,7 @@ import org.dspace.content.Bitstream; */ public class MediaEntryManager { - /** sword service implementation */ + /** SWORD service implementation */ private SWORDService swordService; public MediaEntryManager(SWORDService swordService) @@ -35,8 +35,11 @@ public class MediaEntryManager * with DSpace custom URLs. * * @param url + * URL to check + * @return media entry for the given URL request * @throws DSpaceSWORDException - * @throws SWORDErrorException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public AtomDocumentResponse getMediaEntry(String url) throws DSpaceSWORDException, SWORDErrorException @@ -53,8 +56,8 @@ public class MediaEntryManager // FIXME: what do we actually do about this situation? // throwing an error for the time being throw new SWORDErrorException( - DSpaceSWORDErrorCodes.MEDIA_UNAVAILABLE, - "The media link you requested is not available"); + DSpaceSWORDErrorCodes.MEDIA_UNAVAILABLE, + "The media link you requested is not available"); } // extract the thing that we are trying to get a media entry on @@ -64,7 +67,7 @@ public class MediaEntryManager if (!(dso instanceof Bitstream)) { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "The url you provided does not resolve to an appropriate object"); + "The url you provided does not resolve to an appropriate object"); } // now construct the atom entry for the bitstream diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthentication.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthentication.java index 56c095dc58..3d2d3d02eb 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthentication.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthentication.java @@ -26,14 +26,17 @@ public class SWORDAuthentication * given DSpace Context? * * @param context + * The relevant DSpace Context. * @param un + * username * @param pw + * password * @return true if yes, false if not */ public boolean authenticates(Context context, String un, String pw) { - AuthenticationService authService = AuthenticateServiceFactory - .getInstance().getAuthenticationService(); + AuthenticationService authService = + AuthenticateServiceFactory.getInstance().getAuthenticationService(); int auth = authService.authenticate(context, un, pw, null, null); return auth == AuthenticationMethod.SUCCESS; } diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthenticator.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthenticator.java index 7207221781..b33b63c5ac 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthenticator.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDAuthenticator.java @@ -46,37 +46,40 @@ public class SWORDAuthenticator /** logger */ private static Logger log = Logger.getLogger(SWORDAuthenticator.class); - protected AuthenticationService authenticationService = AuthenticateServiceFactory - .getInstance().getAuthenticationService(); + protected AuthenticationService authenticationService = + AuthenticateServiceFactory.getInstance().getAuthenticationService(); - protected AuthorizeService authorizeService = AuthorizeServiceFactory - .getInstance().getAuthorizeService(); + protected AuthorizeService authorizeService = + AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected EPersonService ePersonService = EPersonServiceFactory - .getInstance().getEPersonService(); + protected EPersonService ePersonService = + EPersonServiceFactory.getInstance().getEPersonService(); - protected CommunityService communityService = ContentServiceFactory - .getInstance().getCommunityService(); + protected CommunityService communityService = + ContentServiceFactory.getInstance().getCommunityService(); - protected CollectionService collectionService = ContentServiceFactory - .getInstance().getCollectionService(); + protected CollectionService collectionService = + ContentServiceFactory.getInstance().getCollectionService(); - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); /** * Does the given username and password authenticate for the * given DSpace Context? * * @param context + * The relevant DSpace Context. * @param un + * username * @param pw + * password * @return true if yes, false if not */ public boolean authenticates(Context context, String un, String pw) { - int auth = authenticationService - .authenticate(context, un, pw, null, null); + int auth = authenticationService.authenticate( + context, un, pw, null, null); return auth == AuthenticationMethod.SUCCESS; } @@ -104,9 +107,11 @@ public class SWORDAuthenticator * appropriate authentication method. * * @param request - * @throws SWORDException - * @throws SWORDErrorException - * @throws SWORDAuthenticationException + * service document request + * @return authenticated SWORD context + * @throws SWORDException passed through. + * @throws SWORDErrorException on generic SWORD exception + * @throws SWORDAuthenticationException Thrown if the authentication fails */ public SWORDContext authenticate(ServiceDocumentRequest request) throws SWORDException, SWORDErrorException, @@ -135,9 +140,11 @@ public class SWORDAuthenticator * appropriate authentication method. * * @param request - * @throws SWORDException - * @throws SWORDErrorException - * @throws SWORDAuthenticationException + * ATOM document request + * @return a SWORDContext object containing the relevant users + * @throws SWORDException passed through. + * @throws SWORDErrorException on generic SWORD exception + * @throws SWORDAuthenticationException Thrown if the authentication fails */ public SWORDContext authenticate(AtomDocumentRequest request) throws SWORDException, SWORDErrorException, @@ -166,6 +173,7 @@ public class SWORDAuthenticator * authenticatate(username, password, onBehalfOf) * * @param request + * ATOM document request * @return a SWORDContext object containing the relevant users * @throws org.purl.sword.base.SWORDAuthenticationException * @throws SWORDException @@ -176,7 +184,7 @@ public class SWORDAuthenticator SWORDErrorException { return this.authenticate(context, request.getUsername(), - request.getPassword(), null, request.getIPAddress()); + request.getPassword(), null, request.getIPAddress()); } /** @@ -185,6 +193,8 @@ public class SWORDAuthenticator * authenticatate(username, password, onBehalfOf) * * @param request + * service document request + * @return a SWORDContext object containing the relevant users * @return a SWORDContext object containing the relevant users * @throws org.purl.sword.base.SWORDAuthenticationException * @throws SWORDException @@ -195,17 +205,19 @@ public class SWORDAuthenticator SWORDErrorException { return this.authenticate(context, request.getUsername(), - request.getPassword(), request.getOnBehalfOf(), - request.getIPAddress()); + request.getPassword(), request.getOnBehalfOf(), + request.getIPAddress()); } /** * Authenticate the deposit request. * * @param deposit - * @throws SWORDException - * @throws SWORDErrorException - * @throws SWORDAuthenticationException + * deposit request + * @return a SWORDContext object containing the relevant users + * @throws SWORDException passed through. + * @throws SWORDErrorException on generic SWORD exception + * @throws SWORDAuthenticationException Thrown if the authentication fails */ public SWORDContext authenticate(Deposit deposit) throws SWORDException, SWORDErrorException, @@ -234,8 +246,9 @@ public class SWORDAuthenticator * authenticate(username, password, onBehalfOf) * * @param deposit + * deposit request * @return a SWORDContext object containing the relevant users - * @throws SWORDAuthenticationException + * @throws SWORDAuthenticationException Thrown if the authentication fails * @throws SWORDException */ private SWORDContext authenticate(Context context, Deposit deposit) @@ -243,8 +256,8 @@ public class SWORDAuthenticator SWORDErrorException { return this.authenticate(context, deposit.getUsername(), - deposit.getPassword(), deposit.getOnBehalfOf(), - deposit.getIPAddress()); + deposit.getPassword(), deposit.getOnBehalfOf(), + deposit.getIPAddress()); } /** @@ -254,10 +267,13 @@ public class SWORDAuthenticator * must exist in the user database. * * @param un + * username * @param pw + * username * @param obo + * onBehalfOf user * @return a SWORD context holding the various user information - * @throws SWORDAuthenticationException + * @throws SWORDAuthenticationException Thrown if the authentication fails * @throws SWORDException */ private SWORDContext authenticate(Context context, String un, String pw, @@ -273,19 +289,19 @@ public class SWORDAuthenticator } // first find out if we support on-behalf-of deposit - boolean mediated = ConfigurationManager - .getBooleanProperty("sword-server", "on-behalf-of.enable"); + boolean mediated = ConfigurationManager.getBooleanProperty( + "sword-server", "on-behalf-of.enable"); if (!mediated && obo != null) { // user is trying to do a mediated deposit on a repository which does not support it log.error( - "Attempted mediated deposit on service not configured to do so"); + "Attempted mediated deposit on service not configured to do so"); throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, - "Mediated deposit to this service is not permitted"); + "Mediated deposit to this service is not permitted"); } log.info(LogManager.getHeader(context, "sword_authenticate", - "username=" + un + ",on_behalf_of=" + obo)); + "username=" + un + ",on_behalf_of=" + obo)); try { @@ -335,13 +351,13 @@ public class SWORDAuthenticator oboContext.setCurrentUser(epObo); // Set any special groups - invoke the authentication mgr. List groups = authenticationService - .getSpecialGroups(oboContext, null); + .getSpecialGroups(oboContext, null); for (Group group : groups) { oboContext.setSpecialGroup(group.getID()); log.debug( - "Adding Special Group id=" + group.getID()); + "Adding Special Group id=" + group.getID()); } sc.setContext(oboContext); } @@ -349,8 +365,8 @@ public class SWORDAuthenticator { authenticated = false; throw new SWORDErrorException( - ErrorCodes.TARGET_OWNER_UKNOWN, - "unable to identify on-behalf-of user: " + obo); + ErrorCodes.TARGET_OWNER_UKNOWN, + "unable to identify on-behalf-of user: " + obo); } } } @@ -360,21 +376,20 @@ public class SWORDAuthenticator // decide what kind of error to throw if (ep != null) { - log.info(LogManager - .getHeader(context, "sword_unable_to_set_user", - "username=" + un)); + log.info(LogManager.getHeader(context, + "sword_unable_to_set_user", "username=" + un)); throw new SWORDAuthenticationException( - "Unable to authenticate the supplied used"); + "Unable to authenticate the supplied used"); } else { // FIXME: this shouldn't ever happen now, but may as well leave it in just in case // there's a bug elsewhere log.info(LogManager.getHeader(context, - "sword_unable_to_set_on_behalf_of", - "username=" + un + ",on_behalf_of=" + obo)); + "sword_unable_to_set_on_behalf_of", + "username=" + un + ",on_behalf_of=" + obo)); throw new SWORDAuthenticationException( - "Unable to authenticate the onBehalfOf account"); + "Unable to authenticate the onBehalfOf account"); } } @@ -384,8 +399,8 @@ public class SWORDAuthenticator { log.error("caught exception: ", e); throw new SWORDException( - "There was a problem accessing the repository user database", - e); + "There was a problem accessing the repository user database", + e); } } @@ -396,8 +411,16 @@ public class SWORDAuthenticator * See javadocs for individual canSubmitTo methods to see the conditions * which are applied in each situation * + * @param swordService + * SWORD service + * @param deposit + * unused + * @param dso + * target DSpace object * @return true if yes, false if not * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public boolean canSubmit(SWORDService swordService, Deposit deposit, DSpaceObject dso) @@ -415,8 +438,8 @@ public class SWORDAuthenticator } else { - swordService - .message("User is not authorised to submit to collection"); + swordService.message( + "User is not authorised to submit to collection"); } return submit; @@ -428,8 +451,10 @@ public class SWORDAuthenticator * of the special DSpace group Administrator, with id 1 * * @param swordContext + * The relevant SWORD Context. * @return true if administrator, false if not - * @throws SQLException + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isUserAdmin(SWORDContext swordContext) throws DSpaceSWORDException @@ -437,8 +462,8 @@ public class SWORDAuthenticator try { EPerson authenticated = swordContext.getAuthenticated(); - return authenticated != null && authorizeService - .isAdmin(swordContext.getAuthenticatorContext()); + return authenticated != null && authorizeService.isAdmin( + swordContext.getAuthenticatorContext()); } catch (SQLException e) { @@ -453,8 +478,10 @@ public class SWORDAuthenticator * of the special DSpace group Administrator, with id 1 * * @param swordContext + * The relevant SWORD Context. * @return true if administrator, false if not - * @throws SQLException + * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isOnBehalfOfAdmin(SWORDContext swordContext) throws DSpaceSWORDException @@ -462,8 +489,8 @@ public class SWORDAuthenticator EPerson onBehalfOf = swordContext.getOnBehalfOf(); try { - return onBehalfOf != null && authorizeService - .isAdmin(swordContext.getOnBehalfOfContext()); + return onBehalfOf != null && authorizeService.isAdmin( + swordContext.getOnBehalfOfContext()); } catch (SQLException e) { @@ -476,7 +503,10 @@ public class SWORDAuthenticator * Is the authenticated user a member of the given group * or one of its sub groups? * - * @param group + * @param swordContext + * The relevant SWORD Context. + * @param group group to search recursively + * @return true if the authenticated user is a member of group or its subgroups */ public boolean isUserInGroup(SWORDContext swordContext, Group group) { @@ -488,7 +518,10 @@ public class SWORDAuthenticator * Is the onBehalfOf user a member of the given group or * one of its sub groups? * - * @param group + * @param swordContext + * The relevant SWORD Context. + * @param group group to search recursively + * @return true if the onBehalfOf user is a member of group or its subgroups */ public boolean isOnBehalfOfInGroup(SWORDContext swordContext, Group group) { @@ -502,8 +535,8 @@ public class SWORDAuthenticator * until it has exhausted the tree of groups or finds the given * eperson * - * @param group - * @param eperson + * @param group group to search recursively + * @param eperson EPerson to find * @return true if in group, false if not */ public boolean isInGroup(Group group, EPerson eperson) @@ -546,17 +579,19 @@ public class SWORDAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to READ * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. * @return the array of allowed collections * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedCommunities(SWORDContext swordContext) throws DSpaceSWORDException @@ -593,8 +628,8 @@ public class SWORDAuthenticator if (!authAllowed) { authAllowed = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), comm, - Constants.READ); + swordContext.getAuthenticatorContext(), comm, + Constants.READ); } // if we have not already determined that the obo user is ok to submit, look up the READ policy on the @@ -602,8 +637,8 @@ public class SWORDAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), comm, - Constants.READ); + swordContext.getOnBehalfOfContext(), comm, + Constants.READ); } // final check to see if we are allowed to READ @@ -631,17 +666,21 @@ public class SWORDAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to READ * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * + * @param swordContext + * The relevant SWORD Context. * @param community + * target community * @return the array of allowed collections * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getCommunities(SWORDContext swordContext, Community community) @@ -678,8 +717,8 @@ public class SWORDAuthenticator if (!authAllowed) { authAllowed = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), comm, - Constants.READ); + swordContext.getAuthenticatorContext(), comm, + Constants.READ); } // if we have not already determined that the obo user is ok to submit, look up the READ policy on the @@ -687,8 +726,8 @@ public class SWORDAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), comm, - Constants.READ); + swordContext.getOnBehalfOfContext(), comm, + Constants.READ); } // final check to see if we are allowed to READ @@ -718,8 +757,10 @@ public class SWORDAuthenticator * See that method for details of the conditions applied * * @param swordContext + * The relevant SWORD Context. * @return the array of allowed collections * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedCollections( SWORDContext swordContext) @@ -735,17 +776,21 @@ public class SWORDAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to ADD * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. + * @param community + * target community * @return the array of allowed collections * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedCollections( SWORDContext swordContext, Community community) @@ -768,8 +813,8 @@ public class SWORDAuthenticator Context authContext = swordContext.getAuthenticatorContext(); // short cut by obtaining the collections to which the authenticated user can submit - List cols = collectionService - .findAuthorized(authContext, community, Constants.ADD); + List cols = collectionService.findAuthorized( + authContext, community, Constants.ADD); List allowed = new ArrayList<>(); // now find out if the obo user is allowed to submit to any of these collections @@ -788,8 +833,8 @@ public class SWORDAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), col, - Constants.ADD); + swordContext.getOnBehalfOfContext(), col, + Constants.ADD); } // final check to see if we are allowed to READ @@ -815,17 +860,21 @@ public class SWORDAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. + * @param collection + * target collection * @return the array of allowed collections * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedItems(SWORDContext swordContext, org.dspace.content.Collection collection) @@ -845,8 +894,8 @@ public class SWORDAuthenticator try { List allowed = new ArrayList<>(); - Iterator ii = itemService - .findByCollection(swordContext.getContext(), collection); + Iterator ii = itemService.findByCollection( + swordContext.getContext(), collection); while (ii.hasNext()) { @@ -869,8 +918,8 @@ public class SWORDAuthenticator if (!authAllowed) { boolean write = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), item, - Constants.WRITE); + swordContext.getAuthenticatorContext(), item, + Constants.WRITE); boolean add = false; for (Bundle bundle : bundles) @@ -879,8 +928,8 @@ public class SWORDAuthenticator .equals(bundle.getName())) { add = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), - bundle, Constants.ADD); + swordContext.getAuthenticatorContext(), + bundle, Constants.ADD); if (!add) { break; @@ -903,10 +952,10 @@ public class SWORDAuthenticator for (Bundle bundle : bundles) { if (Constants.CONTENT_BUNDLE_NAME - .equals(bundle.getName())) + .equals(bundle.getName())) add = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), bundle, - Constants.ADD); + swordContext.getOnBehalfOfContext(), bundle, + Constants.ADD); if (!add) { break; @@ -938,17 +987,21 @@ public class SWORDAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to ADD * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. * @param collection + * target collection + * @return true if collection permits submission by current context * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean canSubmitTo(SWORDContext swordContext, org.dspace.content.Collection collection) @@ -981,8 +1034,8 @@ public class SWORDAuthenticator if (!authAllowed) { authAllowed = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), collection, - Constants.ADD); + swordContext.getAuthenticatorContext(), collection, + Constants.ADD); } // if we have not already determined that the obo user is ok to submit, look up the READ policy on the @@ -990,8 +1043,8 @@ public class SWORDAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), collection, - Constants.ADD); + swordContext.getOnBehalfOfContext(), collection, + Constants.ADD); } // final check to see if we are allowed to READ @@ -1013,17 +1066,21 @@ public class SWORDAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. + * @param item + * target item * @return the array of allowed collections * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean canSubmitTo(SWORDContext swordContext, Item item) throws DSpaceSWORDException @@ -1058,8 +1115,8 @@ public class SWORDAuthenticator if (!authAllowed) { boolean write = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), item, - Constants.WRITE); + swordContext.getAuthenticatorContext(), item, + Constants.WRITE); boolean add = false; for (Bundle bundle : bundles) @@ -1067,8 +1124,8 @@ public class SWORDAuthenticator if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName())) { add = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), bundle, - Constants.ADD); + swordContext.getAuthenticatorContext(), bundle, + Constants.ADD); if (!add) { break; @@ -1093,8 +1150,8 @@ public class SWORDAuthenticator if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName())) { add = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), bundle, - Constants.ADD); + swordContext.getOnBehalfOfContext(), bundle, + Constants.ADD); if (!add) { break; @@ -1117,22 +1174,26 @@ public class SWORDAuthenticator } /** - * Can the given context submit to the specified dspace object. + * Can the given context submit to the specified DSpace object. * * This forwards to the individual methods for different object types; see * their documentation for details of the conditions. * * @param context + * The relevant DSpace Context. * @param dso + * target DSpace object + * @return true if the given context can submit to the specified DSpace object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean canSubmitTo(SWORDContext context, DSpaceObject dso) throws DSpaceSWORDException { if (dso instanceof org.dspace.content.Collection) { - return this - .canSubmitTo(context, (org.dspace.content.Collection) dso); + return this.canSubmitTo( + context, (org.dspace.content.Collection) dso); } else { diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDConfiguration.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDConfiguration.java index 3935a9115b..1616855bbd 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDConfiguration.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDConfiguration.java @@ -29,13 +29,13 @@ import org.apache.log4j.Logger; /** * @author Richard Jones * - * Class to represent the principal configurations of the sword + * Class to represent the principal configurations of the SWORD * service being offered. Not all configuration is available through * this class, but the most useful common options, and those with * default values are available * - * Note that changes to values via the api will not be persisted - * between sword requests. + * Note that changes to values via the API will not be persisted + * between SWORD requests. * * For detailed descriptions of configuration values, see the sword * configuration documentation @@ -48,10 +48,10 @@ public class SWORDConfiguration public static final Logger log = Logger.getLogger(SWORDConfiguration.class); protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory - .getInstance().getBitstreamFormatService(); + .getInstance().getBitstreamFormatService(); protected ConfigurationService configurationService = DSpaceServicesFactory - .getInstance().getConfigurationService(); + .getInstance().getConfigurationService(); /** whether we can support noOp */ private boolean noOp = true; @@ -87,24 +87,24 @@ public class SWORDConfiguration public SWORDConfiguration() { // set the max upload size - int mus = configurationService - .getIntProperty("sword-server.max-upload-size"); + int mus = configurationService.getIntProperty( + "sword-server.max-upload-size"); if (mus > 0) { this.maxUploadSize = mus; } // set the mediation value - this.mediated = configurationService - .getBooleanProperty("sword-server.on-behalf-of.enable"); + this.mediated = configurationService.getBooleanProperty( + "sword-server.on-behalf-of.enable"); // find out if we keep the original as bitstream - this.keepOriginal = configurationService - .getBooleanProperty("sword-server.keep-original-package"); + this.keepOriginal = configurationService.getBooleanProperty( + "sword-server.keep-original-package"); // get the sword bundle - String bundle = configurationService - .getProperty("sword-server.bundle.name"); + String bundle = configurationService.getProperty( + "sword-server.bundle.name"); if (bundle != null && "".equals(bundle)) { this.swordBundle = bundle; @@ -112,12 +112,11 @@ public class SWORDConfiguration // find out if we keep the package as a file in specified directory this.keepPackageOnFailedIngest = configurationService - .getBooleanProperty("sword-server.keep-package-on-fail", - false); + .getBooleanProperty("sword-server.keep-package-on-fail", false); // get directory path and name - this.failedPackageDir = configurationService - .getProperty("sword-server.failed-package.dir"); + this.failedPackageDir = configurationService.getProperty( + "sword-server.failed-package.dir"); // Get the accepted formats String[] acceptsFormats = configurationService @@ -136,6 +135,8 @@ public class SWORDConfiguration /** * Get the bundle name that SWORD will store its original deposit * packages in, when storing them inside an item. + * + * @return bundle name where to store the original deposit packages */ public String getSwordBundle() { @@ -143,9 +144,11 @@ public class SWORDConfiguration } /** - * Set the bundle name that sword will store its original deposit + * Set the bundle name that SWORD will store its original deposit * packages in, when storing them inside an item. - * @param swordBundle + * + * @param swordBundle set bundle name where to store the original + * deposit packages */ public void setSwordBundle(String swordBundle) { @@ -154,6 +157,8 @@ public class SWORDConfiguration /** * Is this a no-op deposit? + * + * @return true if this is a no-op deposit */ public boolean isNoOp() { @@ -163,7 +168,7 @@ public class SWORDConfiguration /** * Set whether this is a no-op deposit. * - * @param noOp + * @param noOp sets whether this is a no-op deposit */ public void setNoOp(boolean noOp) { @@ -172,6 +177,8 @@ public class SWORDConfiguration /** * Is this a verbose deposit? + * + * @return true if is verbose deposit */ public boolean isVerbose() { @@ -180,7 +187,8 @@ public class SWORDConfiguration /** * Set whether this is a verbose deposit. - * @param verbose + * + * @param verbose is verbose deposit? */ public void setVerbose(boolean verbose) { @@ -188,7 +196,9 @@ public class SWORDConfiguration } /** - * What is the max upload size (in bytes) for the sword interface? + * What is the max upload size (in bytes) for the SWORD interface? + * + * @return maximum upload size */ public int getMaxUploadSize() { @@ -196,8 +206,9 @@ public class SWORDConfiguration } /** - * set the max uplaod size (in bytes) for the sword interface - * @param maxUploadSize + * set the max upload size (in bytes) for the SWORD interface + * + * @param maxUploadSize maximum upload size to set */ public void setMaxUploadSize(int maxUploadSize) { @@ -206,6 +217,8 @@ public class SWORDConfiguration /** * Does the server support mediated deposit (aka on-behalf-of)? + * + * @return true if server supports mediated deposit */ public boolean isMediated() { @@ -214,7 +227,8 @@ public class SWORDConfiguration /** * Set whether the server supports mediated deposit (aka on-behalf-of). - * @param mediated + * + * @param mediated set whether server supports mediated deposit */ public void setMediated(boolean mediated) { @@ -223,6 +237,8 @@ public class SWORDConfiguration /** * Should the repository keep the original package? + * + * @return true if repository keeps copies of original package */ public boolean isKeepOriginal() { @@ -231,7 +247,8 @@ public class SWORDConfiguration /** * Set whether the repository should keep copies of the original package. - * @param keepOriginal + * + * @param keepOriginal set whether to keep copies of original package */ public void setKeepOriginal(boolean keepOriginal) { @@ -240,7 +257,9 @@ public class SWORDConfiguration /** * set whether the repository should write file of the original package if ingest fails - * @param keepOriginalOnFail + * + * @param keepOriginalOnFail set whether to keep copies of original + * package if ingest fails */ public void setKeepPackageOnFailedIngest(boolean keepOriginalOnFail) { @@ -249,7 +268,9 @@ public class SWORDConfiguration /** * should the repository write file of the original package if ingest fails - * @return keepPackageOnFailedIngest + * + * @return true if repository keeps copies of original package if ingest + * fails */ public boolean isKeepPackageOnFailedIngest() { @@ -258,7 +279,8 @@ public class SWORDConfiguration /** * set the directory to write file of the original package - * @param dir + * + * @param dir directory where original package is kept */ public void setFailedPackageDir(String dir) { @@ -268,7 +290,8 @@ public class SWORDConfiguration /** * directory location of the files with original packages * for failed ingests - * @return failedPackageDir + * + * @return dir directory where original package is kept */ public String getFailedPackageDir() { @@ -276,12 +299,17 @@ public class SWORDConfiguration } /** - * Get the list of mime types that the given dspace object will + * Get the list of MIME types that the given DSpace object will * accept as packages. * * @param context + * The relevant DSpace Context. * @param dso + * target DSpace object + * @return the list of MIME types that the given DSpace object will + * accept as packages. * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAccepts(Context context, DSpaceObject dso) throws DSpaceSWORDException @@ -315,10 +343,11 @@ public class SWORDConfiguration } /** - * Get the list of mime types that a Collection will accept as packages + * Get the list of MIME types that a Collection will accept as packages * - * @return the list of mime types + * @return the list of MIME types * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getCollectionAccepts() throws DSpaceSWORDException { @@ -343,6 +372,9 @@ public class SWORDConfiguration * how much the server "likes" this packaging type * * @param col + * target collection + * @return map of packaging URIs to Q values for the packaging types which + * the given collection will accept. */ public Map getAcceptPackaging(Collection col) { @@ -407,9 +439,14 @@ public class SWORDConfiguration * object? * * @param mediaType + * packaging/media type to check * @param dso + * target DSpace object + * @return true if the given packaging/media type is supported by the + * given DSpace object * @throws DSpaceSWORDException - * @throws SWORDErrorException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public boolean isSupportedMediaType(String mediaType, DSpaceObject dso) throws DSpaceSWORDException, SWORDErrorException @@ -441,10 +478,17 @@ public class SWORDConfiguration /** * Is the given content MIME type acceptable to the given DSpace object? + * * @param context + * The relevant DSpace Context. * @param type + * MIME type to check * @param dso + * target DSpace object + * @return true if the given content MIME type is acceptable + * to the given DSpace object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isAcceptableContentType(Context context, String type, DSpaceObject dso) @@ -457,14 +501,15 @@ public class SWORDConfiguration /** * Get the temp directory for storing files during deposit. * + * @return temp directory for storing files during deposit * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getTempDir() throws DSpaceSWORDException { return (configurationService.getProperty("upload.temp.dir") != null) - ? - configurationService.getProperty("upload.temp.dir") : - System.getProperty("java.io.tmpdir"); + ? configurationService.getProperty("upload.temp.dir") + : System.getProperty("java.io.tmpdir"); } } diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDContext.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDContext.java index 003055eadf..2c167e37b6 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDContext.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDContext.java @@ -85,6 +85,8 @@ public class SWORDContext * Returns the most appropriate context for operations on the * database. This is the on-behalf-of user's context if the * user exists, or the authenticated user's context otherwise. + * + * @return appropriate DSpace context */ public Context getContext() { @@ -104,6 +106,8 @@ public class SWORDContext * getContext() * * on this class instead. + * + * @return DSpace context of the user who authenticated */ public Context getAuthenticatorContext() { @@ -123,6 +127,8 @@ public class SWORDContext * * on this class instead. If there is no on-behalf-of user, this * method will return null. + * + * @return DSpace context of the on-behalf-of user */ public Context getOnBehalfOfContext() { @@ -157,9 +163,9 @@ public class SWORDContext * user's context if it is different. This ensures that only changes written * through the appropriate user's context is persisted, and all other * operations are flushed. You should, in general, not try to commit the contexts directly - * when using the sword api. + * when using the SWORD API. * - * @throws DSpaceSWORDException + * @throws DSpaceSWORDException on database error. */ public void commit() throws DSpaceSWORDException diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDIngester.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDIngester.java index 79d36c4e36..212e02d3f5 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDIngester.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDIngester.java @@ -26,9 +26,16 @@ public interface SWORDIngester * Ingest the package as described in the given Deposit object * within the given DSpace Context * + * @param service + * SWORD service * @param deposit + * deposit request + * @param target + * target DSpace object * @return the result of the deposit * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject target) diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDIngesterFactory.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDIngesterFactory.java index f4c3dd1f14..a2d8ecdba8 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDIngesterFactory.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDIngesterFactory.java @@ -34,12 +34,19 @@ public class SWORDIngesterFactory * of the interface to return. * * To configure how this method will respond, configure the package ingester - * for the appropriate media types and defaults. See the sword configuration + * for the appropriate media types and defaults. See the SWORD configuration * documentation for more details. * * @param context + * The relevant DSpace Context. * @param deposit + * deposit request + * @param dso + * target DSpace object + * @return SWORD ingester implementation * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public static SWORDIngester getInstance(Context context, Deposit deposit, DSpaceObject dso) @@ -50,27 +57,27 @@ public class SWORDIngesterFactory if (dso instanceof Collection) { SWORDIngester ingester = (SWORDIngester) pluginService - .getNamedPlugin(SWORDIngester.class, deposit.getPackaging()); + .getNamedPlugin(SWORDIngester.class, deposit.getPackaging()); if (ingester == null) { throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT, - "No ingester configured for this package type"); + "No ingester configured for this package type"); } return ingester; } else if (dso instanceof Item) { SWORDIngester ingester = (SWORDIngester) pluginService - .getNamedPlugin(SWORDIngester.class, "SimpleFileIngester"); + .getNamedPlugin(SWORDIngester.class, "SimpleFileIngester"); if (ingester == null) { throw new DSpaceSWORDException( - "SimpleFileIngester is not configured in plugin manager"); + "SimpleFileIngester is not configured in plugin manager"); } return ingester; } throw new DSpaceSWORDException( - "No ingester could be found which works for this DSpace Object"); + "No ingester could be found which works for this DSpace Object"); } } diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDService.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDService.java index a57903b706..daf7acc306 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDService.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDService.java @@ -25,11 +25,11 @@ import org.purl.sword.base.Deposit; * @author Richard Jones * * This class represents the actual sword service provided by dspace. It - * is the central location for the authentcated contexts, the installation - * specific configuration, and the url management. + * is the central location for the authenticated contexts, the installation + * specific configuration, and the URL management. * - * It is ubiquotous in the sword implementation, and all related - * information and services should be retrived via this api + * It is ubiquitous in the sword implementation, and all related + * information and services should be retrieved via this API. * */ public class SWORDService @@ -60,9 +60,10 @@ public class SWORDService /** * Construct a new service instance around the given authenticated - * sword context + * SWORD context * * @param sc + * authenticated SWORD context */ public SWORDService(SWORDContext sc) { @@ -130,6 +131,7 @@ public class SWORDService * looking code up * * @param message + * message to register with the verboseDescription member variable */ public void message(String message) { @@ -150,9 +152,13 @@ public class SWORDService * Construct the most appropriate filename for the incoming deposit. * * @param context + * The relevant DSpace Context. * @param deposit + * deposit request * @param original - * @throws DSpaceSWORDException + * is original? + * @return the most appropriate filename for the incoming deposit + * @throws DSpaceSWORDException on database error. */ public String getFilename(Context context, Deposit deposit, boolean original) @@ -160,8 +166,8 @@ public class SWORDService { try { - BitstreamFormat bf = bitstreamFormatService - .findByMIMEType(context, deposit.getContentType()); + BitstreamFormat bf = bitstreamFormatService.findByMIMEType( + context, deposit.getContentType()); List exts = null; if (bf != null) { @@ -193,6 +199,8 @@ public class SWORDService /** * Get the name of the temp files that should be used. + * + * @return the name of the temp file that should be used */ public String getTempFilename() { diff --git a/dspace-sword/src/main/java/org/dspace/sword/SWORDUrlManager.java b/dspace-sword/src/main/java/org/dspace/sword/SWORDUrlManager.java index 2eed3f55b5..c3f1861cb1 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SWORDUrlManager.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SWORDUrlManager.java @@ -30,17 +30,17 @@ import java.util.List; */ public class SWORDUrlManager { - /** the sword configuration */ + /** the SWORD configuration */ private SWORDConfiguration config; - /** the active dspace context */ + /** the active DSpace context */ private Context context; - protected HandleService handleService = HandleServiceFactory.getInstance() - .getHandleService(); + protected HandleService handleService = + HandleServiceFactory.getInstance().getHandleService(); - protected BitstreamService bitstreamService = ContentServiceFactory - .getInstance().getBitstreamService(); + protected BitstreamService bitstreamService = + ContentServiceFactory.getInstance().getBitstreamService(); public SWORDUrlManager(SWORDConfiguration config, Context context) { @@ -51,11 +51,13 @@ public class SWORDUrlManager /** * Get the generator URL for ATOM entry documents. This can be * overridden from the default in configuration. + * + * @return the generator URL for ATOM entry documents */ public String getGeneratorUrl() { - String cfg = ConfigurationManager - .getProperty("sword-server", "generator.url"); + String cfg = ConfigurationManager.getProperty( + "sword-server", "generator.url"); if (cfg == null || "".equals(cfg)) { return SWORDProperties.SOFTWARE_URI; @@ -69,8 +71,10 @@ public class SWORDUrlManager * unless configuration changes are made to DSpace * * @param collection + * the collection to query * @return The Deposit URL * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getDepositLocation(Collection collection) throws DSpaceSWORDException @@ -84,8 +88,10 @@ public class SWORDUrlManager * unless configuration changes are made to DSpace * * @param item + * the item to query * @return The Deposit URL * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getDepositLocation(Item item) throws DSpaceSWORDException @@ -99,8 +105,10 @@ public class SWORDUrlManager * unless configuration changes are made to DSpace * * @param community + * the community to query * @return The Deposit URL * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getDepositLocation(Community community) throws DSpaceSWORDException @@ -118,6 +126,8 @@ public class SWORDUrlManager * @param location the URL to resolve to a collection * @return The collection to which the url resolves * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ // FIXME: we need to generalise this to DSpaceObjects, so that we can support // Communities, Collections and Items separately @@ -130,7 +140,7 @@ public class SWORDUrlManager if (baseUrl.length() == location.length()) { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "The deposit URL is incomplete"); + "The deposit URL is incomplete"); } String handle = location.substring(baseUrl.length()); if (handle.startsWith("/")) @@ -140,7 +150,7 @@ public class SWORDUrlManager if ("".equals(handle)) { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "The deposit URL is incomplete"); + "The deposit URL is incomplete"); } DSpaceObject dso = handleService.resolveToObject(context, handle); @@ -148,7 +158,7 @@ public class SWORDUrlManager if (!(dso instanceof Collection)) { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "The deposit URL does not resolve to a valid collection"); + "The deposit URL does not resolve to a valid collection"); } return (Collection) dso; @@ -157,7 +167,7 @@ public class SWORDUrlManager { // log.error("Caught exception:", e); throw new DSpaceSWORDException( - "There was a problem resolving the collection", e); + "There was a problem resolving the collection", e); } } @@ -169,6 +179,8 @@ public class SWORDUrlManager * @param location the URL to resolve to a collection * @return The collection to which the url resolves * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public DSpaceObject getDSpaceObject(Context context, String location) throws DSpaceSWORDException, SWORDErrorException @@ -179,7 +191,7 @@ public class SWORDUrlManager if (baseUrl.length() == location.length()) { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "The deposit URL is incomplete"); + "The deposit URL is incomplete"); } String handle = location.substring(baseUrl.length()); if (handle.startsWith("/")) @@ -189,7 +201,7 @@ public class SWORDUrlManager if ("".equals(handle)) { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "The deposit URL is incomplete"); + "The deposit URL is incomplete"); } DSpaceObject dso = handleService.resolveToObject(context, handle); @@ -197,7 +209,7 @@ public class SWORDUrlManager if (!(dso instanceof Collection) && !(dso instanceof Item)) { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "The deposit URL does not resolve to a valid deposit target"); + "The deposit URL does not resolve to a valid deposit target"); } return dso; @@ -206,7 +218,7 @@ public class SWORDUrlManager { // log.error("Caught exception:", e); throw new DSpaceSWORDException( - "There was a problem resolving the collection", e); + "There was a problem resolving the collection", e); } } @@ -216,7 +228,10 @@ public class SWORDUrlManager * entries. * * @param community + * target community + * @return service document URL for the given object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String constructSubServiceUrl(Community community) throws DSpaceSWORDException @@ -232,7 +247,10 @@ public class SWORDUrlManager * entries. * * @param collection + * target collection + * @return service document URL for the given object * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String constructSubServiceUrl(Collection collection) throws DSpaceSWORDException @@ -246,9 +264,13 @@ public class SWORDUrlManager * Extract a DSpaceObject from the given URL. If this method is unable to * locate a meaningful and appropriate DSpace object it will throw the * appropriate SWORD error. + * * @param url + * URL to get DSpace object from + * @return DSpace object corresponding to given URL * @throws DSpaceSWORDException - * @throws SWORDErrorException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public DSpaceObject extractDSpaceObject(String url) throws DSpaceSWORDException, SWORDErrorException @@ -281,7 +303,7 @@ public class SWORDUrlManager else { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "Service Document request does not refer to a DSpace Collection or Community"); + "Service Document request does not refer to a DSpace Collection or Community"); } } else if (url.startsWith(mlBase)) @@ -304,8 +326,8 @@ public class SWORDUrlManager else { throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, - "Unable to recognise URL as a valid service document: " + - url); + "Unable to recognise URL as a valid service document: " + + url); } } catch (SQLException e) @@ -317,22 +339,24 @@ public class SWORDUrlManager /** * Get the base URL for service document requests. * + * @return the base URL for service document requests * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getBaseServiceDocumentUrl() throws DSpaceSWORDException { - String depositUrl = ConfigurationManager - .getProperty("sword-server", "servicedocument.url"); + String depositUrl = ConfigurationManager.getProperty( + "sword-server", "servicedocument.url"); if (depositUrl == null || "".equals(depositUrl)) { - String dspaceUrl = ConfigurationManager - .getProperty("dspace.baseUrl"); + String dspaceUrl = ConfigurationManager.getProperty( + "dspace.baseUrl"); if (dspaceUrl == null || "".equals(dspaceUrl)) { throw new DSpaceSWORDException( - "Unable to construct service document urls, due to missing/invalid " + - "config in sword.servicedocument.url and/or dspace.baseUrl"); + "Unable to construct service document urls, due to missing/invalid " + + "config in sword.servicedocument.url and/or dspace.baseUrl"); } try @@ -344,8 +368,8 @@ public class SWORDUrlManager catch (MalformedURLException e) { throw new DSpaceSWORDException( - "Unable to construct service document urls, due to invalid dspace.baseUrl " + - e.getMessage(), e); + "Unable to construct service document urls, due to invalid dspace.baseUrl " + + e.getMessage(), e); } } @@ -365,36 +389,37 @@ public class SWORDUrlManager * * where dspace.baseUrl is also in the configuration file. * - * @return the base URL for sword deposit + * @return the base URL for SWORD deposit * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getBaseDepositUrl() throws DSpaceSWORDException { - String depositUrl = ConfigurationManager - .getProperty("sword-server", "deposit.url"); + String depositUrl = ConfigurationManager.getProperty( + "sword-server", "deposit.url"); if (depositUrl == null || "".equals(depositUrl)) { - String dspaceUrl = ConfigurationManager - .getProperty("dspace.baseUrl"); + String dspaceUrl = ConfigurationManager.getProperty( + "dspace.baseUrl"); if (dspaceUrl == null || "".equals(dspaceUrl)) { throw new DSpaceSWORDException( - "Unable to construct deposit urls, due to missing/invalid config in " + - "sword.deposit.url and/or dspace.baseUrl"); + "Unable to construct deposit urls, due to missing/invalid config in " + + "sword.deposit.url and/or dspace.baseUrl"); } try { URL url = new URL(dspaceUrl); depositUrl = new URL(url.getProtocol(), url.getHost(), - url.getPort(), "/sword/deposit").toString(); + url.getPort(), "/sword/deposit").toString(); } catch (MalformedURLException e) { throw new DSpaceSWORDException( - "Unable to construct deposit urls, due to invalid dspace.baseUrl " + - e.getMessage(), e); + "Unable to construct deposit urls, due to invalid dspace.baseUrl " + + e.getMessage(), e); } } @@ -405,7 +430,10 @@ public class SWORDUrlManager * Is the given URL the base service document URL? * * @param url + * URL to check + * @return true if the given URL the base service document URL * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isBaseServiceDocumentUrl(String url) throws DSpaceSWORDException @@ -417,7 +445,9 @@ public class SWORDUrlManager * Is the given URL the base media link URL? * * @param url - * @throws DSpaceSWORDException + * URL to check + * @return true if the given URL the base media link URL + * @throws DSpaceSWORDException passed through. */ public boolean isBaseMediaLinkUrl(String url) throws DSpaceSWORDException @@ -430,7 +460,10 @@ public class SWORDUrlManager * There is no place in the main DSpace code base for doing this. * * @param bitstream + * target bitstream + * @return a URL to the given Bitstream. * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getBitstreamUrl(Bitstream bitstream) throws DSpaceSWORDException @@ -446,7 +479,7 @@ public class SWORDUrlManager else { throw new DSpaceSWORDException( - "Encountered orphaned bitstream"); + "Encountered orphaned bitstream"); } List items = parent.getItems(); @@ -482,37 +515,42 @@ public class SWORDUrlManager } /** - * Get the base media link url. + * Get the base media link URL. It can be configured using + * {@code sword-server.media-link.url}. If not configured, it will be + * calculated using {@code dspace.baseUrl} and the constant path + * {@code /sword/media-link}. * + * @return that URL. * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getBaseMediaLinkUrl() throws DSpaceSWORDException { - String mlUrl = ConfigurationManager - .getProperty("sword-server", "media-link.url"); + String mlUrl = ConfigurationManager.getProperty( + "sword-server", "media-link.url"); if (StringUtils.isBlank(mlUrl)) { - String dspaceUrl = ConfigurationManager - .getProperty("dspace.baseUrl"); + String dspaceUrl = ConfigurationManager.getProperty( + "dspace.baseUrl"); if (dspaceUrl == null || "".equals(dspaceUrl)) { throw new DSpaceSWORDException( - "Unable to construct media-link urls, due to missing/invalid config in " + - "media-link.url and/or dspace.baseUrl"); + "Unable to construct media-link urls, due to missing/invalid config in " + + "media-link.url and/or dspace.baseUrl"); } try { URL url = new URL(dspaceUrl); mlUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), - "/sword/media-link").toString(); + "/sword/media-link").toString(); } catch (MalformedURLException e) { throw new DSpaceSWORDException( - "Unable to construct media-link urls, due to invalid dspace.baseUrl " + - e.getMessage(), e); + "Unable to construct media-link urls, due to invalid dspace.baseUrl " + + e.getMessage(), e); } } @@ -520,11 +558,13 @@ public class SWORDUrlManager } /** - * get the media link url for the given item + * get the media link URL for the given item * * @param dso - * @return + * target DSpace object + * @return media link URL for the given item * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ private String getMediaLink(Item dso) throws DSpaceSWORDException @@ -542,7 +582,10 @@ public class SWORDUrlManager * Get the media link URL for the given bitstream. * * @param bitstream + * target bitstream + * @return media link URL for the given bitstream * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getMediaLink(Bitstream bitstream) throws DSpaceSWORDException @@ -558,7 +601,7 @@ public class SWORDUrlManager else { throw new DSpaceSWORDException( - "Encountered orphaned bitstream"); + "Encountered orphaned bitstream"); } List items = parent.getItems(); diff --git a/dspace-sword/src/main/java/org/dspace/sword/ServiceDocumentManager.java b/dspace-sword/src/main/java/org/dspace/sword/ServiceDocumentManager.java index d06564c05f..187f53f86c 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/ServiceDocumentManager.java +++ b/dspace-sword/src/main/java/org/dspace/sword/ServiceDocumentManager.java @@ -49,6 +49,8 @@ public class ServiceDocumentManager * * @return The service document based on the context of the request * @throws DSpaceSWORDException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public ServiceDocument getServiceDocument() throws DSpaceSWORDException, SWORDErrorException @@ -78,13 +80,13 @@ public class ServiceDocumentManager if (context == null) { throw new DSpaceSWORDException( - "The Context is null; please set it before calling getServiceDocument"); + "The Context is null; please set it before calling getServiceDocument"); } if (swordContext == null) { throw new DSpaceSWORDException( - "The SWORD Context is null; please set it before calling getServiceDocument"); + "The SWORD Context is null; please set it before calling getServiceDocument"); } // construct a new service document @@ -108,13 +110,13 @@ public class ServiceDocumentManager workspace.setTitle(ws); // next thing to do is determine whether the default is communities or collections - boolean swordCommunities = ConfigurationManager - .getBooleanProperty("sword-server", "expose-communities"); + boolean swordCommunities = ConfigurationManager.getBooleanProperty( + "sword-server", "expose-communities"); if (swordCommunities) { - List comms = swordAuth - .getAllowedCommunities(swordContext); + List comms = swordAuth.getAllowedCommunities( + swordContext); for (Community comm : comms) { org.purl.sword.base.Collection scol = comGen @@ -198,8 +200,8 @@ public class ServiceDocumentManager */ private void addGenerator(Service service) { - boolean identify = ConfigurationManager - .getBooleanProperty("sword-server", "identify-version", false); + boolean identify = ConfigurationManager.getBooleanProperty( + "sword-server", "identify-version", false); SWORDUrlManager urlManager = swordService.getUrlManager(); String softwareUri = urlManager.getGeneratorUrl(); if (identify) diff --git a/dspace-sword/src/main/java/org/dspace/sword/SimpleFileIngester.java b/dspace-sword/src/main/java/org/dspace/sword/SimpleFileIngester.java index 4a44326ef1..28bdbd3639 100644 --- a/dspace-sword/src/main/java/org/dspace/sword/SimpleFileIngester.java +++ b/dspace-sword/src/main/java/org/dspace/sword/SimpleFileIngester.java @@ -39,27 +39,31 @@ import java.util.List; public class SimpleFileIngester implements SWORDIngester { - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); - protected BundleService bundleService = ContentServiceFactory.getInstance() - .getBundleService(); + protected BundleService bundleService = + ContentServiceFactory.getInstance().getBundleService(); - protected BitstreamService bitstreamService = ContentServiceFactory - .getInstance().getBitstreamService(); + protected BitstreamService bitstreamService = + ContentServiceFactory.getInstance().getBitstreamService(); - protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory - .getInstance().getBitstreamFormatService(); + protected BitstreamFormatService bitstreamFormatService = + ContentServiceFactory.getInstance().getBitstreamFormatService(); /** * Perform the ingest using the given deposit object onto the specified * target DSpace object, using the SWORD service implementation. * * @param service + * SWORD service implementation * @param deposit + * deposit request * @param target + * target DSpace object * @throws DSpaceSWORDException - * @throws SWORDErrorException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SWORDErrorException on generic SWORD exception */ public DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject target) @@ -70,7 +74,7 @@ public class SimpleFileIngester implements SWORDIngester if (!(target instanceof Item)) { throw new DSpaceSWORDException( - "SimpleFileIngester can only be loaded for deposit onto DSpace Items"); + "SimpleFileIngester can only be loaded for deposit onto DSpace Items"); } Item item = (Item) target; @@ -118,8 +122,8 @@ public class SimpleFileIngester implements SWORDIngester swordService.message("File created in item with filename " + fn); - BitstreamFormat bf = bitstreamFormatService - .findByMIMEType(context, deposit.getContentType()); + BitstreamFormat bf = bitstreamFormatService.findByMIMEType( + context, deposit.getContentType()); if (bf != null) { bs.setFormat(context, bf); diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Author.java b/dspace-sword/src/main/java/org/purl/sword/atom/Author.java index 35ffc32cc0..3d544177ee 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Author.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Author.java @@ -31,319 +31,321 @@ import org.purl.sword.base.XmlName; */ public class Author extends XmlElement implements SwordElementInterface { - /** - * Local name for the element. - */ - @Deprecated - public static final String ELEMENT_NAME = "author"; - - /** - * Label for the 'name' attribute. + /** + * Local name for the element. */ - @Deprecated - public static final String ELEMENT_AUTHOR_NAME = "name"; - - /** - * Label for the 'uri' attribute. - */ - @Deprecated - public static final String ELEMENT_URI = "uri"; - - /** - * Label for the 'email' attribute. - */ - @Deprecated - public static final String ELEMENT_EMAIL = "email"; - - /** - * The author's name. - */ - private Name name; - - /** - * The author's URI. - */ - private Uri uri; - - /** - * The author's email. - */ - private Email email; - - /** - * - */ - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_ATOM, "author", Namespaces.NS_ATOM); - - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'author'. - */ - public Author() - { - this(XML_NAME); - } - - public Author(XmlName name) - { - super(name); - } - - /** - * Create a new instance and set the element name. - * - * @param prefix The prefix to use when marshalling the data. - * @param localName The localName to use when marshalling the data. - */ - public Author(String prefix, String localName ) - { - this(prefix, localName, XML_NAME.getNamespace()); - } - - /** - * - * @param prefix - * @param localName - * @param namespaceUri - */ - public Author(String prefix, String localName, String namespaceUri) - { - super(prefix, localName, XML_NAME.getNamespace()); - } - - /** - * Get the XmlName for this class. - * - * @return The prefix, localname and namespace for this element. + @Deprecated + public static final String ELEMENT_NAME = "author"; + + /** + * Label for the 'name' attribute. */ - public static XmlName elementName() + @Deprecated + public static final String ELEMENT_AUTHOR_NAME = "name"; + + /** + * Label for the 'uri' attribute. + */ + @Deprecated + public static final String ELEMENT_URI = "uri"; + + /** + * Label for the 'email' attribute. + */ + @Deprecated + public static final String ELEMENT_EMAIL = "email"; + + /** + * The author's name. + */ + private Name name; + + /** + * The author's URI. + */ + private Uri uri; + + /** + * The author's email. + */ + private Email email; + + /** + * + */ + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_ATOM, "author", Namespaces.NS_ATOM); + + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'author'. + */ + public Author() { - return XML_NAME; + this(XML_NAME); } - - /** - * Marshall the data in this object to a XOM Element. The element - * will have the full name that is specified in the constructor. - * - * @return A XOM Element. - */ - public Element marshall() - { - Element element = new Element(getQualifiedName(), xmlName.getNamespace()); - - if( name != null ) - { - element.appendChild(name.marshall()); - } - - if( uri != null ) - { - element.appendChild(uri.marshall()); - } - - if( email != null ) - { - element.appendChild(email.marshall()); - } - - return element; - } - - - /** - * Unmarshall the author details from the specified element. The element - * is a XOM element. - * - * @param author The element to unmarshall. - */ - public SwordValidationInfo unmarshall(Element author, Properties validationProperties) - throws UnmarshallException - { - if( ! isInstanceOf( author, xmlName) ) - { - handleIncorrectElement(author, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeItems = new ArrayList(); - - processUnexpectedAttributes(author, attributeItems); - - // retrieve all of the sub-elements - Elements elements = author.getChildElements(); - Element element = null; - int length = elements.size(); - - for(int i = 0; i < length; i++ ) - { - element = elements.get(i); - - if( isInstanceOf(element, Name.elementName() )) - { - name = new Name(); - validationItems.add(name.unmarshall(element, validationProperties)); - } - else if( isInstanceOf(element, Uri.elementName())) - { - uri = new Uri(); - validationItems.add(uri.unmarshall(element, validationProperties)); - - } - else if( isInstanceOf(element, Email.elementName() )) - { - email = new Email(); - validationItems.add(email.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), + + public Author(XmlName name) + { + super(name); + } + + /** + * Create a new instance and set the element name. + * + * @param prefix The prefix to use when marshalling the data. + * @param localName The localName to use when marshalling the data. + */ + public Author(String prefix, String localName ) + { + this(prefix, localName, XML_NAME.getNamespace()); + } + + /** + * + * @param prefix The prefix to use when marshalling the data. + * @param localName The localName to use when marshalling the data. + * @param namespaceUri The namespace URI. + */ + public Author(String prefix, String localName, String namespaceUri) + { + super(prefix, localName, XML_NAME.getNamespace()); + } + + /** + * Get the XmlName for this class. + * + * @return The prefix, localname and namespace for this element. + */ + public static XmlName elementName() + { + return XML_NAME; + } + + /** + * Marshall the data in this object to a XOM Element. The element + * will have the full name that is specified in the constructor. + * + * @return A XOM Element. + */ + public Element marshall() + { + Element element = new Element(getQualifiedName(), xmlName.getNamespace()); + + if ( name != null ) + { + element.appendChild(name.marshall()); + } + + if ( uri != null ) + { + element.appendChild(uri.marshall()); + } + + if ( email != null ) + { + element.appendChild(email.marshall()); + } + + return element; + } + + + /** + * Unmarshall the author details from the specified element. The element + * is a XOM element. + * + * @param author The element to unmarshall. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws org.purl.sword.base.UnmarshallException passed through + */ + public SwordValidationInfo unmarshall(Element author, Properties validationProperties) + throws UnmarshallException + { + if ( ! isInstanceOf( author, xmlName) ) + { + handleIncorrectElement(author, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeItems = new ArrayList(); + + processUnexpectedAttributes(author, attributeItems); + + // retrieve all of the sub-elements + Elements elements = author.getChildElements(); + Element element = null; + int length = elements.size(); + + for (int i = 0; i < length; i++ ) + { + element = elements.get(i); + + if ( isInstanceOf(element, Name.elementName() )) + { + name = new Name(); + validationItems.add(name.unmarshall(element, validationProperties)); + } + else if ( isInstanceOf(element, Uri.elementName())) + { + uri = new Uri(); + validationItems.add(uri.unmarshall(element, validationProperties)); + } + else if ( isInstanceOf(element, Email.elementName() )) + { + email = new Email(); + validationItems.add(email.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), SwordValidationInfo.UNKNOWN_ELEMENT, SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } - - } // for - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeItems, validationProperties); - } - return result; - } - - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - public SwordValidationInfo validate(List elements, - List attributes, - Properties validationContext) - { - SwordValidationInfo result = new SwordValidationInfo(xmlName); - - if( name == null ) - { - SwordValidationInfo info = new SwordValidationInfo(Name.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR, - SwordValidationInfoType.ERROR); - result.addValidationInfo(info); - } - else if( elements == null && name != null) - { - result.addValidationInfo(name.validate(validationContext)); - } - - if( elements == null && uri != null ) - { - result.addValidationInfo(uri.validate(validationContext)); - } - - if( elements == null && email != null ) - { - result.addValidationInfo(email.validate(validationContext)); - } - - result.addUnmarshallValidationInfo(elements, attributes); - return result; - } - - /** - * Unmarshall the author details from the specified element. The element - * is a XOM element. - * - * @param author The element to unmarshall. - */ - public void unmarshall(Element author) - throws UnmarshallException - { - unmarshall(author, null); - } - - /** - * Retrieve the author name. - * - * @return The name. - */ - public String getName() - { - if( name == null ) - { - return null; - } - return name.getContent(); - } - - /** - * Set the author name. - * - * @param name The name. - */ - public void setName(String name) - { - this.name = new Name(name); - } - - /** - * Get the author URI. - * - * @return The URI. - */ - public String getUri() - { - if( uri == null ) - { - return null; - } - return uri.getContent(); - } - - /** - * Set the author URI. - * - * @param uri the URI. - */ - public void setUri(String uri) - { - this.uri = new Uri(uri); - } - - /** - * Get the author email. - * - * @return The email. - */ - public String getEmail() - { - if( email == null ) - { - return null; - } - return email.getContent(); - } - - /** - * Set the author email. - * - * @param email The email. - */ - public void setEmail(String email) - { - this.email = new Email(email); - } - - /** - * Return the string. - * @return String. - */ - @Override - public String toString() - { - return "name: " + getName() + - " email: " + getEmail() + " uri: " + getUri(); - } + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + + } // for + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeItems, validationProperties); + } + return result; + } + + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + public SwordValidationInfo validate(List elements, + List attributes, + Properties validationContext) + { + SwordValidationInfo result = new SwordValidationInfo(xmlName); + + if ( name == null ) + { + SwordValidationInfo info = new SwordValidationInfo(Name.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR, + SwordValidationInfoType.ERROR); + result.addValidationInfo(info); + } + else if ( elements == null && name != null) + { + result.addValidationInfo(name.validate(validationContext)); + } + + if ( elements == null && uri != null ) + { + result.addValidationInfo(uri.validate(validationContext)); + } + + if ( elements == null && email != null ) + { + result.addValidationInfo(email.validate(validationContext)); + } + + result.addUnmarshallValidationInfo(elements, attributes); + return result; + } + + /** + * Unmarshall the author details from the specified element. The element + * is a XOM element. + * + * @param author The element to unmarshall. + */ + public void unmarshall(Element author) + throws UnmarshallException + { + unmarshall(author, null); + } + + /** + * Retrieve the author name. + * + * @return The name. + */ + public String getName() + { + if ( name == null ) + { + return null; + } + return name.getContent(); + } + + /** + * Set the author name. + * + * @param name The name. + */ + public void setName(String name) + { + this.name = new Name(name); + } + + /** + * Get the author URI. + * + * @return The URI. + */ + public String getUri() + { + if ( uri == null ) + { + return null; + } + return uri.getContent(); + } + + /** + * Set the author URI. + * + * @param uri the URI. + */ + public void setUri(String uri) + { + this.uri = new Uri(uri); + } + + /** + * Get the author email. + * + * @return The email. + */ + public String getEmail() + { + if ( email == null ) + { + return null; + } + return email.getContent(); + } + + /** + * Set the author email. + * + * @param email The email. + */ + public void setEmail(String email) + { + this.email = new Email(email); + } + + /** + * Return the string. + * @return String. + */ + @Override + public String toString() + { + return "name: " + getName() + + " email: " + getEmail() + " uri: " + getUri(); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Content.java b/dspace-sword/src/main/java/org/purl/sword/atom/Content.java index 13912770ce..d786d39ecd 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Content.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Content.java @@ -30,252 +30,256 @@ import org.purl.sword.base.XmlName; */ public class Content extends XmlElement implements SwordElementInterface { - /** - * The identifier for the src attribute. - */ - public static final String ATTRIBUTE_SRC = "src"; - - /** - * The identifier for the type attribute. - */ - public static final String ATTRIBUTE_TYPE = "type"; - - /** - * The data for the type attribute. - */ - private String type; - - /** - * The data for the source attribute. - */ - private String source; - - /** - * The log. - */ - private static Logger log = Logger.getLogger(Content.class); - - /** - * - */ - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_ATOM, "content", Namespaces.NS_ATOM); - - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'content'. - */ - public Content() - { - super(XML_NAME); - } - - public static XmlName elementName() - { - return XML_NAME; - } - - /** - * Get the Source. - * - * @return The Source. - */ - public String getSource() - { - return source; - } - - /** - * Set the Source. - * - * @param source The source. - */ - public void setSource(String source) - { - this.source = source; - } - - /** - * Get the type. - * - * @return The type. - */ - public String getType() - { - return type; - } - - /** - * Set the type for the content. This should match the pattern - * ".* /.*" [Note, there is no space before the /, this has been added - * to allow this text to be written in a Java comment.]. - * - * An example of the type is application/zip. - * - * @param type The specified type. - * @throws InvalidMediaTypeException If the specified type is null or - * it does not match the specified pattern. - */ - public void setType(String type) - throws InvalidMediaTypeException - { - if( type == null || ! type.matches(".*/.*") ) - { - throw new InvalidMediaTypeException("Type: '" + type + "' does not match .*/.*"); - } - - this.type = type; - } - - /** - * Marshall the data in this object to an Element object. - * - * @return A XOM Element that holds the data for this Content element. - */ - public Element marshall() - { - Element content = new Element(getQualifiedName(), Namespaces.NS_ATOM); + /** + * The identifier for the src attribute. + */ + public static final String ATTRIBUTE_SRC = "src"; + + /** + * The identifier for the type attribute. + */ + public static final String ATTRIBUTE_TYPE = "type"; + + /** + * The data for the type attribute. + */ + private String type; + + /** + * The data for the source attribute. + */ + private String source; + + /** + * The log. + */ + private static Logger log = Logger.getLogger(Content.class); + + /** + * + */ + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_ATOM, "content", Namespaces.NS_ATOM); + + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'content'. + */ + public Content() + { + super(XML_NAME); + } + + public static XmlName elementName() + { + return XML_NAME; + } + + /** + * Get the Source. + * + * @return The Source. + */ + public String getSource() + { + return source; + } + + /** + * Set the Source. + * + * @param source The source. + */ + public void setSource(String source) + { + this.source = source; + } + + /** + * Get the type. + * + * @return The type. + */ + public String getType() + { + return type; + } + + /** + * Set the type for the content. This should match the pattern + * ".* /.*" [Note, there is no space before the /, this has been added + * to allow this text to be written in a Java comment.]. + * + * An example of the type is application/zip. + * + * @param type The specified type. + * @throws InvalidMediaTypeException If the specified type is null or + * it does not match the specified pattern. + */ + public void setType(String type) + throws InvalidMediaTypeException + { + if ( type == null || ! type.matches(".*/.*") ) + { + throw new InvalidMediaTypeException("Type: '" + type + "' does not match .*/.*"); + } + + this.type = type; + } + + /** + * Marshall the data in this object to an Element object. + * + * @return A XOM Element that holds the data for this Content element. + */ + public Element marshall() + { + Element content = new Element(getQualifiedName(), Namespaces.NS_ATOM); + + if ( type != null ) + { + Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type); + content.addAttribute(typeAttribute); + } - if( type != null ) - { - Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type); - content.addAttribute(typeAttribute); - } - - if( source != null ) - { - Attribute typeAttribute = new Attribute(ATTRIBUTE_SRC, source); - content.addAttribute(typeAttribute); - } - - return content; - } - - public void unmarshall(Element content) - throws UnmarshallException - { - unmarshall(content, null); - } - - /** - * Unmarshall the content element into the data in this object. - * - * @throws UnmarshallException If the element does not contain a - * content element or if there are problems - * accessing the data. - */ - public SwordValidationInfo unmarshall(Element content, Properties validationProperties) - throws UnmarshallException - { - - if( ! isInstanceOf( content, xmlName.getLocalName(), Namespaces.NS_ATOM)) - { - return handleIncorrectElement(content, validationProperties); - } - - ArrayList elements = new ArrayList(); - ArrayList attributes = new ArrayList(); - - try - { - // get the attributes - int attributeCount = content.getAttributeCount(); - Attribute attribute = null; - for( int i = 0; i < attributeCount; i++ ) - { - attribute = content.getAttribute(i); - String name = attribute.getQualifiedName(); - if( ATTRIBUTE_TYPE.equals(name)) + if ( source != null ) + { + Attribute typeAttribute = new Attribute(ATTRIBUTE_SRC, source); + content.addAttribute(typeAttribute); + } + + return content; + } + + public void unmarshall(Element content) + throws UnmarshallException + { + unmarshall(content, null); + } + + /** + * Unmarshall the content element into the data in this object. + * + * @param content the element to unmarshall. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException If the element does not contain a + * content element or if there are problems + * accessing the data. + */ + public SwordValidationInfo unmarshall(Element content, Properties validationProperties) + throws UnmarshallException + { + if ( ! isInstanceOf( content, xmlName.getLocalName(), Namespaces.NS_ATOM)) + { + return handleIncorrectElement(content, validationProperties); + } + + ArrayList elements = new ArrayList(); + ArrayList attributes = new ArrayList(); + + try + { + // get the attributes + int attributeCount = content.getAttributeCount(); + Attribute attribute = null; + for ( int i = 0; i < attributeCount; i++ ) { - type = attribute.getValue(); - if( validationProperties != null ) + attribute = content.getAttribute(i); + String name = attribute.getQualifiedName(); + if ( ATTRIBUTE_TYPE.equals(name)) { - attributes.add(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); + type = attribute.getValue(); + if ( validationProperties != null ) + { + attributes.add(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); + } + } + else if ( ATTRIBUTE_SRC.equals(name) ) + { + source = attribute.getValue(); + if ( validationProperties != null ) + { + attributes.add(createValidAttributeInfo(ATTRIBUTE_SRC, source)); + } + } + else + { + SwordValidationInfo info = new SwordValidationInfo(xmlName, + new XmlName(attribute), + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO ); + info.setContentDescription(attribute.getValue()); + attributes.add(info); } } - else if( ATTRIBUTE_SRC.equals(name) ) + + // check if there is any content. If there is, add a simple message to + // say that there are sub elements that are not used in this profile + if ( content.getChildCount() > 0 ) { - source = attribute.getValue(); - if( validationProperties != null ) - { - attributes.add(createValidAttributeInfo(ATTRIBUTE_SRC, source)); - } - } - else - { - SwordValidationInfo info = new SwordValidationInfo(xmlName, - new XmlName(attribute), - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO ); - info.setContentDescription(attribute.getValue()); - attributes.add(info); - } - } - - // check if there is any content. If there is, add a simple message to - // say that there are sub elements that are not used in this profile - if( content.getChildCount() > 0 ) - { - elements.add(new SwordValidationInfo(xmlName, + elements.add(new SwordValidationInfo(xmlName, "This element has child elements. These are not expected as part of the SWORD profile", SwordValidationInfoType.INFO)); - } - - } - catch( Exception ex ) - { - log.error("Unable to parse an element in Content: " + ex.getMessage()); - throw new UnmarshallException("Error parsing Content", ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(elements, attributes, validationProperties); - } - return result; - } - - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - /** - * - * @param elements - * @param attributes - */ - protected SwordValidationInfo validate(List elements, - List attributes, - Properties validationContext) - { - SwordValidationInfo info = new SwordValidationInfo(xmlName); - - if( source == null ) - { - XmlName attributeName = new XmlName(xmlName.getPrefix(), - ATTRIBUTE_SRC, - xmlName.getNamespace()); - - SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, - SwordValidationInfoType.ERROR); - info.addValidationInfo(item); - } - - info.addUnmarshallValidationInfo(elements, attributes); - return info; - } - - /** - * Get a string representation. - * - * @return String - */ - @Override - public String toString() - { - return "Content - source: " + getSource() + " type: " + getType(); - } + } + + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in Content: " + ex.getMessage()); + throw new UnmarshallException("Error parsing Content", ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(elements, attributes, validationProperties); + } + return result; + } + + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + /** + * + * @param elements add results to this. + * @param attributes add these too. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + protected SwordValidationInfo validate(List elements, + List attributes, + Properties validationContext) + { + SwordValidationInfo info = new SwordValidationInfo(xmlName); + + if ( source == null ) + { + XmlName attributeName = new XmlName(xmlName.getPrefix(), + ATTRIBUTE_SRC, + xmlName.getNamespace()); + + SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, + SwordValidationInfoType.ERROR); + info.addValidationInfo(item); + } + + info.addUnmarshallValidationInfo(elements, attributes); + return info; + } + + /** + * Get a string representation. + * + * @return String + */ + @Override + public String toString() + { + return "Content - source: " + getSource() + " type: " + getType(); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/ContentType.java b/dspace-sword/src/main/java/org/purl/sword/atom/ContentType.java index 7c3e0b0c54..23f02541b0 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/ContentType.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/ContentType.java @@ -14,31 +14,31 @@ package org.purl.sword.atom; */ public enum ContentType { - TEXT ("text"), - HTML ("html"), - XHTML ("xhtml"); - - /** - * String representation of the type. - */ - private final String type; - - /** - * Create a new instance and set the string - * representation of the type. - * - * @param type The type, expressed as a string. - */ - private ContentType(String type) - { - this.type = type; - } - - /** - * Retrieve a string representation of this object. - * - * @return A string. - */ - @Override - public String toString() { return this.type; } + TEXT ("text"), + HTML ("html"), + XHTML ("xhtml"); + + /** + * String representation of the type. + */ + private final String type; + + /** + * Create a new instance and set the string + * representation of the type. + * + * @param type The type, expressed as a string. + */ + private ContentType(String type) + { + this.type = type; + } + + /** + * Retrieve a string representation of this object. + * + * @return A string. + */ + @Override + public String toString() { return this.type; } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Contributor.java b/dspace-sword/src/main/java/org/purl/sword/atom/Contributor.java index fd10408de7..ed1fc2f67f 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Contributor.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Contributor.java @@ -17,25 +17,25 @@ import org.purl.sword.base.XmlName; */ public class Contributor extends Author { - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_ATOM, "contributor", Namespaces.NS_ATOM); - - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'contributor'. - */ - public Contributor() - { - super(XML_NAME); - } - - /** - * Get the element name for this Xml Element. - * - * @return The details of prefix, localname and namespace. - */ - public static XmlName elementName() - { - return XML_NAME; - } + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_ATOM, "contributor", Namespaces.NS_ATOM); + + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'contributor'. + */ + public Contributor() + { + super(XML_NAME); + } + + /** + * Get the element name for this Xml Element. + * + * @return The details of prefix, localname and namespace. + */ + public static XmlName elementName() + { + return XML_NAME; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Entry.java b/dspace-sword/src/main/java/org/purl/sword/atom/Entry.java index 1a20f2ffe1..4a745f3ab8 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Entry.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Entry.java @@ -33,989 +33,993 @@ import org.purl.sword.base.XmlName; */ public class Entry extends XmlElement implements SwordElementInterface { - /** - * Local name for the element. - */ - @Deprecated - public static final String ELEMENT_NAME = "entry"; - - /** - * Local name for the atom id element. - */ - @Deprecated - public static final String ELEMENT_ID = "id"; - - /** - * Local name for the atom published element. - */ - @Deprecated - public static final String ELEMENT_PUBLISHED = "published"; - - /** - * Local name for the atom updated element. - */ - @Deprecated - public static final String ELEMENT_UPDATED = "updated"; - - /** - * Local name for the atom category element. - */ - @Deprecated - public static final String ELEMENT_CATEGORY = "category"; - - /** - * Local name for the atom generator element. - */ - @Deprecated - public static final String ELEMENT_GENERATOR = "generator"; - - /** - * A list of authors associated with this entry. There can be 0 - * or more of these elements. - */ - private List authors; - - /** - * The atom:category data. There can be 0 or more of these elements. - */ - private List categories; - - /** - * A single content element for the Entry. - */ - private Content content; - - /** - * A single content element for the Entry. - */ - private Generator generator; - - /** - * A list of contributors associated with this entry. There can be 0 or - * more of these elements. - */ - private List contributors; - - /** - * This is a simplified version. The ID can also have atomCommonAttributes, - * but these have not been modeled in this version. The content of - * ID is an unconstrained string, which is intended to represent a URI. - */ - private Id id; - - /** - * A list of link elements. This can contain 0 or more entries. - */ - private List links; - - /** - * Simplified version of the atom:published element. This implementation - * does not record the general atomCommonAttributes. The date is - * taken from an xsd:dateTime value. - * - * This item is optional. - */ - private Published published; - - /** - * A single, optional, content element for the Entry. - */ - private Rights rights; - - /** - * A single, optional, content element for the Entry. - */ - @Deprecated - private Source source; - - /** - * A single, optional, summary element for the Entry. - */ - private Summary summary; - - /** - * A required title element for the entry. - */ - private Title title; - - /** - * The date on which the entry was last updated. - */ - private Updated updated; - - /** - * The log. - */ - private static Logger log = Logger.getLogger(Entry.class); - - /** - * The prefix, local name and namespace used for this element. - */ - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_ATOM, "entry", Namespaces.NS_ATOM); - - /** - * Create a new instance of the class and initialise it. - * Also, set the prefix to 'atom' and the local name to 'entry'. - */ - public Entry() - { - this(XML_NAME.getPrefix(), - XML_NAME.getLocalName(), - XML_NAME.getNamespace()); - } - - /** - * Create a new instance of the class an initalise it, setting the - * element namespace and name. - * - * @param prefix The namespace prefix of the element - * @param element The element name - */ - public Entry(String prefix, String element) - { - this(prefix, element, XML_NAME.getNamespace()); - } - - /** - * - * @param prefix - * @param element - * @param namespaceUri - */ - public Entry(String prefix, String element, String namespaceUri) - { - super(prefix, element, namespaceUri); - initialise(); - } - - public Entry(XmlName name) - { - this(name.getPrefix(), name.getLocalName(), name.getNamespace()); - } - - - - public static XmlName elementName() - { - return XML_NAME; - } - - protected boolean isElementChecked(XmlName elementName) - { - if( elementName == null ) - { - return false; - } - - return elementName.equals(Author.elementName()) | - elementName.equals(Category.elementName()) | - elementName.equals(Content.elementName()) | - elementName.equals(Generator.elementName()) | - elementName.equals(Contributor.elementName()) | - elementName.equals(Id.elementName()) | - elementName.equals(Link.elementName()) | - elementName.equals(Published.elementName()) | - elementName.equals(Rights.elementName()) | - elementName.equals(Source.elementName()) | - elementName.equals(Summary.elementName()) | - elementName.equals(Title.elementName()) | - elementName.equals(Updated.elementName()); - } - - /** - * - */ - protected void initialise() - { - authors = new ArrayList(); - categories = new ArrayList(); - contributors = new ArrayList(); - links = new ArrayList(); - } - - /** - * Marshal the data stored in this object into Element objects. - * - * @return An element that holds the data associated with this object. - */ - public Element marshall() - { - Element entry = new Element(getQualifiedName(), Namespaces.NS_ATOM); - entry.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD); - entry.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM); - this.marshallElements(entry); - return entry; - } - - protected void marshallElements(Element entry) - { - if (id != null) - { - entry.appendChild(id.marshall()); - } - - for (Author author : authors) - { - entry.appendChild(author.marshall()); - } - - if (content != null) - { - entry.appendChild(content.marshall()); - } - - if (generator != null) - { - entry.appendChild(generator.marshall()); - } - - for (Author contributor : contributors) - { - entry.appendChild(contributor.marshall()); - } - - for (Link link : links) - { - entry.appendChild(link.marshall()); - } - - if (published != null) - { - entry.appendChild(published.marshall()); - } - - if (rights != null) - { - entry.appendChild(rights.marshall()); - } - - if (summary != null) - { - entry.appendChild(summary.marshall()); - } - - if (title != null) - { - entry.appendChild(title.marshall()); - } - - if (source != null) - { - entry.appendChild(source.marshall()); - } - - if (updated != null) - { - entry.appendChild(updated.marshall()); - } - - for (Category category : categories) - { - entry.appendChild(category.marshall()); - } - } - - /** - * Unmarshal the contents of the Entry element into the internal data objects - * in this object. - * - * @param entry The Entry element to process. - * - * @throws UnmarshallException If the element does not contain an ATOM entry - * element, or if there is a problem processing the element or any - * subelements. - */ - public void unmarshall(Element entry) - throws UnmarshallException - { - unmarshall(entry, null); - } - - public SwordValidationInfo unmarshallWithoutValidate(Element entry, Properties validationProperties) - throws UnmarshallException - { - if (! isInstanceOf(entry, xmlName) ) - { - return handleIncorrectElement(entry, validationProperties); - } - - // used to hold the element and attribute unmarshal info results - SwordValidationInfo result = new SwordValidationInfo(xmlName); - - try - { - initialise(); - - // FIXME - attributes? - - // retrieve all of the sub-elements - Elements elements = entry.getChildElements(); - Element element = null; - int length = elements.size(); - - for (int i = 0; i < length; i++) - { - element = elements.get(i); - - if (isInstanceOf(element, Author.elementName())) + /** + * Local name for the element. + */ + @Deprecated + public static final String ELEMENT_NAME = "entry"; + + /** + * Local name for the atom id element. + */ + @Deprecated + public static final String ELEMENT_ID = "id"; + + /** + * Local name for the atom published element. + */ + @Deprecated + public static final String ELEMENT_PUBLISHED = "published"; + + /** + * Local name for the atom updated element. + */ + @Deprecated + public static final String ELEMENT_UPDATED = "updated"; + + /** + * Local name for the atom category element. + */ + @Deprecated + public static final String ELEMENT_CATEGORY = "category"; + + /** + * Local name for the atom generator element. + */ + @Deprecated + public static final String ELEMENT_GENERATOR = "generator"; + + /** + * A list of authors associated with this entry. There can be 0 + * or more of these elements. + */ + private List authors; + + /** + * The atom:category data. There can be 0 or more of these elements. + */ + private List categories; + + /** + * A single content element for the Entry. + */ + private Content content; + + /** + * A single content element for the Entry. + */ + private Generator generator; + + /** + * A list of contributors associated with this entry. There can be 0 or + * more of these elements. + */ + private List contributors; + + /** + * This is a simplified version. The ID can also have atomCommonAttributes, + * but these have not been modeled in this version. The content of + * ID is an unconstrained string, which is intended to represent a URI. + */ + private Id id; + + /** + * A list of link elements. This can contain 0 or more entries. + */ + private List links; + + /** + * Simplified version of the atom:published element. This implementation + * does not record the general atomCommonAttributes. The date is + * taken from an xsd:dateTime value. + * + * This item is optional. + */ + private Published published; + + /** + * A single, optional, content element for the Entry. + */ + private Rights rights; + + /** + * A single, optional, content element for the Entry. + */ + @Deprecated + private Source source; + + /** + * A single, optional, summary element for the Entry. + */ + private Summary summary; + + /** + * A required title element for the entry. + */ + private Title title; + + /** + * The date on which the entry was last updated. + */ + private Updated updated; + + /** + * The log. + */ + private static Logger log = Logger.getLogger(Entry.class); + + /** + * The prefix, local name and namespace used for this element. + */ + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_ATOM, "entry", Namespaces.NS_ATOM); + + /** + * Create a new instance of the class and initialise it. + * Also, set the prefix to 'atom' and the local name to 'entry'. + */ + public Entry() + { + this(XML_NAME.getPrefix(), + XML_NAME.getLocalName(), + XML_NAME.getNamespace()); + } + + /** + * Create a new instance of the class an initalise it, setting the + * element namespace and name. + * + * @param prefix The namespace prefix of the element + * @param element The element name + */ + public Entry(String prefix, String element) + { + this(prefix, element, XML_NAME.getNamespace()); + } + + /** + * + * @param prefix The prefix. + * @param element element name. + * @param namespaceUri The namespace URI. + */ + public Entry(String prefix, String element, String namespaceUri) + { + super(prefix, element, namespaceUri); + initialise(); + } + + public Entry(XmlName name) + { + this(name.getPrefix(), name.getLocalName(), name.getNamespace()); + } + + + + public static XmlName elementName() + { + return XML_NAME; + } + + protected boolean isElementChecked(XmlName elementName) + { + if ( elementName == null ) + { + return false; + } + + return elementName.equals(Author.elementName()) | + elementName.equals(Category.elementName()) | + elementName.equals(Content.elementName()) | + elementName.equals(Generator.elementName()) | + elementName.equals(Contributor.elementName()) | + elementName.equals(Id.elementName()) | + elementName.equals(Link.elementName()) | + elementName.equals(Published.elementName()) | + elementName.equals(Rights.elementName()) | + elementName.equals(Source.elementName()) | + elementName.equals(Summary.elementName()) | + elementName.equals(Title.elementName()) | + elementName.equals(Updated.elementName()); + } + + /** + * + */ + protected void initialise() + { + authors = new ArrayList(); + categories = new ArrayList(); + contributors = new ArrayList(); + links = new ArrayList(); + } + + /** + * Marshal the data stored in this object into Element objects. + * + * @return An element that holds the data associated with this object. + */ + public Element marshall() + { + Element entry = new Element(getQualifiedName(), Namespaces.NS_ATOM); + entry.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD); + entry.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM); + this.marshallElements(entry); + return entry; + } + + protected void marshallElements(Element entry) + { + if (id != null) + { + entry.appendChild(id.marshall()); + } + + for (Author author : authors) + { + entry.appendChild(author.marshall()); + } + + if (content != null) + { + entry.appendChild(content.marshall()); + } + + if (generator != null) + { + entry.appendChild(generator.marshall()); + } + + for (Author contributor : contributors) + { + entry.appendChild(contributor.marshall()); + } + + for (Link link : links) + { + entry.appendChild(link.marshall()); + } + + if (published != null) + { + entry.appendChild(published.marshall()); + } + + if (rights != null) + { + entry.appendChild(rights.marshall()); + } + + if (summary != null) + { + entry.appendChild(summary.marshall()); + } + + if (title != null) + { + entry.appendChild(title.marshall()); + } + + if (source != null) + { + entry.appendChild(source.marshall()); + } + + if (updated != null) + { + entry.appendChild(updated.marshall()); + } + + for (Category category : categories) + { + entry.appendChild(category.marshall()); + } + } + + /** + * Unmarshal the contents of the Entry element into the internal data objects + * in this object. + * + * @param entry The Entry element to process. + * + * @throws UnmarshallException If the element does not contain an ATOM entry + * element, or if there is a problem processing the element or any + * subelements. + */ + public void unmarshall(Element entry) + throws UnmarshallException + { + unmarshall(entry, null); + } + + public SwordValidationInfo unmarshallWithoutValidate(Element entry, Properties validationProperties) + throws UnmarshallException + { + if (! isInstanceOf(entry, xmlName) ) + { + return handleIncorrectElement(entry, validationProperties); + } + + // used to hold the element and attribute unmarshal info results + SwordValidationInfo result = new SwordValidationInfo(xmlName); + + try + { + initialise(); + + // FIXME - attributes? + + // retrieve all of the sub-elements + Elements elements = entry.getChildElements(); + Element element = null; + int length = elements.size(); + + for (int i = 0; i < length; i++) { - Author author = new Author(); - result.addUnmarshallElementInfo(author.unmarshall(element, validationProperties)); - authors.add(author); - } - else if (isInstanceOf(element, Category.elementName())) - { - Category category = new Category(); - result.addUnmarshallElementInfo(category.unmarshall(element, validationProperties)); - categories.add(category); - } - else if (isInstanceOf(element, Content.elementName())) - { - if( content == null ) - { - content = new Content(); - result.addUnmarshallElementInfo(content.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Content.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - - } - else if (isInstanceOf(element, Generator.elementName())) - { - if( generator == null ) - { - generator = new Generator(); - result.addUnmarshallElementInfo(generator.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, Contributor.elementName())) - { - Contributor contributor = new Contributor(); - result.addUnmarshallElementInfo(contributor.unmarshall(element, validationProperties)); - contributors.add(contributor); - } - else if (isInstanceOf(element, Id.elementName())) - { - if( id == null ) - { - id = new Id(); - result.addUnmarshallElementInfo(id.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Id.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - - } - else if (isInstanceOf(element, Link.elementName())) - { - Link link = new Link(); - result.addUnmarshallElementInfo(link.unmarshall(element, validationProperties)); - links.add(link); - } - else if (isInstanceOf(element, Published.elementName())) - { - if( published == null ) - { - published = new Published(); - result.addUnmarshallElementInfo(published.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Published.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, Rights.elementName())) - { - if( rights == null ) - { - rights = new Rights(); - result.addUnmarshallElementInfo(rights.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Rights.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, Summary.elementName())) - { - if( summary == null ) - { - summary = new Summary(); - result.addUnmarshallElementInfo(summary.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Summary.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, Title.elementName())) - { - if( title == null ) - { - title = new Title(); - result.addUnmarshallElementInfo(title.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Title.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, Updated.elementName())) - { - if( updated == null ) - { - updated = new Updated(); - result.addUnmarshallElementInfo(updated.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Updated.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, Source.elementName())) - { - if( source == null ) - { - source = new Source(); - result.addUnmarshallElementInfo(source.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Source.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if( validationProperties != null ) - { - XmlName name = new XmlName(element); - if( ! isElementChecked(name) ) + element = elements.get(i); + + if (isInstanceOf(element, Author.elementName())) { - SwordValidationInfo info = new SwordValidationInfo(name, - SwordValidationInfo.UNKNOWN_ELEMENT, - SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); + Author author = new Author(); + result.addUnmarshallElementInfo(author.unmarshall(element, validationProperties)); + authors.add(author); } - } - - } // for - } - catch (Exception ex) - { - log.error("Unable to parse an element in Entry: " + ex.getMessage()); - ex.printStackTrace(); - throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); - } - - return result; - } - - public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) - throws UnmarshallException - { - - SwordValidationInfo result = unmarshallWithoutValidate(entry, validationProperties); - if( validationProperties != null ) - { - result = validate(result, validationProperties); - } - return result; - } - - /** - * - */ - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, validationContext); - } - - /** - * - * @param info - * @param validationContext - */ - protected SwordValidationInfo validate(SwordValidationInfo info, - Properties validationContext) - { - // determine if a full validation is required - boolean validateAll = (info == null); - - SwordValidationInfo result = info; - if( result == null ) - { - result = new SwordValidationInfo(xmlName); - } - - // id, title an updated are required - if( id == null ) - { - result.addValidationInfo(new SwordValidationInfo(Id.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR, - SwordValidationInfoType.ERROR)); - } - else if( id != null && validateAll ) - { - result.addValidationInfo(id.validate(validationContext)); - } - - if( title == null ) - { - result.addValidationInfo(new SwordValidationInfo(Title.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR, - SwordValidationInfoType.ERROR)); - } - else if( title != null && validateAll ) - { - result.addValidationInfo(title.validate(validationContext)); - } - - if( updated == null ) - { - result.addValidationInfo(new SwordValidationInfo(Updated.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR, - SwordValidationInfoType.ERROR)); - } - else if( updated != null && validateAll ) - { - result.addValidationInfo(updated.validate(validationContext)); - } - - // additional sword requirements on the element - if( contributors.isEmpty() ) - { - String contributor = validationContext.getProperty(HttpHeaders.X_ON_BEHALF_OF); - if( contributor != null ) - { - result.addValidationInfo(new SwordValidationInfo(Contributor.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR + - " This item SHOULD contain the value of the X-On-Behalf-Of header, if one was present in the POST request.", - SwordValidationInfoType.ERROR)); - } - } - else if( (! contributors.isEmpty()) && validateAll ) - { - Iterator iterator = contributors.iterator(); - while( iterator.hasNext() ) - { - Contributor contributor = iterator.next(); - result.addValidationInfo(contributor.validate(validationContext)); - } - } - - if( generator == null ) - { - result.addValidationInfo(new SwordValidationInfo(Generator.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR + - " SHOULD contain the URI and version of the server software.", - SwordValidationInfoType.ERROR)); - } - else if( generator != null && validateAll ) - { - result.addValidationInfo(generator.validate(validationContext)); - } - - if( validateAll ) - { - // process the remaining items - Iterator linksIterator = links.iterator(); - while( linksIterator.hasNext() ) - { - Link link = linksIterator.next(); - result.addValidationInfo(link.validate(validationContext)); - } - - Iterator authorIterator = authors.iterator(); - while( authorIterator.hasNext() ) - { - Author author = authorIterator.next(); - result.addValidationInfo(author.validate(validationContext)); - } - - if( content != null ) - { - result.addValidationInfo(content.validate(validationContext)); - } - - if( published != null ) - { - result.addValidationInfo(published.validate(validationContext)); - } - - if( rights != null ) - { - result.addValidationInfo(rights.validate(validationContext)); - } - - if( summary != null ) - { - result.addValidationInfo(summary.validate(validationContext)); - } - - Iterator categoryIterator = categories.iterator(); - while( categoryIterator.hasNext() ) - { - Category category = categoryIterator.next(); - result.addValidationInfo(category.validate(validationContext)); - } - - } - - return result; - } - - /** - * Get an iterator for the authors in the Entry. - * - * @return An iterator. - */ - public Iterator getAuthors() - { - return authors.iterator(); - } - - /** - * Add an author to the Entry. - * - * @param author The author to add. - */ - public void addAuthors(Author author) - { - this.authors.add(author); - } - - /** - * Clear the list of authors. - */ - public void clearAuthors() - { - this.authors.clear(); - } - - /** - * Get an iterator for the categories in this Entry. - * - * @return An iterator. - */ - public Iterator getCategories() { - ArrayList items = new ArrayList(); - for( int i = 0; i < categories.size(); i++ ) - { - items.add(categories.get(i).getContent()); - } - - return items.iterator(); - } - - /** - * Add a category. - * - * @param category the category to add. - */ - public void addCategory(String category) { - this.categories.add(new Category(category)); - } - - /** - * Clear the list of categories. - */ - public void clearCategories() - { - this.categories.clear(); - } - - /** - * Get the content element for this Entry. - * - * @return The content element. - */ - public Content getContent() - { - return content; - } - - /** - * Set the content element for this Entry. - * @param content - */ - public void setContent(Content content) - { - this.content = content; - } - - /** - * Get the generator for this Entry. - * - * @return The generator element. - */ - public Generator getGenerator() - { - return generator; - } - - /** - * Set the generator for this Entry. - * @param generator - */ - public void setGenerator(Generator generator) - { - this.generator = generator; - } - - /** - * Get a list of contributors. - * - * @return An iterator. - */ - public Iterator getContributors() { - return contributors.iterator(); - } - - /** - * Add a contributor. - * - * @param contributor The contributor. - */ - public void addContributor(Contributor contributor) - { - this.contributors.add(contributor); - } - - /** - * Clear the list of contributors. - */ - public void clearContributors() - { - this.contributors.clear(); - } - - /** - * Get the ID for this Entry. - * - * @return The ID. - */ - public String getId() - { - if( id == null ) - { - return null; - } - return id.getContent(); - } - - /** - * Set the ID for this Entry. - * - * @param id The ID. - */ - public void setId(String id) - { - this.id = new Id(id); - } - - /** - * Get the list of links for this Entry. - * - * @return An iterator. - */ - public Iterator getLinks() - { - return links.iterator(); - } - - /** - * Get the link for this Entry. - * - * @param link The link. - */ - public void addLink(Link link) - { - this.links.add(link); - } - - /** - * Clear the list of links. - */ - public void clearLinks() - { - this.links.clear(); - } - - /** - * Get the published date, expressed as a String. - * - * @return The date. - */ - public String getPublished() - { - if( published == null ) - { - return null; - } - return published.getContent(); - } + else if (isInstanceOf(element, Category.elementName())) + { + Category category = new Category(); + result.addUnmarshallElementInfo(category.unmarshall(element, validationProperties)); + categories.add(category); + } + else if (isInstanceOf(element, Content.elementName())) + { + if ( content == null ) + { + content = new Content(); + result.addUnmarshallElementInfo(content.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Content.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } - /** - * Set the published date. The date should be in one of the - * supported formats. This method will not check that the string - * is in the correct format. - * - * @param published The string. - */ - public void setPublished(String published) - { - this.published = new Published(published); - } - - /** - * Get the rights for this Entry. - * @return The rights. - */ - public Rights getRights() { - return rights; - } - - /** - * Set the rights for this Entry. - * - * @param rights The rights. - */ - public void setRights(Rights rights) { - this.rights = rights; - } - - /** - * Get the source for this Entry. - * @return The source. - * @deprecated - */ - @Deprecated - public Source getSource() { - return source; - } - - /** - * Set the source for this entry. - * - * @param source The source. - * @deprecated - */ - @Deprecated - public void setSource(Source source) - { - this.source = source; - } - - /** - * Get the summary. - * - * @return The summary. - */ - public Summary getSummary() - { - return summary; - } - - /** - * Set the summary. - * - * @param summary The summary. - */ - public void setSummary(Summary summary) - { - this.summary = summary; - } - - /** - * Get the title. - * - * @return The title. - */ - public Title getTitle() - { - return title; - } - - /** - * Set the title. - * - * @param title The title. - */ - public void setTitle(Title title) - { - this.title = title; - } - - /** - * Get the updated date, expressed as a String. See - * org.purl.sword.XmlElement.stringToDate for the - * list of supported formats. This particular method - * will not check if the date is formatted correctly. - * - * @return The date. - */ - public String getUpdated() - { - if( updated == null ) - { - return null; - } - return updated.getContent(); - } - - /** - * Set the updated date. The date should match one of the - * supported formats. This method will not check the format of the - * string. - * - * @param updated The string. - * @see Entry#setPublished(String) setPublished - */ - public void setUpdated(String updated) - { - this.updated = new Updated(updated); - } + } + else if (isInstanceOf(element, Generator.elementName())) + { + if ( generator == null ) + { + generator = new Generator(); + result.addUnmarshallElementInfo(generator.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, Contributor.elementName())) + { + Contributor contributor = new Contributor(); + result.addUnmarshallElementInfo(contributor.unmarshall(element, validationProperties)); + contributors.add(contributor); + } + else if (isInstanceOf(element, Id.elementName())) + { + if ( id == null ) + { + id = new Id(); + result.addUnmarshallElementInfo(id.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Id.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, Link.elementName())) + { + Link link = new Link(); + result.addUnmarshallElementInfo(link.unmarshall(element, validationProperties)); + links.add(link); + } + else if (isInstanceOf(element, Published.elementName())) + { + if ( published == null ) + { + published = new Published(); + result.addUnmarshallElementInfo(published.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Published.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, Rights.elementName())) + { + if ( rights == null ) + { + rights = new Rights(); + result.addUnmarshallElementInfo(rights.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Rights.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, Summary.elementName())) + { + if ( summary == null ) + { + summary = new Summary(); + result.addUnmarshallElementInfo(summary.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Summary.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, Title.elementName())) + { + if ( title == null ) + { + title = new Title(); + result.addUnmarshallElementInfo(title.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Title.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, Updated.elementName())) + { + if ( updated == null ) + { + updated = new Updated(); + result.addUnmarshallElementInfo(updated.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Updated.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, Source.elementName())) + { + if ( source == null ) + { + source = new Source(); + result.addUnmarshallElementInfo(source.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Source.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if ( validationProperties != null ) + { + XmlName name = new XmlName(element); + if ( ! isElementChecked(name) ) + { + SwordValidationInfo info = new SwordValidationInfo(name, + SwordValidationInfo.UNKNOWN_ELEMENT, + SwordValidationInfoType.INFO); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + + } // for + } + catch (Exception ex) + { + log.error("Unable to parse an element in Entry: " + ex.getMessage()); + ex.printStackTrace(); + throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); + } + + return result; + } + + public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) + throws UnmarshallException + { + + SwordValidationInfo result = unmarshallWithoutValidate(entry, validationProperties); + if ( validationProperties != null ) + { + result = validate(result, validationProperties); + } + return result; + } + + /** + * + */ + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, validationContext); + } + + /** + * + * @param info add results to this. If null, a new one is created. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + protected SwordValidationInfo validate(SwordValidationInfo info, + Properties validationContext) + { + // determine if a full validation is required + boolean validateAll = (info == null); + + SwordValidationInfo result = info; + if ( result == null ) + { + result = new SwordValidationInfo(xmlName); + } + + // id, title an updated are required + if ( id == null ) + { + result.addValidationInfo(new SwordValidationInfo(Id.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR, + SwordValidationInfoType.ERROR)); + } + else if ( id != null && validateAll ) + { + result.addValidationInfo(id.validate(validationContext)); + } + + if ( title == null ) + { + result.addValidationInfo(new SwordValidationInfo(Title.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR, + SwordValidationInfoType.ERROR)); + } + else if ( title != null && validateAll ) + { + result.addValidationInfo(title.validate(validationContext)); + } + + if ( updated == null ) + { + result.addValidationInfo(new SwordValidationInfo(Updated.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR, + SwordValidationInfoType.ERROR)); + } + else if ( updated != null && validateAll ) + { + result.addValidationInfo(updated.validate(validationContext)); + } + + // additional sword requirements on the element + if ( contributors.isEmpty() ) + { + String contributor = validationContext.getProperty(HttpHeaders.X_ON_BEHALF_OF); + if ( contributor != null ) + { + result.addValidationInfo(new SwordValidationInfo(Contributor.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR + + " This item SHOULD contain the value of the X-On-Behalf-Of header, if one was present in the POST request.", + SwordValidationInfoType.ERROR)); + } + } + else if ( (! contributors.isEmpty()) && validateAll ) + { + Iterator iterator = contributors.iterator(); + while ( iterator.hasNext() ) + { + Contributor contributor = iterator.next(); + result.addValidationInfo(contributor.validate(validationContext)); + } + } + + if ( generator == null ) + { + result.addValidationInfo(new SwordValidationInfo(Generator.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR + + " SHOULD contain the URI and version of the server software.", + SwordValidationInfoType.ERROR)); + } + else if ( generator != null && validateAll ) + { + result.addValidationInfo(generator.validate(validationContext)); + } + + if ( validateAll ) + { + // process the remaining items + Iterator linksIterator = links.iterator(); + while ( linksIterator.hasNext() ) + { + Link link = linksIterator.next(); + result.addValidationInfo(link.validate(validationContext)); + } + + Iterator authorIterator = authors.iterator(); + while ( authorIterator.hasNext() ) + { + Author author = authorIterator.next(); + result.addValidationInfo(author.validate(validationContext)); + } + + if ( content != null ) + { + result.addValidationInfo(content.validate(validationContext)); + } + + if ( published != null ) + { + result.addValidationInfo(published.validate(validationContext)); + } + + if ( rights != null ) + { + result.addValidationInfo(rights.validate(validationContext)); + } + + if ( summary != null ) + { + result.addValidationInfo(summary.validate(validationContext)); + } + + Iterator categoryIterator = categories.iterator(); + while ( categoryIterator.hasNext() ) + { + Category category = categoryIterator.next(); + result.addValidationInfo(category.validate(validationContext)); + } + + } + + return result; + } + + /** + * Get an iterator for the authors in the Entry. + * + * @return An iterator. + */ + public Iterator getAuthors() + { + return authors.iterator(); + } + + /** + * Add an author to the Entry. + * + * @param author The author to add. + */ + public void addAuthors(Author author) + { + this.authors.add(author); + } + + /** + * Clear the list of authors. + */ + public void clearAuthors() + { + this.authors.clear(); + } + + /** + * Get an iterator for the categories in this Entry. + * + * @return An iterator. + */ + public Iterator getCategories() { + ArrayList items = new ArrayList(); + for ( int i = 0; i < categories.size(); i++ ) + { + items.add(categories.get(i).getContent()); + } + + return items.iterator(); + } + + /** + * Add a category. + * + * @param category the category to add. + */ + public void addCategory(String category) { + this.categories.add(new Category(category)); + } + + /** + * Clear the list of categories. + */ + public void clearCategories() + { + this.categories.clear(); + } + + /** + * Get the content element for this Entry. + * + * @return The content element. + */ + public Content getContent() + { + return content; + } + + /** + * Set the content element for this Entry. + * + * @param content + * content element to set + */ + public void setContent(Content content) + { + this.content = content; + } + + /** + * Get the generator for this Entry. + * + * @return The generator element. + */ + public Generator getGenerator() + { + return generator; + } + + /** + * Set the generator for this Entry. + * + * @param generator + * generator element to set + */ + public void setGenerator(Generator generator) + { + this.generator = generator; + } + + /** + * Get a list of contributors. + * + * @return An iterator. + */ + public Iterator getContributors() { + return contributors.iterator(); + } + + /** + * Add a contributor. + * + * @param contributor The contributor. + */ + public void addContributor(Contributor contributor) + { + this.contributors.add(contributor); + } + + /** + * Clear the list of contributors. + */ + public void clearContributors() + { + this.contributors.clear(); + } + + /** + * Get the ID for this Entry. + * + * @return The ID. + */ + public String getId() + { + if ( id == null ) + { + return null; + } + return id.getContent(); + } + + /** + * Set the ID for this Entry. + * + * @param id The ID. + */ + public void setId(String id) + { + this.id = new Id(id); + } + + /** + * Get the list of links for this Entry. + * + * @return An iterator. + */ + public Iterator getLinks() + { + return links.iterator(); + } + + /** + * Get the link for this Entry. + * + * @param link The link. + */ + public void addLink(Link link) + { + this.links.add(link); + } + + /** + * Clear the list of links. + */ + public void clearLinks() + { + this.links.clear(); + } + + /** + * Get the published date, expressed as a String. + * + * @return The date. + */ + public String getPublished() + { + if ( published == null ) + { + return null; + } + return published.getContent(); + } + + /** + * Set the published date. The date should be in one of the + * supported formats. This method will not check that the string + * is in the correct format. + * + * @param published The string. + */ + public void setPublished(String published) + { + this.published = new Published(published); + } + + /** + * Get the rights for this Entry. + * @return The rights. + */ + public Rights getRights() { + return rights; + } + + /** + * Set the rights for this Entry. + * + * @param rights The rights. + */ + public void setRights(Rights rights) { + this.rights = rights; + } + + /** + * Get the source for this Entry. + * @return The source. + * @deprecated + */ + @Deprecated + public Source getSource() { + return source; + } + + /** + * Set the source for this entry. + * + * @param source The source. + * @deprecated + */ + @Deprecated + public void setSource(Source source) + { + this.source = source; + } + + /** + * Get the summary. + * + * @return The summary. + */ + public Summary getSummary() + { + return summary; + } + + /** + * Set the summary. + * + * @param summary The summary. + */ + public void setSummary(Summary summary) + { + this.summary = summary; + } + + /** + * Get the title. + * + * @return The title. + */ + public Title getTitle() + { + return title; + } + + /** + * Set the title. + * + * @param title The title. + */ + public void setTitle(Title title) + { + this.title = title; + } + + /** + * Get the updated date, expressed as a String. See + * org.purl.sword.XmlElement.stringToDate for the + * list of supported formats. This particular method + * will not check if the date is formatted correctly. + * + * @return The date. + */ + public String getUpdated() + { + if ( updated == null ) + { + return null; + } + return updated.getContent(); + } + + /** + * Set the updated date. The date should match one of the + * supported formats. This method will not check the format of the + * string. + * + * @param updated The string. + * @see Entry#setPublished(String) setPublished + */ + public void setUpdated(String updated) + { + this.updated = new Updated(updated); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Generator.java b/dspace-sword/src/main/java/org/purl/sword/atom/Generator.java index c1aded3dfd..ecd2ca3d2c 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Generator.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Generator.java @@ -30,319 +30,321 @@ import org.purl.sword.base.XmlName; */ public class Generator extends XmlElement implements SwordElementInterface { - /** - * Label for the URI attribute. - */ - public static final String ATTRIBUTE_URI = "uri"; - - /** - * Label for the version attribute. - */ - public static final String ATTRIBUTE_VERSION = "version"; - - /** - * Local name for the element. - */ - @Deprecated - public static final String ELEMENT_NAME = "generator"; - - /** - * The content for the element. - */ - private String content; - - /** - * The URI attribute. - */ - private String uri; - - /** - * The version attribute. - */ - private String version; - - /** - * The logger. - */ - private static Logger log = Logger.getLogger(Generator.class); - - /** - * The Xml name details for the element. - */ - private static final XmlName XML_NAME = new XmlName( - Namespaces.PREFIX_ATOM, "generator", Namespaces.NS_ATOM); - - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'generator'. - */ - public Generator() - { - super(XML_NAME); - initialise(); - } - - public static XmlName elementName() - { - return XML_NAME; - } - - protected final void initialise() - { - content = null; - version = null; - uri = null; - } - - /** - * Marshal the data in the object to an Element object. - * - * @return The element. - */ - public Element marshall() - { - Element element = new Element(getQualifiedName(), xmlName.getNamespace()); - - if( content != null ) - { - element.appendChild(content); - } - - if( uri != null ) - { - Attribute uriAttribute = new Attribute(ATTRIBUTE_URI, uri); - element.addAttribute(uriAttribute); - } - - if( version != null ) - { - Attribute versionAttribute = new Attribute(ATTRIBUTE_VERSION, version); - element.addAttribute(versionAttribute); - } - - - return element; - } - - /** - * Unmarshal the specified Generator element into the data in this object. - * - * @param generator The generator element. - * - * @throws UnmarshallException If the specified element is not an atom:generator - * element, or if there is an error accessing the data. - */ - public void unmarshall(Element generator) - throws UnmarshallException - { - unmarshall(generator, null); - } - - public SwordValidationInfo unmarshall(Element generator, Properties validationProperties) - throws UnmarshallException - { - if( ! isInstanceOf(generator, xmlName)) - { - return handleIncorrectElement(generator, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeValidationItems = new ArrayList(); - - try - { - initialise(); - - // get the attributes - int attributeCount = generator.getAttributeCount(); - Attribute attribute = null; - for( int i = 0; i < attributeCount; i++ ) - { - attribute = generator.getAttribute(i); - if( ATTRIBUTE_URI.equals(attribute.getQualifiedName())) + /** + * Label for the URI attribute. + */ + public static final String ATTRIBUTE_URI = "uri"; + + /** + * Label for the version attribute. + */ + public static final String ATTRIBUTE_VERSION = "version"; + + /** + * Local name for the element. + */ + @Deprecated + public static final String ELEMENT_NAME = "generator"; + + /** + * The content for the element. + */ + private String content; + + /** + * The URI attribute. + */ + private String uri; + + /** + * The version attribute. + */ + private String version; + + /** + * The logger. + */ + private static Logger log = Logger.getLogger(Generator.class); + + /** + * The Xml name details for the element. + */ + private static final XmlName XML_NAME = new XmlName( + Namespaces.PREFIX_ATOM, "generator", Namespaces.NS_ATOM); + + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'generator'. + */ + public Generator() + { + super(XML_NAME); + initialise(); + } + + public static XmlName elementName() + { + return XML_NAME; + } + + protected final void initialise() + { + content = null; + version = null; + uri = null; + } + + /** + * Marshal the data in the object to an Element object. + * + * @return The element. + */ + public Element marshall() + { + Element element = new Element(getQualifiedName(), xmlName.getNamespace()); + + if ( content != null ) + { + element.appendChild(content); + } + + if ( uri != null ) + { + Attribute uriAttribute = new Attribute(ATTRIBUTE_URI, uri); + element.addAttribute(uriAttribute); + } + + if ( version != null ) + { + Attribute versionAttribute = new Attribute(ATTRIBUTE_VERSION, version); + element.addAttribute(versionAttribute); + } + + + return element; + } + + /** + * Unmarshal the specified Generator element into the data in this object. + * + * @param generator The generator element. + * + * @throws UnmarshallException If the specified element is not an atom:generator + * element, or if there is an error accessing the data. + */ + public void unmarshall(Element generator) + throws UnmarshallException + { + unmarshall(generator, null); + } + + public SwordValidationInfo unmarshall(Element generator, Properties validationProperties) + throws UnmarshallException + { + if ( ! isInstanceOf(generator, xmlName)) + { + return handleIncorrectElement(generator, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeValidationItems = new ArrayList(); + + try + { + initialise(); + + // get the attributes + int attributeCount = generator.getAttributeCount(); + Attribute attribute = null; + for ( int i = 0; i < attributeCount; i++ ) { - uri = attribute.getValue(); - - XmlName uriName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_URI, Namespaces.NS_ATOM); - SwordValidationInfo info = new SwordValidationInfo(xmlName, uriName); - info.setContentDescription(uri); - attributeValidationItems.add(info); - - } - else if( ATTRIBUTE_VERSION.equals(attribute.getQualifiedName())) - { - version = attribute.getValue(); - XmlName versionName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_VERSION, Namespaces.NS_ATOM); - SwordValidationInfo info = new SwordValidationInfo(xmlName, versionName); - info.setContentDescription(version); - attributeValidationItems.add(info); - } - else - { - XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), - attribute.getLocalName(), - attribute.getNamespaceURI()); - - SwordValidationInfo info = new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO); - info.setContentDescription(attribute.getValue()); - validationItems.add(info); - } - - } - - int length = generator.getChildCount(); - if( length > 0 ) - { - content = unmarshallString(generator); - } - } - catch( Exception ex ) - { - log.error("Unable to parse an element in Generator: " + ex.getMessage()); - throw new UnmarshallException("Unable to parse element in Generator", ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeValidationItems, validationProperties); - } - return result; - } - - /** - * - */ - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - /** - * - * @param existing - * @param attributeItems - */ - public SwordValidationInfo validate(List existing, - List attributeItems, - Properties validationContext) - { - boolean validateAll = (existing == null); - - SwordValidationInfo result = new SwordValidationInfo(xmlName); - result.setContentDescription(content); - - XmlName attributeName; - - if( content == null ) - { - result.addValidationInfo( - new SwordValidationInfo(xmlName, - SwordValidationInfo.MISSING_CONTENT, - SwordValidationInfoType.WARNING)); - } - - - if( uri == null ) - { - attributeName = new XmlName(Namespaces.PREFIX_ATOM, - ATTRIBUTE_URI, - Namespaces.NS_ATOM); - - result.addAttributeValidationInfo( - new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, - SwordValidationInfoType.WARNING)); - } - else if( validateAll && uri != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_URI, uri)); - } - - if( version == null ) - { - attributeName = new XmlName(Namespaces.PREFIX_ATOM, - ATTRIBUTE_VERSION, - Namespaces.NS_ATOM); - - result.addAttributeValidationInfo( - new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, - SwordValidationInfoType.WARNING)); - } - else if( validateAll && version != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_VERSION, version)); - } - - result.addUnmarshallValidationInfo(existing, attributeItems); - return result; - } - - /** - * Get the content. - * - * @return The content. - */ - public String getContent() { - return content; - } - - /** - * Set the content. - * - * @param content The content. - */ - public void setContent(String content) { - this.content = content; - } - - /** - * Get the URI. - * - * @return The URI. - */ - public String getUri() { - return uri; - } - - /** - * Set the URI. - * - * @param uri The URI. - */ - public void setUri(String uri) { - this.uri = uri; - } - - /** - * Get the version. - * - * @return The version. - */ - public String getVersion() { - return version; - } - - /** - * Set the version. - * - * @param version The version. - */ - public void setVersion(String version) { - this.version = version; - } + attribute = generator.getAttribute(i); + if ( ATTRIBUTE_URI.equals(attribute.getQualifiedName())) + { + uri = attribute.getValue(); - /** - * Get a string representation. - */ - public String toString() - { - return "Generator - content: " + getContent() + - " version: " + getVersion() + - " uri: " + getUri(); - } - + XmlName uriName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_URI, Namespaces.NS_ATOM); + SwordValidationInfo info = new SwordValidationInfo(xmlName, uriName); + info.setContentDescription(uri); + attributeValidationItems.add(info); + } + else if ( ATTRIBUTE_VERSION.equals(attribute.getQualifiedName())) + { + version = attribute.getValue(); + XmlName versionName = new XmlName(Namespaces.PREFIX_ATOM, ATTRIBUTE_VERSION, Namespaces.NS_ATOM); + SwordValidationInfo info = new SwordValidationInfo(xmlName, versionName); + info.setContentDescription(version); + attributeValidationItems.add(info); + } + else + { + XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), + attribute.getLocalName(), + attribute.getNamespaceURI()); + + SwordValidationInfo info = new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO); + info.setContentDescription(attribute.getValue()); + validationItems.add(info); + } + } + + int length = generator.getChildCount(); + if ( length > 0 ) + { + content = unmarshallString(generator); + } + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in Generator: " + ex.getMessage()); + throw new UnmarshallException("Unable to parse element in Generator", ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeValidationItems, validationProperties); + } + return result; + } + + /** + * + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info. + */ + @Override + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + /** + * + * @param existing add results to this. + * @param attributeItems add these too. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + public SwordValidationInfo validate(List existing, + List attributeItems, + Properties validationContext) + { + boolean validateAll = (existing == null); + + SwordValidationInfo result = new SwordValidationInfo(xmlName); + result.setContentDescription(content); + + XmlName attributeName; + + if ( content == null ) + { + result.addValidationInfo( + new SwordValidationInfo(xmlName, + SwordValidationInfo.MISSING_CONTENT, + SwordValidationInfoType.WARNING)); + } + + + if ( uri == null ) + { + attributeName = new XmlName(Namespaces.PREFIX_ATOM, + ATTRIBUTE_URI, + Namespaces.NS_ATOM); + + result.addAttributeValidationInfo( + new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, + SwordValidationInfoType.WARNING)); + } + else if ( validateAll && uri != null ) + { + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_URI, uri)); + } + + if ( version == null ) + { + attributeName = new XmlName(Namespaces.PREFIX_ATOM, + ATTRIBUTE_VERSION, + Namespaces.NS_ATOM); + + result.addAttributeValidationInfo( + new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, + SwordValidationInfoType.WARNING)); + } + else if ( validateAll && version != null ) + { + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_VERSION, version)); + } + + result.addUnmarshallValidationInfo(existing, attributeItems); + return result; + } + + /** + * Get the content. + * + * @return The content. + */ + public String getContent() { + return content; + } + + /** + * Set the content. + * + * @param content The content. + */ + public void setContent(String content) { + this.content = content; + } + + /** + * Get the URI. + * + * @return The URI. + */ + public String getUri() { + return uri; + } + + /** + * Set the URI. + * + * @param uri The URI. + */ + public void setUri(String uri) { + this.uri = uri; + } + + /** + * Get the version. + * + * @return The version. + */ + public String getVersion() { + return version; + } + + /** + * Set the version. + * + * @param version The version. + */ + public void setVersion(String version) { + this.version = version; + } + + /** + * Get a string representation. + */ + public String toString() + { + return "Generator - content: " + getContent() + + " version: " + getVersion() + + " uri: " + getUri(); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/InvalidMediaTypeException.java b/dspace-sword/src/main/java/org/purl/sword/atom/InvalidMediaTypeException.java index e37b5cc444..bac22e550a 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/InvalidMediaTypeException.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/InvalidMediaTypeException.java @@ -14,13 +14,13 @@ package org.purl.sword.atom; */ public class InvalidMediaTypeException extends Exception { - /** - * Create a new instance and store the message. - * - * @param message The exception's message. - */ - public InvalidMediaTypeException( String message ) - { - super(message); - } + /** + * Create a new instance and store the message. + * + * @param message The exception's message. + */ + public InvalidMediaTypeException( String message ) + { + super(message); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Link.java b/dspace-sword/src/main/java/org/purl/sword/atom/Link.java index 2ce39bb69c..46056c4e84 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Link.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Link.java @@ -29,470 +29,470 @@ import org.purl.sword.base.XmlName; */ public class Link extends XmlElement implements SwordElementInterface { - /** - * Label for the href attribute. - */ - public static final String ATTRIBUTE_HREF = "href"; + /** + * Label for the href attribute. + */ + public static final String ATTRIBUTE_HREF = "href"; - /** - * Label for the rel attribute. - */ - public static final String ATTRIBUTE_REL = "rel"; + /** + * Label for the rel attribute. + */ + public static final String ATTRIBUTE_REL = "rel"; - /** - * Label for the type attribute. - */ - public static final String ATTRIBUTE_TYPE = "type"; + /** + * Label for the type attribute. + */ + public static final String ATTRIBUTE_TYPE = "type"; - /** - * Label for the hreflang attribute. - */ - public static final String ATTRIBUTE_HREF_LANG = "hreflang"; + /** + * Label for the hreflang attribute. + */ + public static final String ATTRIBUTE_HREF_LANG = "hreflang"; - /** - * Label for the title attribute. - */ - public static final String ATTRIBUTE_TITLE = "title"; + /** + * Label for the title attribute. + */ + public static final String ATTRIBUTE_TITLE = "title"; /** * Label for the length attribute. */ public static final String ATTRIBUTE_LENGTH = "length"; - - /** - * Local name for the element. - */ - @Deprecated - public static final String ELEMENT_NAME = "link"; + + /** + * Local name for the element. + */ + @Deprecated + public static final String ELEMENT_NAME = "link"; + + /** + * Stores the href. + */ + private String href; + + /** + * Stores the Rel attribute. + */ + private String rel; + + /** + * Stores the type. + */ + private String type; + + /** + * Stores the HREF lang. + */ + private String hreflang; + + /** + * Stores the title. + */ + private String title; + + /** + * Stores the length. + */ + private String length; + + /** + * Stores the content. + */ + private String content; + + /** + * The logger. + */ + private static Logger log = Logger.getLogger(Link.class); + + private static final XmlName XML_NAME = new XmlName( + Namespaces.PREFIX_ATOM, "link", Namespaces.NS_ATOM); + + /** + * Create a new instance and set prefix and local name to 'atom' and 'link', + * respectively. + */ + public Link() + { + super(XML_NAME); + } + + public static XmlName elementName() + { + return XML_NAME; + } + + /** + * Mashall the data stored in this object into Element objects. + * + * @return An element that holds the data associated with this object. + */ + public Element marshall() + { + Element element = new Element(getQualifiedName(), xmlName.getNamespace()); + + if ( content != null ) + { + element.appendChild(content); + } + + if ( href != null ) + { + Attribute hrefAttribute = new Attribute(ATTRIBUTE_HREF, href); + element.addAttribute(hrefAttribute); + } + + if ( rel != null ) + { + Attribute relAttribute = new Attribute(ATTRIBUTE_REL, rel); + element.addAttribute(relAttribute); + } + + if ( type != null ) + { + Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type); + element.addAttribute(typeAttribute); + } + + if ( hreflang != null ) + { + Attribute hreflangAttribute = new Attribute(ATTRIBUTE_HREF_LANG, hreflang); + element.addAttribute(hreflangAttribute); + } + + if ( title != null ) + { + Attribute titleAttribute = new Attribute(ATTRIBUTE_TITLE, title); + element.addAttribute(titleAttribute); + } + + if ( length != null ) + { + Attribute lengthAttribute = new Attribute(ATTRIBUTE_LENGTH, length); + element.addAttribute(lengthAttribute); + } + + return element; + } + + /** + * Unmarshall the contents of the Link element into the internal data objects + * in this object. + * + * @param link The Link element to process. + * + * @throws UnmarshallException If the element does not contain an ATOM link + * element, or if there is a problem processing the element or any + * subelements. + */ + public void unmarshall(Element link) + throws UnmarshallException + { + unmarshall(link, null); + } + + + public SwordValidationInfo unmarshall(Element link, Properties validationProperties) + throws UnmarshallException + { + if ( ! isInstanceOf(link, xmlName) ) + { + return handleIncorrectElement(link, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeItems = new ArrayList(); + + try + { + // get the attributes + int attributeCount = link.getAttributeCount(); + Attribute attribute = null; + for ( int i = 0; i < attributeCount; i++ ) + { + attribute = link.getAttribute(i); + if ( ATTRIBUTE_HREF.equals(attribute.getQualifiedName())) + { + href = attribute.getValue(); + if ( validationProperties != null) + { + attributeItems.add(createValidAttributeInfo(ATTRIBUTE_HREF, href)); + } + } + else if ( ATTRIBUTE_REL.equals(attribute.getQualifiedName())) + { + rel = attribute.getValue(); + if ( validationProperties != null) + { + attributeItems.add(createValidAttributeInfo(ATTRIBUTE_REL, rel)); + } + } + else if ( ATTRIBUTE_TYPE.equals(attribute.getQualifiedName())) + { + type = attribute.getValue(); + if ( validationProperties != null) + { + attributeItems.add(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); + } + } + else if ( ATTRIBUTE_HREF_LANG.equals(attribute.getQualifiedName())) + { + hreflang = attribute.getValue(); + if ( validationProperties != null) + { + attributeItems.add(createValidAttributeInfo(ATTRIBUTE_HREF_LANG, hreflang)); + } + } + else if ( ATTRIBUTE_TITLE.equals(attribute.getQualifiedName())) + { + title = attribute.getValue(); + if ( validationProperties != null) + { + attributeItems.add(createValidAttributeInfo(ATTRIBUTE_TITLE, title)); + } + } + else if ( ATTRIBUTE_LENGTH.equals(attribute.getQualifiedName())) + { + length = attribute.getValue(); + if ( validationProperties != null) + { + attributeItems.add(createValidAttributeInfo(ATTRIBUTE_LENGTH, length)); + } + } + else + { + XmlName attributeName = new XmlName(attribute); - /** - * Stores the href. - */ - private String href; - - /** - * Stores the Rel attribute. - */ - private String rel; - - /** - * Stores the type. - */ - private String type; - - /** - * Stores the HREF lang. - */ - private String hreflang; - - /** - * Stores the title. - */ - private String title; - - /** - * Stores the length. - */ - private String length; - - /** - * Stores the content. - */ - private String content; - - /** - * The logger. - */ - private static Logger log = Logger.getLogger(Link.class); - - private static final XmlName XML_NAME = new XmlName( - Namespaces.PREFIX_ATOM, "link", Namespaces.NS_ATOM); - - /** - * Create a new instance and set prefix and local name to 'atom' and 'link', - * respectively. - */ - public Link() - { - super(XML_NAME); - } - - public static XmlName elementName() - { - return XML_NAME; - } - - /** - * Mashall the data stored in this object into Element objects. - * - * @return An element that holds the data associated with this object. - */ - public Element marshall() - { - Element element = new Element(getQualifiedName(), xmlName.getNamespace()); - - if( content != null ) - { - element.appendChild(content); - } - - if( href != null ) - { - Attribute hrefAttribute = new Attribute(ATTRIBUTE_HREF, href); - element.addAttribute(hrefAttribute); - } - - if( rel != null ) - { - Attribute relAttribute = new Attribute(ATTRIBUTE_REL, rel); - element.addAttribute(relAttribute); - } - - if( type != null ) - { - Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type); - element.addAttribute(typeAttribute); - } - - if( hreflang != null ) - { - Attribute hreflangAttribute = new Attribute(ATTRIBUTE_HREF_LANG, hreflang); - element.addAttribute(hreflangAttribute); - } - - if( title != null ) - { - Attribute titleAttribute = new Attribute(ATTRIBUTE_TITLE, title); - element.addAttribute(titleAttribute); - } - - if( length != null ) - { - Attribute lengthAttribute = new Attribute(ATTRIBUTE_LENGTH, length); - element.addAttribute(lengthAttribute); - } - - return element; - } - - /** - * Unmarshall the contents of the Link element into the internal data objects - * in this object. - * - * @param link The Link element to process. - * - * @throws UnmarshallException If the element does not contain an ATOM link - * element, or if there is a problem processing the element or any - * subelements. - */ - public void unmarshall(Element link) - throws UnmarshallException - { - unmarshall(link, null); - } - - - public SwordValidationInfo unmarshall(Element link, Properties validationProperties) - throws UnmarshallException - { - if( ! isInstanceOf(link, xmlName) ) - { - return handleIncorrectElement(link, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeItems = new ArrayList(); - - try - { - // get the attributes - int attributeCount = link.getAttributeCount(); - Attribute attribute = null; - for( int i = 0; i < attributeCount; i++ ) - { - attribute = link.getAttribute(i); - if( ATTRIBUTE_HREF.equals(attribute.getQualifiedName())) - { - href = attribute.getValue(); - if( validationProperties != null) - { - attributeItems.add(createValidAttributeInfo(ATTRIBUTE_HREF, href)); - } + SwordValidationInfo unknown = new SwordValidationInfo(xmlName, + attributeName, + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO); + unknown.setContentDescription(attribute.getValue()); + attributeItems.add(unknown); + } } - else if( ATTRIBUTE_REL.equals(attribute.getQualifiedName())) + + if ( link.getChildCount() > 0 ) { - rel = attribute.getValue(); - if( validationProperties != null) - { - attributeItems.add(createValidAttributeInfo(ATTRIBUTE_REL, rel)); - } + SwordValidationInfo content = new SwordValidationInfo(xmlName, + "This element has content, but it is not used by SWORD", + SwordValidationInfoType.INFO); + validationItems.add(content); } - else if( ATTRIBUTE_TYPE.equals(attribute.getQualifiedName())) + + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in Link: " + ex.getMessage()); + throw new UnmarshallException("Unable to parse element in link", ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeItems, validationProperties); + } + return result; + } + + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + public SwordValidationInfo validate(List elements, + List attributes, + Properties validationContext) + { + boolean validateAll = (elements == null); + + SwordValidationInfo result = new SwordValidationInfo(xmlName); + + if ( href == null ) + { + XmlName attributeName = new XmlName(xmlName.getPrefix(), + ATTRIBUTE_HREF, + xmlName.getNamespace()); + + SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, + SwordValidationInfoType.ERROR); + result.addAttributeValidationInfo(item); + } + + if ( validateAll ) + { + if ( href != null ) { - type = attribute.getValue(); - if( validationProperties != null) - { - attributeItems.add(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); - } + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF, href)); } - else if( ATTRIBUTE_HREF_LANG.equals(attribute.getQualifiedName())) + + if ( rel != null ) { - hreflang = attribute.getValue(); - if( validationProperties != null) - { - attributeItems.add(createValidAttributeInfo(ATTRIBUTE_HREF_LANG, hreflang)); - } + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_REL, rel)); } - else if( ATTRIBUTE_TITLE.equals(attribute.getQualifiedName())) + + if ( type != null ) { - title = attribute.getValue(); - if( validationProperties != null) - { - attributeItems.add(createValidAttributeInfo(ATTRIBUTE_TITLE, title)); - } + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); } - else if( ATTRIBUTE_LENGTH.equals(attribute.getQualifiedName())) + + if ( hreflang != null ) { - length = attribute.getValue(); - if( validationProperties != null) - { - attributeItems.add(createValidAttributeInfo(ATTRIBUTE_LENGTH, length)); - } + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF_LANG, hreflang)); } - else + + if ( title != null ) { - XmlName attributeName = new XmlName(attribute); - - SwordValidationInfo unknown = new SwordValidationInfo(xmlName, - attributeName, - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO); - unknown.setContentDescription(attribute.getValue()); - attributeItems.add(unknown); + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_TITLE, title)); } - } - - if( link.getChildCount() > 0 ) - { - SwordValidationInfo content = new SwordValidationInfo(xmlName, - "This element has content, but it is not used by SWORD", - SwordValidationInfoType.INFO); - validationItems.add(content); - } - - } - catch( Exception ex ) - { - log.error("Unable to parse an element in Link: " + ex.getMessage()); - throw new UnmarshallException("Unable to parse element in link", ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeItems, validationProperties); - } - return result; - } - - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - public SwordValidationInfo validate(List elements, - List attributes, - Properties validationContext) - { - boolean validateAll = (elements == null); - - SwordValidationInfo result = new SwordValidationInfo(xmlName); - - if( href == null ) - { - XmlName attributeName = new XmlName(xmlName.getPrefix(), - ATTRIBUTE_HREF, - xmlName.getNamespace()); - - SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, - SwordValidationInfoType.ERROR); - result.addAttributeValidationInfo(item); - } - - if( validateAll ) - { - if( href != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF, href)); - } - - if( rel != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_REL, rel)); - } - - if( type != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_TYPE, type)); - } - - if( hreflang != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF_LANG, hreflang)); - } - - if( title != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_TITLE, title)); - } - - if( length != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_LENGTH, length)); - } - - } - - result.addUnmarshallValidationInfo(elements, attributes); - return result; - } - - /** - * Get the HREF attribute. - * - * @return The HREF. - */ - public String getHref() { - return href; - } - - /** - * Set the HREF attribute. - * - * @param href The href. - */ - public void setHref(String href) { - this.href = href; - } - - /** - * Get the Rel attribute. - * - * @return The Rel. - */ - public String getRel() { - return rel; - } - - /** - * Set the Rel attribute. - * - * @param rel The Rel. - */ - public void setRel(String rel) { - this.rel = rel; - } - - /** - * Get the type. - * - * @return The type. - */ - public String getType() { - return type; - } - - /** - * Set the type. - * @param type The type. - */ - public void setType(String type) { - this.type = type; - } - - /** - * Get the HREF Lang attribute. - * - * @return The HREF Lang. - */ - public String getHreflang() { - return hreflang; - } - - /** - * Set the HREF Lang attribute. - * - * @param hreflang The HREF Lang. - */ - public void setHreflang(String hreflang) { - this.hreflang = hreflang; - } - - /** - * Get the title. - * - * @return The title. - */ - public String getTitle() { - return title; - } - - /** - * Set the title. - * - * @param title The title. - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * Get the length. - * - * @return The length. - */ - public String getLength() { - return length; - } - - /** - * Set the length. - * - * @param length The length. - */ - public void setLength(String length) { - this.length = length; - } - - /** - * Get the content. - * - * @return The content. - */ - public String getContent() { - return content; - } - - /** - * Set the content. - * - * @param content The content. - */ - public void setContent(String content) { - this.content = content; - } - - public String toString() - { - return "Link -" + - " href: " + getHref() + - " hreflang: " + getHreflang() + - " title: " + getTitle() + - " rel: " + getRel() + - " content: " + getContent() + - " type: " + getType() + - " length: " + getLength(); - } + + if ( length != null ) + { + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_LENGTH, length)); + } + + } + + result.addUnmarshallValidationInfo(elements, attributes); + return result; + } + + /** + * Get the HREF attribute. + * + * @return The HREF. + */ + public String getHref() { + return href; + } + + /** + * Set the HREF attribute. + * + * @param href The href. + */ + public void setHref(String href) { + this.href = href; + } + + /** + * Get the Rel attribute. + * + * @return The Rel. + */ + public String getRel() { + return rel; + } + + /** + * Set the Rel attribute. + * + * @param rel The Rel. + */ + public void setRel(String rel) { + this.rel = rel; + } + + /** + * Get the type. + * + * @return The type. + */ + public String getType() { + return type; + } + + /** + * Set the type. + * @param type The type. + */ + public void setType(String type) { + this.type = type; + } + + /** + * Get the HREF Lang attribute. + * + * @return The HREF Lang. + */ + public String getHreflang() { + return hreflang; + } + + /** + * Set the HREF Lang attribute. + * + * @param hreflang The HREF Lang. + */ + public void setHreflang(String hreflang) { + this.hreflang = hreflang; + } + + /** + * Get the title. + * + * @return The title. + */ + public String getTitle() { + return title; + } + + /** + * Set the title. + * + * @param title The title. + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * Get the length. + * + * @return The length. + */ + public String getLength() { + return length; + } + + /** + * Set the length. + * + * @param length The length. + */ + public void setLength(String length) { + this.length = length; + } + + /** + * Get the content. + * + * @return The content. + */ + public String getContent() { + return content; + } + + /** + * Set the content. + * + * @param content The content. + */ + public void setContent(String content) { + this.content = content; + } + + public String toString() + { + return "Link -" + + " href: " + getHref() + + " hreflang: " + getHreflang() + + " title: " + getTitle() + + " rel: " + getRel() + + " content: " + getContent() + + " type: " + getType() + + " length: " + getLength(); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Rights.java b/dspace-sword/src/main/java/org/purl/sword/atom/Rights.java index f95eb939bd..a3bbdfa508 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Rights.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Rights.java @@ -18,26 +18,26 @@ import org.purl.sword.base.XmlName; */ public class Rights extends TextConstruct { - /** - * Local name for the element. - */ - private static final XmlName XML_NAME = new XmlName( - Namespaces.PREFIX_ATOM, "rights", Namespaces.NS_ATOM); - - - - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'rights'. - */ - public Rights() - { - super(XML_NAME); - } - - public static XmlName elementName() - { - return XML_NAME; - } + /** + * Local name for the element. + */ + private static final XmlName XML_NAME = new XmlName( + Namespaces.PREFIX_ATOM, "rights", Namespaces.NS_ATOM); + + + + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'rights'. + */ + public Rights() + { + super(XML_NAME); + } + + public static XmlName elementName() + { + return XML_NAME; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Source.java b/dspace-sword/src/main/java/org/purl/sword/atom/Source.java index 9821f1a88c..c1a6ab8387 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Source.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Source.java @@ -29,163 +29,164 @@ import org.purl.sword.base.SwordValidationInfoType; */ public class Source extends XmlElement implements SwordElementInterface { - /** - * Local name for the element. - */ - private static final XmlName XML_NAME = new XmlName( - Namespaces.PREFIX_ATOM, "source", Namespaces.NS_ATOM); - - /** - * The generator data for this object. - */ - private Generator generator; - - /** - * The log. - */ - private static Logger log = Logger.getLogger(Source.class); - - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'source'. - */ - public Source() - { - super(XML_NAME); - } - - public static XmlName elementName() - { - return XML_NAME; - } - - /** - * Marshal the data stored in this object into Element objects. - * - * @return An element that holds the data associated with this object. - */ - public Element marshall() - { - Element source = new Element(getQualifiedName(), xmlName.getNamespace()); - - if( generator != null ) - { - source.appendChild(generator.marshall()); - } - - return source; - } - - /** - * Unmarshal the contents of the source element into the internal data objects - * in this object. - * - * @param source The Source element to process. - * - * @throws UnmarshallException If the element does not contain an ATOM Source - * element, or if there is a problem processing the element or any - * sub-elements. - */ - public void unmarshall(Element source) - throws UnmarshallException - { - unmarshall(source, null); - } - - /** - * - * @param source - * @param validationProperties - * @throws org.purl.sword.base.UnmarshallException - */ - public SwordValidationInfo unmarshall(Element source, Properties validationProperties) - throws UnmarshallException - { - if( ! isInstanceOf(source, xmlName.getLocalName(), Namespaces.NS_ATOM)) - { - //throw new UnmarshallException( "Not an atom:source element" ); - return handleIncorrectElement(source, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeItems = new ArrayList(); - - try - { - processUnexpectedAttributes(source, attributeItems); - - // retrieve all of the sub-elements - Elements elements = source.getChildElements(); - Element element = null; - int length = elements.size(); - - for(int i = 0; i < length; i++ ) - { - element = elements.get(i); - if( isInstanceOf(element, Generator.elementName()) ) - { - generator = new Generator(); - generator.unmarshall(element); - } - else - { - SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), - SwordValidationInfo.UNKNOWN_ELEMENT, - SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } - } - } - catch( Exception ex ) - { - log.error("Unable to parse an element in Source: " + ex.getMessage()); - throw new UnmarshallException("Unable to parse an element in Source", ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeItems, validationProperties); - } - return result; - - } - - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - public SwordValidationInfo validate(List elements, - List attributes, - Properties validationContext) - { - SwordValidationInfo result = new SwordValidationInfo(xmlName); + /** + * Local name for the element. + */ + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_ATOM, "source", Namespaces.NS_ATOM); + + /** + * The generator data for this object. + */ + private Generator generator; + + /** + * The log. + */ + private static Logger log = Logger.getLogger(Source.class); + + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'source'. + */ + public Source() + { + super(XML_NAME); + } + + public static XmlName elementName() + { + return XML_NAME; + } + + /** + * Marshal the data stored in this object into Element objects. + * + * @return An element that holds the data associated with this object. + */ + public Element marshall() + { + Element source = new Element(getQualifiedName(), xmlName.getNamespace()); + if ( generator != null ) + { + source.appendChild(generator.marshall()); + } - result.addUnmarshallValidationInfo(elements, attributes); + return source; + } + + /** + * Unmarshal the contents of the source element into the internal data objects + * in this object. + * + * @param source The Source element to process. + * + * @throws UnmarshallException If the element does not contain an ATOM Source + * element, or if there is a problem processing the element or any + * sub-elements. + */ + public void unmarshall(Element source) + throws UnmarshallException + { + unmarshall(source, null); + } + + /** + * + * @param source the element to unmarshall. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException If there was an error unmarshalling the data. + */ + public SwordValidationInfo unmarshall(Element source, Properties validationProperties) + throws UnmarshallException + { + if ( ! isInstanceOf(source, xmlName.getLocalName(), Namespaces.NS_ATOM)) + { + //throw new UnmarshallException( "Not an atom:source element" ); + return handleIncorrectElement(source, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeItems = new ArrayList(); + + try + { + processUnexpectedAttributes(source, attributeItems); + + // retrieve all of the sub-elements + Elements elements = source.getChildElements(); + Element element = null; + int length = elements.size(); + + for (int i = 0; i < length; i++ ) + { + element = elements.get(i); + if ( isInstanceOf(element, Generator.elementName()) ) + { + generator = new Generator(); + generator.unmarshall(element); + } + else + { + SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), + SwordValidationInfo.UNKNOWN_ELEMENT, + SwordValidationInfoType.INFO); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in Source: " + ex.getMessage()); + throw new UnmarshallException("Unable to parse an element in Source", ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeItems, validationProperties); + } return result; - } - - - /** - * Get the generator. - * - * @return The generator. - */ - public Generator getGenerator() - { - return generator; - } - - /** - * Set the generator. - * - * @param generator The generator. - */ - public void setGenerator(Generator generator) - { - this.generator = generator; - } + + } + + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + public SwordValidationInfo validate(List elements, + List attributes, + Properties validationContext) + { + SwordValidationInfo result = new SwordValidationInfo(xmlName); + + + result.addUnmarshallValidationInfo(elements, attributes); + return result; + } + + + /** + * Get the generator. + * + * @return The generator. + */ + public Generator getGenerator() + { + return generator; + } + + /** + * Set the generator. + * + * @param generator The generator. + */ + public void setGenerator(Generator generator) + { + this.generator = generator; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Summary.java b/dspace-sword/src/main/java/org/purl/sword/atom/Summary.java index 4a082597c4..bc5370808d 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Summary.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Summary.java @@ -18,20 +18,20 @@ import org.purl.sword.base.XmlName; */ public class Summary extends TextConstruct { - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_ATOM, "summary", Namespaces.NS_ATOM); - - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'summary'. - */ - public Summary() - { - super(XML_NAME); - } - - public static XmlName elementName() - { - return XML_NAME; - } + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_ATOM, "summary", Namespaces.NS_ATOM); + + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'summary'. + */ + public Summary() + { + super(XML_NAME); + } + + public static XmlName elementName() + { + return XML_NAME; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/TextConstruct.java b/dspace-sword/src/main/java/org/purl/sword/atom/TextConstruct.java index d16f793477..47f62dba81 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/TextConstruct.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/TextConstruct.java @@ -32,46 +32,46 @@ import org.purl.sword.base.XmlName; public class TextConstruct extends XmlElement implements SwordElementInterface { - /** + /** * The content in the element. */ - private String content; + private String content; - /** - * The type of the element. - */ - private ContentType type; + /** + * The type of the element. + */ + private ContentType type; - /** - * The log. - */ - private static Logger log = Logger.getLogger(TextConstruct.class); - - /** - * label for the type attribute. - */ - public static final String ATTRIBUTE_TYPE = "type"; - - /** - * Create a new instance, specifying the prefix and local name. - * - * @param prefix The prefix. - * @param name The local name. - */ - public TextConstruct(String prefix, String name) - { - this(prefix, name, Namespaces.NS_ATOM); - } - - /** - * Create a new instance. Set the default type to TextConstructType.TEXT. - * - * @param name The name that will be applied. - */ - public TextConstruct(String name) - { + /** + * The log. + */ + private static Logger log = Logger.getLogger(TextConstruct.class); + + /** + * label for the type attribute. + */ + public static final String ATTRIBUTE_TYPE = "type"; + + /** + * Create a new instance, specifying the prefix and local name. + * + * @param prefix The prefix. + * @param name The local name. + */ + public TextConstruct(String prefix, String name) + { + this(prefix, name, Namespaces.NS_ATOM); + } + + /** + * Create a new instance. Set the default type to TextConstructType.TEXT. + * + * @param name The name that will be applied. + */ + public TextConstruct(String name) + { this(Namespaces.PREFIX_ATOM, name); - } + } /** * Create a new instance. Set the XML name for the element. @@ -85,9 +85,9 @@ implements SwordElementInterface /** * - * @param prefix - * @param name - * @param namespaceUri + * @param prefix The prefix. + * @param name The local name. + * @param namespaceUri The namespace URI. */ public TextConstruct(String prefix, String name, String namespaceUri) { @@ -104,229 +104,234 @@ implements SwordElementInterface this.content = null; } - /** - * Marshal the data in this object to an Element object. - * - * @return The data expressed in an Element. - */ - public Element marshall() - { - Element element = new Element(getQualifiedName(), Namespaces.NS_ATOM); - if( type != null ) - { - Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type.toString()); - element.addAttribute(typeAttribute); - } - - if( content != null ) - { - element.appendChild(content); - } - return element; - } - - /** - * Unmarshal the text element into this object. - * - * This unmarshaller only handles plain text content, although it can - * recognise the three different type elements of text, html and xhtml. This - * is an area that can be improved in a future implementation, if necessary. - * - * @param text The text element. - * - * @throws UnmarshallException If the specified element is not of - * the correct type, where the localname is used - * to specify the valid name. Also thrown - * if there is an issue accessing the data. - */ - public void unmarshall(Element text) - throws UnmarshallException - { - unmarshall(text, null); - } - - /** - * - * @param text - * @param validationProperties - * @throws org.purl.sword.base.UnmarshallException - */ - public SwordValidationInfo unmarshall(Element text, Properties validationProperties) - throws UnmarshallException - { - if( ! isInstanceOf(text, xmlName)) - { - return handleIncorrectElement(text, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeItems = new ArrayList(); - - try - { - initialise(); - - // get the attributes - int attributeCount = text.getAttributeCount(); - Attribute attribute = null; - for( int i = 0; i < attributeCount; i++ ) - { - attribute = text.getAttribute(i); - if( ATTRIBUTE_TYPE.equals(attribute.getQualifiedName())) - { - boolean success = true; - String value = attribute.getValue(); - if( ContentType.TEXT.toString().equals(value) ) - { - type = ContentType.TEXT; - } - else if( ContentType.HTML.toString().equals(value) ) - { - type = ContentType.HTML; - } - else if( ContentType.XHTML.toString().equals(value) ) - { - type = ContentType.XHTML; - } - else - { - log.error("Unable to parse extract type in " + getQualifiedName() ); - SwordValidationInfo info = new SwordValidationInfo(xmlName, - new XmlName(attribute), - "Invalid content type has been specified", - SwordValidationInfoType.ERROR); - info.setContentDescription(value); - attributeItems.add(info); - success = false; - } - - if( success ) - { - SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(attribute)); - info.setContentDescription(type.toString()); - attributeItems.add(info); - } - } - else - { - SwordValidationInfo info = new SwordValidationInfo(xmlName, - new XmlName(attribute), - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO); - info.setContentDescription(attribute.getValue()); - attributeItems.add(info); - } - } - - // retrieve all of the sub-elements - int length = text.getChildCount(); - if( length > 0 ) - { - content = unmarshallString(text); - } - - } - catch( Exception ex ) - { - log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); - throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeItems, validationProperties); - } - return result; - } - - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - /** - * - * @param existing - * @param attributeItems - */ - protected SwordValidationInfo validate(List existing, - List attributeItems, - Properties validationContext) - { - boolean validateAll = (existing == null); - - SwordValidationInfo result = new SwordValidationInfo(xmlName); - result.setContentDescription(content); - - // item specific rules - if( content == null ) - { - result.addValidationInfo( - new SwordValidationInfo(xmlName, "Missing content for element", - SwordValidationInfoType.WARNING)); - } - - if( validateAll ) - { - SwordValidationInfo info = new SwordValidationInfo(xmlName, - new XmlName(xmlName.getPrefix(), ATTRIBUTE_TYPE, xmlName.getNamespace())); - info.setContentDescription(type.toString()); - result.addAttributeValidationInfo(info); - - } - - result.addUnmarshallValidationInfo(existing, attributeItems); - return result; - } - - - /** - * Get the content in this TextConstruct. - * - * @return The content, expressed as a string. - */ - public String getContent() { - return content; - } - - /** - * Set the content. This only supports text content. - * - * @param content The content. - */ - public void setContent(String content) - { - this.content = content; - } - - /** - * Get the type. - * - * @return The type. - */ - public ContentType getType() - { - return type; - } - - /** - * Set the type. - * - * @param type The type. - */ - public void setType(ContentType type) - { - this.type = type; - } - - /** - * Get a string representation. - * - * @return The string. - */ - public String toString() - { - return "Summary - content: " + getContent() + " type: " + getType(); - } + /** + * Marshal the data in this object to an Element object. + * + * @return The data expressed in an Element. + */ + public Element marshall() + { + Element element = new Element(getQualifiedName(), Namespaces.NS_ATOM); + if ( type != null ) + { + Attribute typeAttribute = new Attribute(ATTRIBUTE_TYPE, type.toString()); + element.addAttribute(typeAttribute); + } + + if ( content != null ) + { + element.appendChild(content); + } + return element; + } + + /** + * Unmarshal the text element into this object. + * + * This unmarshaller only handles plain text content, although it can + * recognise the three different type elements of text, html and xhtml. This + * is an area that can be improved in a future implementation, if necessary. + * + * @param text The text element. + * + * @throws UnmarshallException If the specified element is not of + * the correct type, where the localname is used + * to specify the valid name. Also thrown + * if there is an issue accessing the data. + */ + public void unmarshall(Element text) + throws UnmarshallException + { + unmarshall(text, null); + } + + /** + * + * @param text The text element. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException If the specified element is not of + * the correct type, where the localname is used + * to specify the valid name. Also thrown + * if there is an issue accessing the data. + */ + public SwordValidationInfo unmarshall(Element text, Properties validationProperties) + throws UnmarshallException + { + if ( ! isInstanceOf(text, xmlName)) + { + return handleIncorrectElement(text, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeItems = new ArrayList(); + + try + { + initialise(); + + // get the attributes + int attributeCount = text.getAttributeCount(); + Attribute attribute = null; + for ( int i = 0; i < attributeCount; i++ ) + { + attribute = text.getAttribute(i); + if ( ATTRIBUTE_TYPE.equals(attribute.getQualifiedName())) + { + boolean success = true; + String value = attribute.getValue(); + if ( ContentType.TEXT.toString().equals(value) ) + { + type = ContentType.TEXT; + } + else if ( ContentType.HTML.toString().equals(value) ) + { + type = ContentType.HTML; + } + else if ( ContentType.XHTML.toString().equals(value) ) + { + type = ContentType.XHTML; + } + else + { + log.error("Unable to parse extract type in " + getQualifiedName() ); + SwordValidationInfo info = new SwordValidationInfo(xmlName, + new XmlName(attribute), + "Invalid content type has been specified", + SwordValidationInfoType.ERROR); + info.setContentDescription(value); + attributeItems.add(info); + success = false; + } + + if ( success ) + { + SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(attribute)); + info.setContentDescription(type.toString()); + attributeItems.add(info); + } + } + else + { + SwordValidationInfo info = new SwordValidationInfo(xmlName, + new XmlName(attribute), + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO); + info.setContentDescription(attribute.getValue()); + attributeItems.add(info); + } + } + + // retrieve all of the sub-elements + int length = text.getChildCount(); + if ( length > 0 ) + { + content = unmarshallString(text); + } + + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); + throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeItems, validationProperties); + } + return result; + } + + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + /** + * + * @param existing add results to this. + * @param attributeItems add these too. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + protected SwordValidationInfo validate(List existing, + List attributeItems, + Properties validationContext) + { + boolean validateAll = (existing == null); + + SwordValidationInfo result = new SwordValidationInfo(xmlName); + result.setContentDescription(content); + + // item specific rules + if ( content == null ) + { + result.addValidationInfo( + new SwordValidationInfo(xmlName, "Missing content for element", + SwordValidationInfoType.WARNING)); + } + + if ( validateAll ) + { + SwordValidationInfo info = new SwordValidationInfo(xmlName, + new XmlName(xmlName.getPrefix(), ATTRIBUTE_TYPE, xmlName.getNamespace())); + info.setContentDescription(type.toString()); + result.addAttributeValidationInfo(info); + } + + result.addUnmarshallValidationInfo(existing, attributeItems); + return result; + } + + + /** + * Get the content in this TextConstruct. + * + * @return The content, expressed as a string. + */ + public String getContent() { + return content; + } + + /** + * Set the content. This only supports text content. + * + * @param content The content. + */ + public void setContent(String content) + { + this.content = content; + } + + /** + * Get the type. + * + * @return The type. + */ + public ContentType getType() + { + return type; + } + + /** + * Set the type. + * + * @param type The type. + */ + public void setType(ContentType type) + { + this.type = type; + } + + /** + * Get a string representation. + * + * @return The string. + */ + public String toString() + { + return "Summary - content: " + getContent() + " type: " + getType(); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/atom/Title.java b/dspace-sword/src/main/java/org/purl/sword/atom/Title.java index dbba5f0d8c..64f6195c84 100644 --- a/dspace-sword/src/main/java/org/purl/sword/atom/Title.java +++ b/dspace-sword/src/main/java/org/purl/sword/atom/Title.java @@ -19,26 +19,26 @@ import org.purl.sword.base.XmlName; public class Title extends TextConstruct { - /** - * Local name part of the element. - */ + /** + * Local name part of the element. + */ @Deprecated - public static final String ELEMENT_NAME = "title"; + public static final String ELEMENT_NAME = "title"; /** * XML Name representation. */ private static final XmlName XML_NAME = new XmlName(Namespaces.PREFIX_ATOM, - "title", Namespaces.NS_ATOM); + "title", Namespaces.NS_ATOM); - /** - * Create a new instance and set the prefix to - * 'atom' and the local name to 'title'. - */ - public Title() - { - super(XML_NAME); - } + /** + * Create a new instance and set the prefix to + * 'atom' and the local name to 'title'. + */ + public Title() + { + super(XML_NAME); + } public static XmlName elementName() { diff --git a/dspace-sword/src/main/java/org/purl/sword/base/AtomDocumentResponse.java b/dspace-sword/src/main/java/org/purl/sword/base/AtomDocumentResponse.java index ee0f8b60de..73f40216fd 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/AtomDocumentResponse.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/AtomDocumentResponse.java @@ -15,14 +15,14 @@ package org.purl.sword.base; public class AtomDocumentResponse extends DepositResponse { - /** - * Create a new response with the specified http code. - * - * @param httpResponse Response code. - */ - public AtomDocumentResponse(int httpResponse) - { - super(httpResponse); - } + /** + * Create a new response with the specified http code. + * + * @param httpResponse Response code. + */ + public AtomDocumentResponse(int httpResponse) + { + super(httpResponse); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/BasicBooleanContentElement.java b/dspace-sword/src/main/java/org/purl/sword/base/BasicBooleanContentElement.java index 052e22fab8..c09a8c83ff 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/BasicBooleanContentElement.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/BasicBooleanContentElement.java @@ -60,11 +60,11 @@ public class BasicBooleanContentElement extends BasicContentElement protected SwordValidationInfo validateContent(Properties validationContext) { SwordValidationInfo result = null; - if( ! isSet ) + if ( ! isSet ) { - result = new SwordValidationInfo(xmlName, - SwordValidationInfo.MISSING_CONTENT, - SwordValidationInfoType.WARNING); + result = new SwordValidationInfo(xmlName, + SwordValidationInfo.MISSING_CONTENT, + SwordValidationInfoType.WARNING); } return result; } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/BasicContentElement.java b/dspace-sword/src/main/java/org/purl/sword/base/BasicContentElement.java index d84f7fe521..69a487760f 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/BasicContentElement.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/BasicContentElement.java @@ -25,12 +25,12 @@ import org.purl.sword.base.XmlName; public abstract class BasicContentElement extends XmlElement implements SwordElementInterface { - /** - * The log. - */ - private static Logger log = Logger.getLogger(BasicContentElement.class); - - public BasicContentElement(String prefix, String name, String namespaceUri) + /** + * The log. + */ + private static Logger log = Logger.getLogger(BasicContentElement.class); + + public BasicContentElement(String prefix, String name, String namespaceUri) { super(prefix, name, namespaceUri); } @@ -41,133 +41,135 @@ implements SwordElementInterface } /** - * Marshal the data in this object to an Element object. - * - * @return The data expressed in an Element. - */ + * Marshal the data in this object to an Element object. + * + * @return The data expressed in an Element. + */ public Element marshall() { - Element element = new Element(getQualifiedName(), xmlName.getNamespace()); - marshallContent(element); - return element; - } - - protected abstract void marshallContent(Element element); - - /** - * Unmarshal the text element into this object. - * - * This unmarshaller only handles plain text content, although it can - * recognise the three different type elements of text, html and xhtml. This - * is an area that can be improved in a future implementation, if necessary. - * - * @param element The text element. - * @param validationProperties - * - * @throws UnmarshallException If the specified element is not of - * the correct type, where the localname is used - * to specify the valid name. Also thrown - * if there is an issue accessing the data. - */ - public SwordValidationInfo unmarshall(Element element, Properties validationProperties) - throws UnmarshallException - { - if( ! isInstanceOf(element, xmlName) ) - { - return handleIncorrectElement(element, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeItems = new ArrayList(); - - try - { - processUnexpectedAttributes(element, attributeItems); - - int length = element.getChildCount(); - if( length > 0 ) - { - try - { - unmarshallContent(element); - } - catch( UnmarshallException ume ) - { - log.error("Error accessing the content of the " + xmlName.getQualifiedName() + " element"); - if( validationProperties == null ) - { - throw ume; - } - else - { - SwordValidationInfo info = new SwordValidationInfo(xmlName, - SwordValidationInfo.ERROR_WITH_CONTENT, SwordValidationInfoType.ERROR); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } - } - } - - } - catch( Exception ex ) - { - log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); - if( validationProperties == null ) - { - throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); - } - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeItems, validationProperties); - } - return result; - } - - public void unmarshall(Element element) - throws UnmarshallException - { - - } - - @Override - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - /** - * - * @param existing - * @param attributeItems - */ - protected SwordValidationInfo validate(List existing, - List attributeItems, - Properties validationContext) - { - SwordValidationInfo result = new SwordValidationInfo(xmlName); - result.setContentDescription(getContentAsString()); - - SwordValidationInfo contentResult = validateContent(validationContext); - if( contentResult != null ) - { - result.addValidationInfo(contentResult); - } - - result.addUnmarshallValidationInfo(existing, attributeItems); - return result; - } - - - protected abstract void unmarshallContent(Element element) - throws UnmarshallException; - - - protected abstract SwordValidationInfo validateContent(Properties validationContext); - - - protected abstract String getContentAsString(); + Element element = new Element(getQualifiedName(), xmlName.getNamespace()); + marshallContent(element); + return element; + } + + protected abstract void marshallContent(Element element); + + /** + * Unmarshal the text element into this object. + * + * This unmarshaller only handles plain text content, although it can + * recognise the three different type elements of text, html and xhtml. This + * is an area that can be improved in a future implementation, if necessary. + * + * @param element The text element. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return object representing the text element + * @throws UnmarshallException If the specified element is not of + * the correct type, where the localname is used + * to specify the valid name. Also thrown + * if there is an issue accessing the data. + */ + public SwordValidationInfo unmarshall(Element element, Properties validationProperties) + throws UnmarshallException + { + if ( ! isInstanceOf(element, xmlName) ) + { + return handleIncorrectElement(element, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeItems = new ArrayList(); + + try + { + processUnexpectedAttributes(element, attributeItems); + + int length = element.getChildCount(); + if ( length > 0 ) + { + try + { + unmarshallContent(element); + } + catch ( UnmarshallException ume ) + { + log.error("Error accessing the content of the " + xmlName.getQualifiedName() + " element"); + if ( validationProperties == null ) + { + throw ume; + } + else + { + SwordValidationInfo info = new SwordValidationInfo(xmlName, + SwordValidationInfo.ERROR_WITH_CONTENT, SwordValidationInfoType.ERROR); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + } + + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); + if ( validationProperties == null ) + { + throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); + } + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeItems, validationProperties); + } + return result; + } + + public void unmarshall(Element element) + throws UnmarshallException + { + + } + + @Override + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + /** + * + * @param existing add results to this. + * @param attributeItems FIXME: PLEASE DOCUMENT. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + protected SwordValidationInfo validate(List existing, + List attributeItems, + Properties validationContext) + { + SwordValidationInfo result = new SwordValidationInfo(xmlName); + result.setContentDescription(getContentAsString()); + + SwordValidationInfo contentResult = validateContent(validationContext); + if ( contentResult != null ) + { + result.addValidationInfo(contentResult); + } + + result.addUnmarshallValidationInfo(existing, attributeItems); + return result; + } + + + protected abstract void unmarshallContent(Element element) + throws UnmarshallException; + + + protected abstract SwordValidationInfo validateContent(Properties validationContext); + + + protected abstract String getContentAsString(); } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/BasicIntegerContentElement.java b/dspace-sword/src/main/java/org/purl/sword/base/BasicIntegerContentElement.java index b35a7fd2df..b144f2a86d 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/BasicIntegerContentElement.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/BasicIntegerContentElement.java @@ -60,11 +60,11 @@ public class BasicIntegerContentElement extends BasicContentElement protected SwordValidationInfo validateContent(Properties validationContext) { SwordValidationInfo result = null; - if( ! isSet ) + if ( ! isSet ) { result = new SwordValidationInfo(xmlName, - SwordValidationInfo.MISSING_CONTENT, - SwordValidationInfoType.WARNING); + SwordValidationInfo.MISSING_CONTENT, + SwordValidationInfoType.WARNING); } return result; } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/BasicStringContentElement.java b/dspace-sword/src/main/java/org/purl/sword/base/BasicStringContentElement.java index 4ba5bead68..cc45a1ce5f 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/BasicStringContentElement.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/BasicStringContentElement.java @@ -40,7 +40,7 @@ public class BasicStringContentElement extends BasicContentElement protected void marshallContent(Element element) { - if( content != null ) + if ( content != null ) { element.appendChild(content); } @@ -55,11 +55,11 @@ public class BasicStringContentElement extends BasicContentElement protected SwordValidationInfo validateContent(Properties validationContext) { SwordValidationInfo result = null; - if( content == null ) + if ( content == null ) { - result = new SwordValidationInfo(xmlName, - SwordValidationInfo.MISSING_CONTENT, - SwordValidationInfoType.WARNING); + result = new SwordValidationInfo(xmlName, + SwordValidationInfo.MISSING_CONTENT, + SwordValidationInfoType.WARNING); } return result; } @@ -69,6 +69,4 @@ public class BasicStringContentElement extends BasicContentElement { return content; } - - } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/ChecksumUtils.java b/dspace-sword/src/main/java/org/purl/sword/base/ChecksumUtils.java index bcf038d75e..926b24277c 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/ChecksumUtils.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/ChecksumUtils.java @@ -22,145 +22,145 @@ import org.apache.log4j.Logger; */ public class ChecksumUtils { - /** Logger */ - private static Logger log = Logger.getLogger(ChecksumUtils.class); - - /** - * Generate an MD5 hash for the file that is specified in the - * filepath. The hash is returned as a String representation. - * - * @param filepath The path to the file to load. - * @return A string hash of the file. - * @throws NoSuchAlgorithmException If the MD5 algorithm is - * not supported by the installed virtual machine. - * - * @throws IOException If there is an error accessing the file. - */ - public static String generateMD5(String filepath) - throws NoSuchAlgorithmException, IOException - { - return generateMD5(new FileInputStream(filepath)); - } - - /** - * Generate an MD5 hash for the file that is specified in the - * filepath. The hash is returned as a String representation. - * - * @param md5Stream The InputStream to checksum. - * @return A string hash of the file. - * @throws NoSuchAlgorithmException If the MD5 algorithm is - * not supported by the installed virtual machine. - * - * @throws IOException If there is an error accessing the file. - */ - public static String generateMD5(InputStream md5Stream) - throws NoSuchAlgorithmException, IOException - { - String md5 = null; - - try - { - MessageDigest md = MessageDigest.getInstance("MD5"); - md.reset(); - - byte[] bytes = new byte[1024]; - int count = 0; - while( (count = md5Stream.read(bytes)) != -1 ) - { - md.update(bytes, 0, count); - } - - byte[] md5Digest = md.digest(); - - StringBuffer buffer = new StringBuffer(); - for( byte b : md5Digest ) - { - // 0xFF is used to handle the issue of negative numbers in the bytes - String hex = Integer.toHexString(b & 0xFF); - if( hex.length() == 1 ) - { - buffer.append("0"); - } - buffer.append(hex); - } - - md5 = buffer.toString(); - } - catch(NoSuchAlgorithmException ex ) - { - log.error("MD5 Algorithm Not found"); - throw ex; - } - finally - { - if( md5Stream != null ) - { - md5Stream.close(); - } - } - - return md5; - } - - /** - * Generate an MD5 hash for the file that is specified in the - * filepath. The hash is returned as a String representation. - * - * @param bytes The byte array to checksum. - * @return A string hash of the file. - * @throws NoSuchAlgorithmException If the MD5 algorithm is - * not supported by the installed virtual machine. - * - * @throws IOException If there is an error accessing the file. - */ - public static String generateMD5(byte[] bytes) - throws NoSuchAlgorithmException, IOException - { - String md5 = null; - - try - { - MessageDigest md = MessageDigest.getInstance("MD5"); - md.reset(); - - md.update(bytes); - - - byte[] md5Digest = md.digest(); - - StringBuffer buffer = new StringBuffer(); - for( byte b : md5Digest ) - { - // 0xFF is used to handle the issue of negative numbers in the bytes - String hex = Integer.toHexString(b & 0xFF); - if( hex.length() == 1 ) - { - buffer.append("0"); - } - buffer.append(hex); - } - - md5 = buffer.toString(); - } - catch(NoSuchAlgorithmException ex ) - { - log.error("MD5 Algorithm Not found"); - throw ex; // rethrow - } - - return md5; - } - - /** - * Run a simple test to process the file. - * - * @param args The command line arguments. - * @throws NoSuchAlgorithmException If there was an error generating the MD5. - * @throws IOException If there is an error accessing the file. - */ - public static void main(String[] args) - throws NoSuchAlgorithmException, IOException - { - System.out.println(ChecksumUtils.generateMD5(args[0])); - } + /** Logger */ + private static Logger log = Logger.getLogger(ChecksumUtils.class); + + /** + * Generate an MD5 hash for the file that is specified in the + * filepath. The hash is returned as a String representation. + * + * @param filepath The path to the file to load. + * @return A string hash of the file. + * @throws NoSuchAlgorithmException If the MD5 algorithm is + * not supported by the installed virtual machine. + * + * @throws IOException If there is an error accessing the file. + */ + public static String generateMD5(String filepath) + throws NoSuchAlgorithmException, IOException + { + return generateMD5(new FileInputStream(filepath)); + } + + /** + * Generate an MD5 hash for the file that is specified in the + * filepath. The hash is returned as a String representation. + * + * @param md5Stream The InputStream to checksum. + * @return A string hash of the file. + * @throws NoSuchAlgorithmException If the MD5 algorithm is + * not supported by the installed virtual machine. + * + * @throws IOException If there is an error accessing the file. + */ + public static String generateMD5(InputStream md5Stream) + throws NoSuchAlgorithmException, IOException + { + String md5 = null; + + try + { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.reset(); + + byte[] bytes = new byte[1024]; + int count = 0; + while ( (count = md5Stream.read(bytes)) != -1 ) + { + md.update(bytes, 0, count); + } + + byte[] md5Digest = md.digest(); + + StringBuffer buffer = new StringBuffer(); + for ( byte b : md5Digest ) + { + // 0xFF is used to handle the issue of negative numbers in the bytes + String hex = Integer.toHexString(b & 0xFF); + if ( hex.length() == 1 ) + { + buffer.append("0"); + } + buffer.append(hex); + } + + md5 = buffer.toString(); + } + catch (NoSuchAlgorithmException ex ) + { + log.error("MD5 Algorithm Not found"); + throw ex; + } + finally + { + if ( md5Stream != null ) + { + md5Stream.close(); + } + } + + return md5; + } + + /** + * Generate an MD5 hash for the file that is specified in the + * filepath. The hash is returned as a String representation. + * + * @param bytes The byte array to checksum. + * @return A string hash of the file. + * @throws NoSuchAlgorithmException If the MD5 algorithm is + * not supported by the installed virtual machine. + * + * @throws IOException If there is an error accessing the file. + */ + public static String generateMD5(byte[] bytes) + throws NoSuchAlgorithmException, IOException + { + String md5 = null; + + try + { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.reset(); + + md.update(bytes); + + + byte[] md5Digest = md.digest(); + + StringBuffer buffer = new StringBuffer(); + for ( byte b : md5Digest ) + { + // 0xFF is used to handle the issue of negative numbers in the bytes + String hex = Integer.toHexString(b & 0xFF); + if ( hex.length() == 1 ) + { + buffer.append("0"); + } + buffer.append(hex); + } + + md5 = buffer.toString(); + } + catch (NoSuchAlgorithmException ex) + { + log.error("MD5 Algorithm Not found"); + throw ex; // rethrow + } + + return md5; + } + + /** + * Run a simple test to process the file. + * + * @param args the command line arguments given + * @throws NoSuchAlgorithmException If there was an error generating the MD5. + * @throws IOException If there is an error accessing the file. + */ + public static void main(String[] args) + throws NoSuchAlgorithmException, IOException + { + System.out.println(ChecksumUtils.generateMD5(args[0])); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/Collection.java b/dspace-sword/src/main/java/org/purl/sword/base/Collection.java index e5d954fafd..0b782a5963 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/Collection.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/Collection.java @@ -29,747 +29,751 @@ import org.purl.sword.atom.Accept; */ public class Collection extends XmlElement implements SwordElementInterface { - /** - * Collection location, expressed as a URL. - */ - private String location; - - /** - * Holds the ATOM Title for the collection. - */ - private Title title; - - /** - * List of the APP:Accept elements. - */ - private List accepts; - - /** - * Holds the SWORD Collection policy. - */ - //private String collectionPolicy; - - /** - * The SWORD mediation value. Indicates if mediation is allowed. - */ - //private boolean mediation; - private SwordMediation swordMediation; - - private SwordService swordService; - - private DcAbstract dcTermsAbstract; - - private SwordTreatment swordTreatment; - - private SwordCollectionPolicy swordCollectionPolicy; - - /** - * The SWORD acceptsPackaging details. - */ - private List acceptPackaging; - - /** - * The logger. - */ - private static Logger log = Logger.getLogger(Collection.class); - - /** - * Label for the Href attribute. - */ - public static final String ATTRIBUTE_HREF = "href"; - - /** - * Label for the local part of this element. - */ - @Deprecated - public static final String ELEMENT_NAME = "collection"; - - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_APP, "collection", Namespaces.NS_APP); - - /** - * Create a new instance. - */ - public Collection() - { - super(XML_NAME); - initialise(); - } - - public static XmlName elementName() - { - return XML_NAME; - } - - protected final void initialise() - { - location = null; - title = null; - accepts = new ArrayList(); - acceptPackaging = new ArrayList(); - swordCollectionPolicy = null; - swordMediation = null; - swordService = null; - dcTermsAbstract = null; - swordTreatment = null; - } - - /** - * Create a new instance and set the initial location for the collection. - * - * @param location The initial location, expressed as a URL. - */ - public Collection(String location) - { - this(); - this.location = location; - } - - /** - * Retrieve an array that holds all of the Accept details. - * - * @return An array of strings. Each string represents an - * individual accept element. The array will have a length - * of 0 if no accepts elements are stored in this collection. - */ - public String[] getAccepts() - { - - String[] values = new String[this.accepts.size()]; - Iterator iterator = accepts.iterator(); - for(int i = 0; iterator.hasNext(); i++ ) - { - Accept accept = iterator.next(); - values[i] = accept.getContent(); - } - return values; - } - - /** - * Retrieve an array that holds all of the Accept details. - * - * @return An array of strings. Each string represents an - * individual accept element. The array will have a length - * of 0 if no accepts elements are stored in this collection. - */ - @Deprecated - public List getAcceptsList() - { - ArrayList items = new ArrayList(); - for(Accept item : accepts ) - { - items.add(item.getContent()); - } - return items; - } - - /** - * - */ - public List getAcceptList() - { - return accepts; - } - - /** - * Add an accepts entry. - * - * @param accepts The accepts value. - */ - public void addAccepts(String accepts) { - this.accepts.add(new Accept(accepts)); - } - - /** - * Remove all of the accepts associated with this Collection. - */ - public void clearAccepts( ) - { - this.accepts.clear(); - } - - /** - * Retrieve a hashtable that holds all the acceptsPackaging details. - * - * @return A hashtable. The keys are accepted packaging formats, - * and the values the quality values (stored as QualityValue objects) - */ - public List getAcceptPackaging() - { - return acceptPackaging; - } - - /** - * Add an acceptPackaging format. - * - * @param acceptPackaging the packaging format. - * @param qualityValue the quality value of accepted packaging format. - */ - public void addAcceptPackaging(String acceptPackaging, float qualityValue) { - - this.acceptPackaging.add(new SwordAcceptPackaging(acceptPackaging, qualityValue)); - } - - /** - * Add an acceptPackaging format. A default quality vale is given. - * - * @param acceptPackaging the packaging format. - */ - public void addAcceptPackaging(String acceptPackaging) { - this.acceptPackaging.add(new SwordAcceptPackaging(acceptPackaging, new QualityValue())); - } - - /** - * Remove all of the accepted packaging formats associated with this Collection. - */ - public void clearAcceptPackaging( ) - { - this.acceptPackaging.clear(); - } - - /** - * Get the collection policy. - * - * @return The SWORD collectionPolicy. - */ - public String getCollectionPolicy() - { - if( swordCollectionPolicy == null ) - { - return null; - } - return swordCollectionPolicy.getContent(); - } - - /** - * Set the collection policy. - * - * @param collectionPolicy The collection policy. - */ - public void setCollectionPolicy(String collectionPolicy) - { - swordCollectionPolicy = new SwordCollectionPolicy(collectionPolicy); - } - - /** - * Get the location. - * - * @return TShe location - */ - public String getLocation() { - return location; - } - - /** - * Set the location. - * - * @param location The location. - */ - public void setLocation(String location) { - this.location = location; - } - - /** - * Get the mediation value. - * - * @return The mediation - */ - public boolean getMediation() { - if( swordMediation == null ) - { - return false; - } - return swordMediation.getContent(); - } - - public boolean isMediationSet() - { - if( swordMediation == null ) - { - return false; - } - return swordMediation.isSet(); - } - - /** - * Set the mediation value. - * - * @param mediation The mediation value. - */ - public void setMediation(boolean mediation) - { - swordMediation = new SwordMediation(mediation); - } - - /** - * Get the DC Term abstract. - * - * @return The abstract. - */ - public String getAbstract() - { - if( dcTermsAbstract == null ) - { - return null; - } - return dcTermsAbstract.getContent(); - } - - /** - * Set the abstract. - * - * @param abstractString The abstract. - */ - public void setAbstract(String abstractString) - { - dcTermsAbstract = new DcAbstract(abstractString); - } - - /** - * Get the sword service. - * - * @return The service. - */ - public String getService() - { - if( swordService == null ) - { - return null; - } - return swordService.getContent(); - } - - /** - * Set the sword service. - * - * @param serviceString The service. - */ - public void setService(String serviceString) - { - swordService = new SwordService(serviceString); - } - - /** - * Set the title. This will set the title type to ContentType.TEXT. - * - * @param title The title. - */ - public void setTitle( String title ) - { - if( this.title == null) - { - this.title = new Title(); - } - this.title.setContent(title); - this.title.setType(ContentType.TEXT); - } - - /** - * Get the title. - * - * @return The title, or null if no title has been set. - */ - public String getTitle( ) - { - if( title == null ) - { - return null; - } - return title.getContent(); - } - - /** - * Get the treatment value. - * - * @return The treatment. - */ - public String getTreatment() - { - if( swordTreatment == null ) - { - return null; - } - return swordTreatment.getContent(); - } - - /** - * Set the treatment. - * - * @param treatment The treatment. - */ - public void setTreatment(String treatment) - { - swordTreatment = new SwordTreatment(treatment); - } - - /** - * Get a string representation of this object. This is - * equivalent to calling marshall().toString(). - */ - @Override - public String toString() - { - Element element = marshall(); - return element.toString(); - } - - /** - * Marshall the data in this object to an Element object. - * - * @return A XOM Element that holds the data for this Content element. - */ - public Element marshall( ) - { - // convert data into XOM elements and return the 'root', i.e. the one - // that represents the collection. - Element collection = new Element(getQualifiedName(), Namespaces.NS_APP); - Attribute href = new Attribute(ATTRIBUTE_HREF, location); - collection.addAttribute(href); - - if (title == null) - { - title = new Title(); - title.setContent("Untitled"); - } - collection.appendChild(title.marshall()); - - for (Accept item:accepts) - { - collection.appendChild(item.marshall()); - } - - Iterator apIterator = acceptPackaging.iterator(); - while( apIterator.hasNext() ) - { - collection.appendChild(apIterator.next().marshall()); - } - - if (swordCollectionPolicy != null) - { - collection.appendChild(swordCollectionPolicy.marshall()); - } - - if (dcTermsAbstract != null) - { - collection.appendChild(dcTermsAbstract.marshall()); - } - - if (swordService != null) - { - collection.appendChild(swordService.marshall()); - } - - if (swordMediation != null ) - { - collection.appendChild(swordMediation.marshall()); - } - - if (swordTreatment != null) - { - collection.appendChild(swordTreatment.marshall()); - } - - return collection; - } - - /** - * Unmarshall the content element into the data in this object. - * - * @throws UnmarshallException If the element does not contain a - * content element or if there are problems - * accessing the data. - */ - public void unmarshall(Element collection) - throws UnmarshallException - { - unmarshall(collection, null); - } - - - public SwordValidationInfo unmarshall(Element collection, Properties validationProperties) - throws UnmarshallException - { - if (!isInstanceOf(collection, xmlName)) - { - return handleIncorrectElement(collection, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeValidationItems = new ArrayList(); - - try - { - initialise(); - - // retrieve the attributes - int count = collection.getAttributeCount(); - Attribute a = null; - for( int i = 0; i < count; i++ ) - { - a = collection.getAttribute(i); - if (ATTRIBUTE_HREF.equals(a.getQualifiedName())) + /** + * Collection location, expressed as a URL. + */ + private String location; + + /** + * Holds the ATOM Title for the collection. + */ + private Title title; + + /** + * List of the APP:Accept elements. + */ + private List accepts; + + /** + * Holds the SWORD Collection policy. + */ + //private String collectionPolicy; + + /** + * The SWORD mediation value. Indicates if mediation is allowed. + */ + //private boolean mediation; + private SwordMediation swordMediation; + + private SwordService swordService; + + private DcAbstract dcTermsAbstract; + + private SwordTreatment swordTreatment; + + private SwordCollectionPolicy swordCollectionPolicy; + + /** + * The SWORD acceptsPackaging details. + */ + private List acceptPackaging; + + /** + * The logger. + */ + private static Logger log = Logger.getLogger(Collection.class); + + /** + * Label for the Href attribute. + */ + public static final String ATTRIBUTE_HREF = "href"; + + /** + * Label for the local part of this element. + */ + @Deprecated + public static final String ELEMENT_NAME = "collection"; + + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_APP, "collection", Namespaces.NS_APP); + + /** + * Create a new instance. + */ + public Collection() + { + super(XML_NAME); + initialise(); + } + + public static XmlName elementName() + { + return XML_NAME; + } + + protected final void initialise() + { + location = null; + title = null; + accepts = new ArrayList(); + acceptPackaging = new ArrayList(); + swordCollectionPolicy = null; + swordMediation = null; + swordService = null; + dcTermsAbstract = null; + swordTreatment = null; + } + + /** + * Create a new instance and set the initial location for the collection. + * + * @param location The initial location, expressed as a URL. + */ + public Collection(String location) + { + this(); + this.location = location; + } + + /** + * Retrieve an array that holds all of the Accept details. + * + * @return An array of strings. Each string represents an + * individual accept element. The array will have a length + * of 0 if no accepts elements are stored in this collection. + */ + public String[] getAccepts() + { + String[] values = new String[this.accepts.size()]; + Iterator iterator = accepts.iterator(); + for (int i = 0; iterator.hasNext(); i++ ) + { + Accept accept = iterator.next(); + values[i] = accept.getContent(); + } + return values; + } + + /** + * Retrieve an array that holds all of the Accept details. + * + * @return An array of strings. Each string represents an + * individual accept element. The array will have a length + * of 0 if no accepts elements are stored in this collection. + */ + @Deprecated + public List getAcceptsList() + { + ArrayList items = new ArrayList(); + for (Accept item : accepts ) + { + items.add(item.getContent()); + } + return items; + } + + /** + * Return the list of accepts entries. + * + * @return the list of accepts entries + */ + public List getAcceptList() + { + return accepts; + } + + /** + * Add an accepts entry. + * + * @param accepts The accepts value. + */ + public void addAccepts(String accepts) { + this.accepts.add(new Accept(accepts)); + } + + /** + * Remove all of the accepts associated with this Collection. + */ + public void clearAccepts( ) + { + this.accepts.clear(); + } + + /** + * Retrieve a hashtable that holds all the acceptsPackaging details. + * + * @return A hashtable. The keys are accepted packaging formats, + * and the values the quality values (stored as QualityValue objects) + */ + public List getAcceptPackaging() + { + return acceptPackaging; + } + + /** + * Add an acceptPackaging format. + * + * @param acceptPackaging the packaging format. + * @param qualityValue the quality value of accepted packaging format. + */ + public void addAcceptPackaging(String acceptPackaging, float qualityValue) { + + this.acceptPackaging.add(new SwordAcceptPackaging(acceptPackaging, qualityValue)); + } + + /** + * Add an acceptPackaging format. A default quality vale is given. + * + * @param acceptPackaging the packaging format. + */ + public void addAcceptPackaging(String acceptPackaging) { + this.acceptPackaging.add(new SwordAcceptPackaging(acceptPackaging, new QualityValue())); + } + + /** + * Remove all of the accepted packaging formats associated with this Collection. + */ + public void clearAcceptPackaging( ) + { + this.acceptPackaging.clear(); + } + + /** + * Get the collection policy. + * + * @return The SWORD collectionPolicy. + */ + public String getCollectionPolicy() + { + if ( swordCollectionPolicy == null ) + { + return null; + } + return swordCollectionPolicy.getContent(); + } + + /** + * Set the collection policy. + * + * @param collectionPolicy The collection policy. + */ + public void setCollectionPolicy(String collectionPolicy) + { + swordCollectionPolicy = new SwordCollectionPolicy(collectionPolicy); + } + + /** + * Get the location. + * + * @return TShe location + */ + public String getLocation() { + return location; + } + + /** + * Set the location. + * + * @param location The location. + */ + public void setLocation(String location) { + this.location = location; + } + + /** + * Get the mediation value. + * + * @return The mediation + */ + public boolean getMediation() { + if ( swordMediation == null ) + { + return false; + } + return swordMediation.getContent(); + } + + public boolean isMediationSet() + { + if ( swordMediation == null ) + { + return false; + } + return swordMediation.isSet(); + } + + /** + * Set the mediation value. + * + * @param mediation The mediation value. + */ + public void setMediation(boolean mediation) + { + swordMediation = new SwordMediation(mediation); + } + + /** + * Get the DC Term abstract. + * + * @return The abstract. + */ + public String getAbstract() + { + if ( dcTermsAbstract == null ) + { + return null; + } + return dcTermsAbstract.getContent(); + } + + /** + * Set the abstract. + * + * @param abstractString The abstract. + */ + public void setAbstract(String abstractString) + { + dcTermsAbstract = new DcAbstract(abstractString); + } + + /** + * Get the sword service. + * + * @return The service. + */ + public String getService() + { + if ( swordService == null ) + { + return null; + } + return swordService.getContent(); + } + + /** + * Set the sword service. + * + * @param serviceString The service. + */ + public void setService(String serviceString) + { + swordService = new SwordService(serviceString); + } + + /** + * Set the title. This will set the title type to ContentType.TEXT. + * + * @param title The title. + */ + public void setTitle( String title ) + { + if ( this.title == null) + { + this.title = new Title(); + } + this.title.setContent(title); + this.title.setType(ContentType.TEXT); + } + + /** + * Get the title. + * + * @return The title, or null if no title has been set. + */ + public String getTitle( ) + { + if ( title == null ) + { + return null; + } + return title.getContent(); + } + + /** + * Get the treatment value. + * + * @return The treatment. + */ + public String getTreatment() + { + if ( swordTreatment == null ) + { + return null; + } + return swordTreatment.getContent(); + } + + /** + * Set the treatment. + * + * @param treatment The treatment. + */ + public void setTreatment(String treatment) + { + swordTreatment = new SwordTreatment(treatment); + } + + /** + * Get a string representation of this object. This is + * equivalent to calling marshall().toString(). + */ + @Override + public String toString() + { + Element element = marshall(); + return element.toString(); + } + + /** + * Marshall the data in this object to an Element object. + * + * @return A XOM Element that holds the data for this Content element. + */ + public Element marshall( ) + { + // convert data into XOM elements and return the 'root', i.e. the one + // that represents the collection. + Element collection = new Element(getQualifiedName(), Namespaces.NS_APP); + Attribute href = new Attribute(ATTRIBUTE_HREF, location); + collection.addAttribute(href); + + if (title == null) + { + title = new Title(); + title.setContent("Untitled"); + } + collection.appendChild(title.marshall()); + + for (Accept item:accepts) + { + collection.appendChild(item.marshall()); + } + + Iterator apIterator = acceptPackaging.iterator(); + while ( apIterator.hasNext() ) + { + collection.appendChild(apIterator.next().marshall()); + } + + if (swordCollectionPolicy != null) + { + collection.appendChild(swordCollectionPolicy.marshall()); + } + + if (dcTermsAbstract != null) + { + collection.appendChild(dcTermsAbstract.marshall()); + } + + if (swordService != null) + { + collection.appendChild(swordService.marshall()); + } + + if (swordMediation != null ) + { + collection.appendChild(swordMediation.marshall()); + } + + if (swordTreatment != null) + { + collection.appendChild(swordTreatment.marshall()); + } + + return collection; + } + + /** + * Unmarshall the content element into the data in this object. + * + * @throws UnmarshallException If the element does not contain a + * content element or if there are problems + * accessing the data. + */ + public void unmarshall(Element collection) + throws UnmarshallException + { + unmarshall(collection, null); + } + + + public SwordValidationInfo unmarshall(Element collection, Properties validationProperties) + throws UnmarshallException + { + if (!isInstanceOf(collection, xmlName)) + { + return handleIncorrectElement(collection, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeValidationItems = new ArrayList(); + + try + { + initialise(); + + // retrieve the attributes + int count = collection.getAttributeCount(); + Attribute a = null; + for ( int i = 0; i < count; i++ ) { - location = a.getValue(); - SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(a)); - info.setContentDescription(location); - attributeValidationItems.add(info); - } - else - { - SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(a), - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO ); - info.setContentDescription(a.getValue()); - attributeValidationItems.add(info); - } - } - - // retrieve all of the sub-elements - Elements elements = collection.getChildElements(); - Element element = null; - int length = elements.size(); - - for (int i = 0; i < length; i++) - { - element = elements.get(i); - if (isInstanceOf(element, Title.elementName())) - { - if( title == null ) - { - title = new Title(); - validationItems.add(title.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo( - Title.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } - } - else if (isInstanceOf(element, Accept.elementName()) ) - { - Accept accept = new Accept(); - SwordValidationInfo info = accept.unmarshall(element, validationProperties); - accepts.add(accept); - validationItems.add(info); - } - else if (isInstanceOf(element, SwordAcceptPackaging.elementName())) - { - SwordAcceptPackaging packaging = new SwordAcceptPackaging(); - validationItems.add(packaging.unmarshall(element, validationProperties)); - acceptPackaging.add(packaging); - } - else if (isInstanceOf(element, SwordCollectionPolicy.elementName())) - { - if (swordCollectionPolicy == null) { - swordCollectionPolicy = new SwordCollectionPolicy(); - validationItems.add(swordCollectionPolicy.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) + a = collection.getAttribute(i); + if (ATTRIBUTE_HREF.equals(a.getQualifiedName())) { - SwordValidationInfo info = new SwordValidationInfo( - SwordCollectionPolicy.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - validationItems.add(info); + location = a.getValue(); + SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(a)); + info.setContentDescription(location); + attributeValidationItems.add(info); + } + else + { + SwordValidationInfo info = new SwordValidationInfo(xmlName, new XmlName(a), + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO ); + info.setContentDescription(a.getValue()); + attributeValidationItems.add(info); } - } - else if (isInstanceOf(element, DcAbstract.elementName())) + + // retrieve all of the sub-elements + Elements elements = collection.getChildElements(); + Element element = null; + int length = elements.size(); + + for (int i = 0; i < length; i++) { - if( dcTermsAbstract == null ) + element = elements.get(i); + if (isInstanceOf(element, Title.elementName())) { - dcTermsAbstract = new DcAbstract(); - validationItems.add(dcTermsAbstract.unmarshall(element, validationProperties)); + if ( title == null ) + { + title = new Title(); + validationItems.add(title.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo( + Title.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.INFO); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } } - else if( validationProperties != null ) + else if (isInstanceOf(element, Accept.elementName()) ) { - SwordValidationInfo info = new SwordValidationInfo(DcAbstract.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.INFO); + Accept accept = new Accept(); + SwordValidationInfo info = accept.unmarshall(element, validationProperties); + accepts.add(accept); + validationItems.add(info); + } + else if (isInstanceOf(element, SwordAcceptPackaging.elementName())) + { + SwordAcceptPackaging packaging = new SwordAcceptPackaging(); + validationItems.add(packaging.unmarshall(element, validationProperties)); + acceptPackaging.add(packaging); + } + else if (isInstanceOf(element, SwordCollectionPolicy.elementName())) + { + if (swordCollectionPolicy == null) { + swordCollectionPolicy = new SwordCollectionPolicy(); + validationItems.add(swordCollectionPolicy.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo( + SwordCollectionPolicy.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.INFO); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + + } + else if (isInstanceOf(element, DcAbstract.elementName())) + { + if ( dcTermsAbstract == null ) + { + dcTermsAbstract = new DcAbstract(); + validationItems.add(dcTermsAbstract.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(DcAbstract.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, SwordValidationInfoType.INFO); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if (isInstanceOf(element, SwordService.elementName())) + { + if ( swordService == null ) + { + swordService = new SwordService(); + validationItems.add(swordService.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordService.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.INFO); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if (isInstanceOf(element, SwordMediation.elementName())) + { + if ( swordMediation == null ) + { + swordMediation = new SwordMediation(); + validationItems.add(swordMediation.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordMediation.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if (isInstanceOf(element, SwordTreatment.elementName())) + { + if ( swordTreatment == null ) + { + swordTreatment = new SwordTreatment(); + validationItems.add(swordTreatment.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordTreatment.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), + SwordValidationInfo.UNKNOWN_ELEMENT, + SwordValidationInfoType.INFO); info.setContentDescription(element.getValue()); validationItems.add(info); } } - else if (isInstanceOf(element, SwordService.elementName())) + } + catch (Exception ex) + { + log.error("Unable to parse an element in collection: " + ex.getMessage()); + throw new UnmarshallException("Unable to parse an element in Collection", ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeValidationItems, validationProperties); + } + return result; + + } + + /** + * + */ + @Override + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, null, validationContext); + } + + /** + * + * @param existing add results to this. + * @param attributes FIXME: PLEASE DOCUMENT. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + protected SwordValidationInfo validate(List existing, + List attributes, + Properties validationContext) + { + boolean validateAll = (existing == null); + + SwordValidationInfo result = new SwordValidationInfo(xmlName); + + if ( accepts == null || accepts.size() == 0 ) + { + result.addValidationInfo(new SwordValidationInfo(Accept.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR, + SwordValidationInfoType.WARNING )); + } + + if ( location == null ) + { + XmlName attribute = new XmlName(Namespaces.PREFIX_ATOM, + ATTRIBUTE_HREF, + Namespaces.NS_ATOM); + + result.addAttributeValidationInfo(new SwordValidationInfo(xmlName, + attribute, SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, + SwordValidationInfoType.WARNING )); + } + + if ( swordMediation == null ) + { + result.addValidationInfo(new SwordValidationInfo(SwordMediation.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING, + SwordValidationInfoType.WARNING)); + } + + if ( validateAll ) + { + if ( accepts.size() > 0 ) { - if( swordService == null ) + Iterator acceptIterator = accepts.iterator(); + while ( acceptIterator.hasNext() ) { - swordService = new SwordService(); - validationItems.add(swordService.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordService.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - validationItems.add(info); + result.addValidationInfo(acceptIterator.next().validate(validationContext)); } } - else if (isInstanceOf(element, SwordMediation.elementName())) + + if ( acceptPackaging.size() > 0 ) { - if( swordMediation == null ) + Iterator apIterator = acceptPackaging.iterator(); + while ( apIterator.hasNext() ) { - swordMediation = new SwordMediation(); - validationItems.add(swordMediation.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordMediation.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); + result.addValidationInfo(apIterator.next().validate(validationContext)); } } - else if (isInstanceOf(element, SwordTreatment.elementName())) + + if ( location != null ) { - if( swordTreatment == null ) - { - swordTreatment = new SwordTreatment(); - validationItems.add(swordTreatment.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordTreatment.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } + result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF, location)); } - else if( validationProperties != null ) + + if ( title != null ) { - SwordValidationInfo info = new SwordValidationInfo(new XmlName(element), - SwordValidationInfo.UNKNOWN_ELEMENT, - SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - validationItems.add(info); + result.addValidationInfo(title.validate(validationContext)); } - } - } - catch (Exception ex) - { - log.error("Unable to parse an element in collection: " + ex.getMessage()); - throw new UnmarshallException("Unable to parse an element in Collection", ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeValidationItems, validationProperties); - } - return result; - - } - - /** - * - */ - @Override - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - /** - * - * @param existing - */ - protected SwordValidationInfo validate(List existing, - List attributes, - Properties validationContext) - { - boolean validateAll = (existing == null); - - SwordValidationInfo result = new SwordValidationInfo(xmlName); - - if( accepts == null || accepts.size() == 0 ) - { - result.addValidationInfo(new SwordValidationInfo(Accept.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR, - SwordValidationInfoType.WARNING )); - } - - if( location == null ) - { - XmlName attribute = new XmlName(Namespaces.PREFIX_ATOM, - ATTRIBUTE_HREF, - Namespaces.NS_ATOM); - - result.addAttributeValidationInfo(new SwordValidationInfo(xmlName, - attribute, SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, - SwordValidationInfoType.WARNING )); - } - - if( swordMediation == null ) - { - result.addValidationInfo(new SwordValidationInfo(SwordMediation.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING, - SwordValidationInfoType.WARNING)); - } - - if( validateAll ) - { - if( accepts.size() > 0 ) - { - Iterator acceptIterator = accepts.iterator(); - while( acceptIterator.hasNext() ) - { - result.addValidationInfo(acceptIterator.next().validate(validationContext)); - } - } - - if( acceptPackaging.size() > 0 ) - { - Iterator apIterator = acceptPackaging.iterator(); - while( apIterator.hasNext() ) - { - result.addValidationInfo(apIterator.next().validate(validationContext)); - } - } - - if( location != null ) - { - result.addAttributeValidationInfo(createValidAttributeInfo(ATTRIBUTE_HREF, location)); - } - - if( title != null ) - { - result.addValidationInfo(title.validate(validationContext)); - } - - if( swordMediation != null ) - { - result.addValidationInfo(swordMediation.validate(validationContext)); - } - - if( swordService != null ) - { - result.addValidationInfo(swordService.validate(validationContext)); - } - - if( swordTreatment != null ) - { - result.addValidationInfo(swordTreatment.validate(validationContext)); - } - - if( swordCollectionPolicy != null ) - { - result.addValidationInfo(swordCollectionPolicy.validate(validationContext)); - } - - if( dcTermsAbstract != null ) - { - result.addValidationInfo(dcTermsAbstract.validate(validationContext)); - } - } - - result.addUnmarshallValidationInfo(existing, attributes); - return result; - } + + if ( swordMediation != null ) + { + result.addValidationInfo(swordMediation.validate(validationContext)); + } + + if ( swordService != null ) + { + result.addValidationInfo(swordService.validate(validationContext)); + } + + if ( swordTreatment != null ) + { + result.addValidationInfo(swordTreatment.validate(validationContext)); + } + + if ( swordCollectionPolicy != null ) + { + result.addValidationInfo(swordCollectionPolicy.validate(validationContext)); + } + + if ( dcTermsAbstract != null ) + { + result.addValidationInfo(dcTermsAbstract.validate(validationContext)); + } + } + + result.addUnmarshallValidationInfo(existing, attributes); + return result; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/Deposit.java b/dspace-sword/src/main/java/org/purl/sword/base/Deposit.java index b89d718ece..d0063e4ffa 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/Deposit.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/Deposit.java @@ -24,314 +24,314 @@ public class Deposit { private static final Logger log = Logger.getLogger(Deposit.class); - /** The File deposited */ - private File file; - - /** The content type */ - private String contentType; - - /** The content length */ - private int contentLength; - - /** The username */ - private String username; - - /** The password */ - private String password; - - /** The onBehalfOf value */ - private String onBehalfOf; - - /** The slug string */ - private String slug; - - /** MD5 hash */ - private String md5; - - /** True if verbose should be used */ - private boolean verbose; - - /** True if this is a no-operation command */ - private boolean noOp; - - /** The packaging format */ - private String packaging; - - /** Deposit ID */ - private String depositID; - - /** The IP address */ - private String IPAddress; - - /** The location */ - private String location; - - /** The content disposition */ - private String contentDisposition; - - /** - * Submission created - */ - public static final int CREATED = HttpServletResponse.SC_CREATED; - - /** - * Submission accepted. - */ - public static final int ACCEPTED = HttpServletResponse.SC_ACCEPTED; - - /** - * @return the authenticatedUserName - */ - public String getUsername() { - return username; - } - - /** - * @param username the authenticated UserName to set - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * @return the authenticatedUserPassword - */ - public String getPassword() { - return password; - } - - /** - * @param password the password to set - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return the contentLength - */ - public int getContentLength() { - return contentLength; - } - - /** - * @param contentLength the contentLength to set - */ - public void setContentLength(int contentLength) { - this.contentLength = contentLength; - } - - /** - * @return the contentType - */ - public String getContentType() { - return contentType; - } - - /** - * @param contentType the contentType to set - */ - public void setContentType(String contentType) { - this.contentType = contentType; - } - - /** - * @return the depositID - */ - public String getDepositID() { - return depositID; - } - - /** - * @param depositID the depositID to set - */ - public void setDepositID(String depositID) { - this.depositID = depositID; - } - - /** - * @return the file - */ - public File getFile() { - return file; - } - - /** - * @param file the file to set - */ - public void setFile(File file) { - this.file = file; - } - - /** - * @return the packaging - */ - public String getPackaging() { - return packaging; - } - - /** - * @param packaging the packaging to set - */ - public void setPackaging(String packaging) { - this.packaging = packaging; - } - - /** - * @return the md5 - */ - public String getMd5() { - return md5; - } - - /** - * @param md5 the md5 to set - */ - public void setMd5(String md5) { - this.md5 = md5; - } - - /** - * @return the noOp - */ - public boolean isNoOp() { - return noOp; - } - - /** - * @param noOp the noOp to set - */ - public void setNoOp(boolean noOp) { - this.noOp = noOp; - } - - /** - * @return the onBehalfOf - */ - public String getOnBehalfOf() { - return onBehalfOf; - } - - /** - * @param onBehalfOf the onBehalfOf to set - */ - public void setOnBehalfOf(String onBehalfOf) { - this.onBehalfOf = onBehalfOf; - } - - /** - * @return the slug - */ - public String getSlug() { - return slug; - } - - /** - * @param slug the slug to set - */ - public void setSlug(String slug) { - this.slug = slug; - } - - /** - * @return the verbose - */ - public boolean isVerbose() { - return verbose; - } - - /** - * @param verbose the verbose to set - */ - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - /** - * Get the IP address of the user - * - * @return the IP address - */ - public String getIPAddress() { - return IPAddress; - } - - /** - * Set the IP address of the user - * - * @param IPAddress the IP address - */ - public void setIPAddress(String IPAddress) { - this.IPAddress = IPAddress; - } - - /** - * Get the location of the deposit - * - * @return the location of the deposit - */ - public String getLocation() { - return location; - } - - /** - * Set the location of the deposit - * - * @param location the location - */ - public void setLocation(String location) { - this.location = location; - } - - /** - * Retrieve the filename that is associated with this deposit. This - * is extracted from the content disposition value. - * - * @return The filename. - */ - public String getFilename() - { - String filename = null; // default return value - if( contentDisposition != null ) - { - try - { - String filePattern = ".*filename=(.*?)((; *.*)|( +)){0,1}"; - Pattern p = Pattern.compile(filePattern); - Matcher m = p.matcher(contentDisposition); - - if( m.matches() && m.groupCount() > 2 ) - { - filename = m.group(1); - } - } - catch( Exception ex ) - { - log.error("Unable to extract filename", ex); - } - } - return filename; - } - - /** - * Set the content disposition that is to be used for this deposit. - * This will include the filename, if specified. - * - * @param disposition The content disposition value. - */ - public void setContentDisposition(String disposition) - { - this.contentDisposition = disposition; - } - - /** - * Return the content disposition value. - * - * @return The value. - */ - public String getContentDisposition() - { - return this.contentDisposition; - } + /** The File deposited */ + private File file; + + /** The content type */ + private String contentType; + + /** The content length */ + private int contentLength; + + /** The username */ + private String username; + + /** The password */ + private String password; + + /** The onBehalfOf value */ + private String onBehalfOf; + + /** The slug string */ + private String slug; + + /** MD5 hash */ + private String md5; + + /** True if verbose should be used */ + private boolean verbose; + + /** True if this is a no-operation command */ + private boolean noOp; + + /** The packaging format */ + private String packaging; + + /** Deposit ID */ + private String depositID; + + /** The IP address */ + private String IPAddress; + + /** The location */ + private String location; + + /** The content disposition */ + private String contentDisposition; + + /** + * Submission created + */ + public static final int CREATED = HttpServletResponse.SC_CREATED; + + /** + * Submission accepted. + */ + public static final int ACCEPTED = HttpServletResponse.SC_ACCEPTED; + + /** + * @return the authenticatedUserName + */ + public String getUsername() { + return username; + } + + /** + * @param username the authenticated UserName to set + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * @return the authenticatedUserPassword + */ + public String getPassword() { + return password; + } + + /** + * @param password the password to set + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return the contentLength + */ + public int getContentLength() { + return contentLength; + } + + /** + * @param contentLength the contentLength to set + */ + public void setContentLength(int contentLength) { + this.contentLength = contentLength; + } + + /** + * @return the contentType + */ + public String getContentType() { + return contentType; + } + + /** + * @param contentType the contentType to set + */ + public void setContentType(String contentType) { + this.contentType = contentType; + } + + /** + * @return the depositID + */ + public String getDepositID() { + return depositID; + } + + /** + * @param depositID the depositID to set + */ + public void setDepositID(String depositID) { + this.depositID = depositID; + } + + /** + * @return the file + */ + public File getFile() { + return file; + } + + /** + * @param file the file to set + */ + public void setFile(File file) { + this.file = file; + } + + /** + * @return the packaging + */ + public String getPackaging() { + return packaging; + } + + /** + * @param packaging the packaging to set + */ + public void setPackaging(String packaging) { + this.packaging = packaging; + } + + /** + * @return the md5 + */ + public String getMd5() { + return md5; + } + + /** + * @param md5 the md5 to set + */ + public void setMd5(String md5) { + this.md5 = md5; + } + + /** + * @return the noOp + */ + public boolean isNoOp() { + return noOp; + } + + /** + * @param noOp the noOp to set + */ + public void setNoOp(boolean noOp) { + this.noOp = noOp; + } + + /** + * @return the onBehalfOf + */ + public String getOnBehalfOf() { + return onBehalfOf; + } + + /** + * @param onBehalfOf the onBehalfOf to set + */ + public void setOnBehalfOf(String onBehalfOf) { + this.onBehalfOf = onBehalfOf; + } + + /** + * @return the slug + */ + public String getSlug() { + return slug; + } + + /** + * @param slug the slug to set + */ + public void setSlug(String slug) { + this.slug = slug; + } + + /** + * @return the verbose + */ + public boolean isVerbose() { + return verbose; + } + + /** + * @param verbose the verbose to set + */ + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + /** + * Get the IP address of the user + * + * @return the IP address + */ + public String getIPAddress() { + return IPAddress; + } + + /** + * Set the IP address of the user + * + * @param IPAddress the IP address + */ + public void setIPAddress(String IPAddress) { + this.IPAddress = IPAddress; + } + + /** + * Get the location of the deposit + * + * @return the location of the deposit + */ + public String getLocation() { + return location; + } + + /** + * Set the location of the deposit + * + * @param location the location + */ + public void setLocation(String location) { + this.location = location; + } + + /** + * Retrieve the filename that is associated with this deposit. This + * is extracted from the content disposition value. + * + * @return The filename. + */ + public String getFilename() + { + String filename = null; // default return value + if ( contentDisposition != null ) + { + try + { + String filePattern = ".*filename=(.*?)((; *.*)|( +)){0,1}"; + Pattern p = Pattern.compile(filePattern); + Matcher m = p.matcher(contentDisposition); + + if ( m.matches() && m.groupCount() > 2 ) + { + filename = m.group(1); + } + } + catch ( Exception ex ) + { + log.error("Unable to extract filename", ex); + } + } + return filename; + } + + /** + * Set the content disposition that is to be used for this deposit. + * This will include the filename, if specified. + * + * @param disposition The content disposition value. + */ + public void setContentDisposition(String disposition) + { + this.contentDisposition = disposition; + } + + /** + * Return the content disposition value. + * + * @return The value. + */ + public String getContentDisposition() + { + return this.contentDisposition; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/DepositResponse.java b/dspace-sword/src/main/java/org/purl/sword/base/DepositResponse.java index b9aed770aa..15b45bcf1f 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/DepositResponse.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/DepositResponse.java @@ -28,213 +28,215 @@ import nu.xom.Serializer; */ public class DepositResponse { - /** The entry returned in the response */ - private SWORDEntry entry; - - /** The HTTP Response code */ - private int httpResponse; - - /** The value to set in the Location header (typically the atom edit link) */ - private String location; - - /** Logger */ - private static Logger log = Logger.getLogger(DepositResponse.class); - - /** - * Create a new response with the specified http code. - * - * @param httpResponse Response code. - */ - public DepositResponse( int httpResponse ) - { - entry = new SWORDEntry(); - this.httpResponse = httpResponse; - location = null; - } - - /** - * Set the entry element for this response. - * - * @param entry The SWORD Entry. - */ - public void setEntry( SWORDEntry entry ) - { - this.entry = entry; - } - - /** - * Get the SWORD Entry - * - * @return The entry - */ - public SWORDEntry getEntry( ) - { - return entry; - } - - /** - * Get the SWORD Entry as an error document - * - * @return The error document - * @throws SWORDException If this DespositResponse does not contain a - * SWORDErrorDocumentTest. If this is thrown, then - * the document stores an Entry. - */ - public SWORDErrorDocument getErrorDocument( ) - throws SWORDException - { - if( entry instanceof SWORDErrorDocument) + /** The entry returned in the response */ + private SWORDEntry entry; + + /** The HTTP Response code */ + private int httpResponse; + + /** The value to set in the Location header (typically the atom edit link) */ + private String location; + + /** Logger */ + private static Logger log = Logger.getLogger(DepositResponse.class); + + /** + * Create a new response with the specified http code. + * + * @param httpResponse Response code. + */ + public DepositResponse( int httpResponse ) + { + entry = new SWORDEntry(); + this.httpResponse = httpResponse; + location = null; + } + + /** + * Set the entry element for this response. + * + * @param entry The SWORD Entry. + */ + public void setEntry( SWORDEntry entry ) + { + this.entry = entry; + } + + /** + * Get the SWORD Entry + * + * @return The entry + */ + public SWORDEntry getEntry( ) + { + return entry; + } + + /** + * Get the SWORD Entry as an error document + * + * @return The error document + * @throws SWORDException If this DespositResponse does not contain a + * SWORDErrorDocumentTest. If this is thrown, then + * the document stores an Entry. + */ + public SWORDErrorDocument getErrorDocument( ) + throws SWORDException + { + if ( entry instanceof SWORDErrorDocument) + { + return (SWORDErrorDocument)entry; + } + + throw new SWORDException("Requested document is not an Error Document."); + } + + /** + * Retrieve the HTTP Response code. + * + * @return The response code. + */ + public int getHttpResponse() { + return httpResponse; + } + + /** + * Set the HTTP Response code. + * + * @param httpResponse The code. + */ + public void setHttpResponse(int httpResponse) { + this.httpResponse = httpResponse; + } + + /** + * Retrieve the Location header. + * + * @return The Location header + */ + public String getLocation() { + return location; + } + + /** + * Set the HTTP Location header. + * + * @param location The Location header. + */ + public void setLocation(String location) { + this.location = location; + } + + /** + * Marshall the data in the enclosed SWORD Entry. + * + * @return The string representation. Null if there was an error. + */ + public String marshall( ) + { + try { - return (SWORDErrorDocument)entry; + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Serializer serializer = new Serializer(stream, "UTF-8"); + serializer.setIndent(3); + + if ( entry != null ) + { + Document doc = new Document(entry.marshall()); + serializer.write(doc); + log.info(stream.toString()); + return stream.toString(); + } } - - throw new SWORDException("Requested document is not an Error Document."); - } - - /** - * Retrieve the HTTP Response code. - * - * @return The response code. - */ - public int getHttpResponse() { - return httpResponse; - } - - /** - * Set the HTTP Response code. - * - * @param httpResponse The code. - */ - public void setHttpResponse(int httpResponse) { - this.httpResponse = httpResponse; - } - - /** - * Retrieve the Location header. - * - * @return The Location header - */ - public String getLocation() { - return location; - } - - /** - * Set the HTTP Location header. - * - * @param location The Location header. - */ - public void setLocation(String location) { - this.location = location; - } - - /** - * Marshall the data in the enclosed SWORD Entry. - * - * @return The string representation. Null if there was an error. - */ - public String marshall( ) - { - try - { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - Serializer serializer = new Serializer(stream, "UTF-8"); - serializer.setIndent(3); - - if( entry != null ) - { - Document doc = new Document(entry.marshall()); - serializer.write(doc); - log.info(stream.toString()); - return stream.toString(); - } - } - catch (IOException ex) - { - log.error(ex.getMessage()); - } - - return null; // default return value. - } - - /** - * Unmarshall the specified XML data into a SWORD Entry. - * - * @param xml The XML data as a string. - * @throws UnmarshallException If there was an error unmarshalling the data. - */ - public void unmarshall(String xml) throws UnmarshallException - { - unmarshall(xml, null); - } - - public SwordValidationInfo unmarshall(String xml, Properties validationContext) - throws UnmarshallException - { - try - { - Builder builder = new Builder(); - Document doc = builder.build(xml, Namespaces.NS_ATOM); - Element root = doc.getRootElement(); - - entry = new SWORDEntry( ); - return entry.unmarshall(root, validationContext); - } - catch( ParsingException ex ) - { - throw new UnmarshallException("Unable to parse the XML", ex ); - } - catch( IOException ex ) - { - throw new UnmarshallException("Error acessing the file?", ex); - } - } - - public void unmarshallErrorDocument(String xml) - throws UnmarshallException - { - unmarshallErrorDocument(xml, null); - } - - /** - * Unmarshall the specified XML data into a SWORD error document. - * - * @param xml The XML data as a string. - * @throws UnmarshallException If there was an error unmarshalling the data. - */ - public SwordValidationInfo unmarshallErrorDocument(String xml, - Properties validationContext ) - throws UnmarshallException - { - try - { - Builder builder = new Builder(); - Document doc = builder.build(xml, Namespaces.NS_SWORD); - Element root = doc.getRootElement(); - - SWORDErrorDocument sed = new SWORDErrorDocument(); - SwordValidationInfo info = sed.unmarshall(root, validationContext); - entry = sed; - return info; - } - catch( ParsingException ex ) - { - throw new UnmarshallException("Unable to parse the XML", ex ); - } - catch( IOException ex ) - { - throw new UnmarshallException("Error acessing the file?", ex); - } - } - - /** - * Retrieve a string representation of this data. This is equivalent to - * calling unmarshall(). - * - * @return The marshalled data. - */ - public String toString() - { - return marshall(); - } - + catch (IOException ex) + { + log.error(ex.getMessage()); + } + + return null; // default return value. + } + + /** + * Unmarshall the specified XML data into a SWORD Entry. + * + * @param xml The XML data as a string. + * @throws UnmarshallException If there was an error unmarshalling the data. + */ + public void unmarshall(String xml) throws UnmarshallException + { + unmarshall(xml, null); + } + + public SwordValidationInfo unmarshall(String xml, Properties validationContext) + throws UnmarshallException + { + try + { + Builder builder = new Builder(); + Document doc = builder.build(xml, Namespaces.NS_ATOM); + Element root = doc.getRootElement(); + + entry = new SWORDEntry( ); + return entry.unmarshall(root, validationContext); + } + catch ( ParsingException ex ) + { + throw new UnmarshallException("Unable to parse the XML", ex ); + } + catch ( IOException ex ) + { + throw new UnmarshallException("Error acessing the file?", ex); + } + } + + public void unmarshallErrorDocument(String xml) + throws UnmarshallException + { + unmarshallErrorDocument(xml, null); + } + + /** + * Unmarshall the specified XML data into a SWORD error document. + * + * @param xml The XML data as a string. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException If there was an error unmarshalling the data. + */ + public SwordValidationInfo unmarshallErrorDocument( + String xml, Properties validationContext ) + throws UnmarshallException + { + try + { + Builder builder = new Builder(); + Document doc = builder.build(xml, Namespaces.NS_SWORD); + Element root = doc.getRootElement(); + + SWORDErrorDocument sed = new SWORDErrorDocument(); + SwordValidationInfo info = sed.unmarshall(root, validationContext); + entry = sed; + return info; + } + catch ( ParsingException ex ) + { + throw new UnmarshallException("Unable to parse the XML", ex ); + } + catch ( IOException ex ) + { + throw new UnmarshallException("Error acessing the file?", ex); + } + } + + /** + * Retrieve a string representation of this data. This is equivalent to + * calling unmarshall(). + * + * @return The marshalled data. + */ + public String toString() + { + return marshall(); + } + } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/QualityValue.java b/dspace-sword/src/main/java/org/purl/sword/base/QualityValue.java index 436f2e0272..ef68378748 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/QualityValue.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/QualityValue.java @@ -17,164 +17,165 @@ package org.purl.sword.base; * @author Stuart Lewis */ public class QualityValue { - - /** The quality value. */ - private float quality; - - /** - * Create a quality value defaulting to 1 - * - * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification - */ - public QualityValue() throws NumberFormatException - { - // As per the spec, default to value 1 - setQualityValue(1f); - } - - /** - * Create a quality value - * - * @param q The quality value - * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification - */ - public QualityValue(float q) throws NumberFormatException - { - setQualityValue(q); - } - - /** - * Set the quality value. - * - * @param q The quality value - * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification - */ - public final void setQualityValue(float q) throws NumberFormatException - { - // Check the float is in range - if ((q < 0) || (q > 1)) - { - throw new NumberFormatException("Invalid value - must be between 0 and 1"); - } - - // Check there are no more than three digits after the decimal point - String qStr = "" + q; + + /** The quality value. */ + private float quality; + + /** + * Create a quality value defaulting to 1 + * + * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification + */ + public QualityValue() throws NumberFormatException + { + // As per the spec, default to value 1 + setQualityValue(1f); + } + + /** + * Create a quality value + * + * @param q The quality value + * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification + */ + public QualityValue(float q) throws NumberFormatException + { + setQualityValue(q); + } + + /** + * Set the quality value. + * + * @param q The quality value + * @throws NumberFormatException thrown if the quality value is invalid according to the SWORD specification + */ + public final void setQualityValue(float q) throws NumberFormatException + { + // Check the float is in range + if ((q < 0) || (q > 1)) + { + throw new NumberFormatException("Invalid value - must be between 0 and 1"); + } + + // Check there are no more than three digits after the decimal point + String qStr = "" + q; int pos = qStr.indexOf('.'); if (qStr.substring(pos + 1).length() > 3) - { - throw new NumberFormatException("Invalid value - no more than three digits after the decimal point: " + qStr); - } - quality = q; - } - - /** - * Get the quality value - * - * @return the quality value - */ - public final float getQualityValue() - { - return quality; - } - - /** - * Get a String representation of this quality value - * - * @return The String representation of the quality value - */ - public String toString() - { - return Float.toString(quality); - } - - /** - * A main method with rudimentary tests to check the class - */ - /*public static void main(String[] args) - { - // Test the class - - // Fail - under 0 - try - { - QualityValue qv1 = new QualityValue(-0.01f); - System.out.println("1) Fail: -0.01 passed unexpectedly"); - } - catch (NumberFormatException nfe) - { - System.out.print("1) Pass: -0.01 failed as expected "); - System.out.println(nfe); - } - - // Fail - over 1 - try - { - QualityValue qv2 = new QualityValue(1.01f); - System.out.println("2) Fail: 1.01 passed unexpectedly"); - } - catch (NumberFormatException nfe) - { - System.out.print("2) Pass: 1.01 failed as expected "); - System.out.println(nfe); - } - - // Fail - to many decimal points - try - { - QualityValue qv3 = new QualityValue(0.1234f); - System.out.println("3) Fail: 0.1234 passed unexpectedly"); - } - catch (NumberFormatException nfe) - { - System.out.print("3) Pass: 0.1234 failed as expected "); - System.out.println(nfe); - } - - // Pass - no decimal places 0 - try - { - QualityValue qv4 = new QualityValue(0f); - System.out.println("4) Pass: 0 passed as expected"); - } - catch (NumberFormatException nfe) - { - System.out.println("4) Fail: 0 failed unexpectedly"); - } - - // Pass - no decimal places 1 - try - { - QualityValue qv5 = new QualityValue(1f); - System.out.println("5) Pass: 1 passed as expected"); - } - catch (NumberFormatException nfe) - { - System.out.println("5) Fail: 1 failed unexpectedly"); - } - - // Pass - 3 decimal places - try - { - QualityValue qv6 = new QualityValue(0.123f); - System.out.print("6) Pass: 0.123 passed as expected - "); - System.out.println(qv6); - } - catch (NumberFormatException nfe) - { - System.out.println("6) Fail: 0.123 failed unexpectedly"); - } - - // Pass - No value given - try - { - QualityValue qv6 = new QualityValue(); - System.out.print("7) Pass: no value passed as expected - "); - System.out.println(qv6); - } - catch (NumberFormatException nfe) - { - System.out.println("7) Fail: no value failed unexpectedly"); - } - } + { + throw new NumberFormatException("Invalid value - no more than three digits after the decimal point: " + qStr); + } + quality = q; + } + + /** + * Get the quality value + * + * @return the quality value */ + public final float getQualityValue() + { + return quality; + } + + /** + * Get a String representation of this quality value + * + * @return The String representation of the quality value + */ + public String toString() + { + return Float.toString(quality); + } + + /** + * A main method with rudimentary tests to check the class + */ +/* + public static void main(String[] args) + { + // Test the class + + // Fail - under 0 + try + { + QualityValue qv1 = new QualityValue(-0.01f); + System.out.println("1) Fail: -0.01 passed unexpectedly"); + } + catch (NumberFormatException nfe) + { + System.out.print("1) Pass: -0.01 failed as expected "); + System.out.println(nfe); + } + + // Fail - over 1 + try + { + QualityValue qv2 = new QualityValue(1.01f); + System.out.println("2) Fail: 1.01 passed unexpectedly"); + } + catch (NumberFormatException nfe) + { + System.out.print("2) Pass: 1.01 failed as expected "); + System.out.println(nfe); + } + + // Fail - to many decimal points + try + { + QualityValue qv3 = new QualityValue(0.1234f); + System.out.println("3) Fail: 0.1234 passed unexpectedly"); + } + catch (NumberFormatException nfe) + { + System.out.print("3) Pass: 0.1234 failed as expected "); + System.out.println(nfe); + } + + // Pass - no decimal places 0 + try + { + QualityValue qv4 = new QualityValue(0f); + System.out.println("4) Pass: 0 passed as expected"); + } + catch (NumberFormatException nfe) + { + System.out.println("4) Fail: 0 failed unexpectedly"); + } + + // Pass - no decimal places 1 + try + { + QualityValue qv5 = new QualityValue(1f); + System.out.println("5) Pass: 1 passed as expected"); + } + catch (NumberFormatException nfe) + { + System.out.println("5) Fail: 1 failed unexpectedly"); + } + + // Pass - 3 decimal places + try + { + QualityValue qv6 = new QualityValue(0.123f); + System.out.print("6) Pass: 0.123 passed as expected - "); + System.out.println(qv6); + } + catch (NumberFormatException nfe) + { + System.out.println("6) Fail: 0.123 failed unexpectedly"); + } + + // Pass - No value given + try + { + QualityValue qv6 = new QualityValue(); + System.out.print("7) Pass: no value passed as expected - "); + System.out.println(qv6); + } + catch (NumberFormatException nfe) + { + System.out.println("7) Fail: no value failed unexpectedly"); + } + } +*/ } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/SWORDAuthenticationException.java b/dspace-sword/src/main/java/org/purl/sword/base/SWORDAuthenticationException.java index e17e38f049..d353f5a5dc 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/SWORDAuthenticationException.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/SWORDAuthenticationException.java @@ -16,26 +16,26 @@ package org.purl.sword.base; */ public class SWORDAuthenticationException extends Exception { - /** - * Create a new instance and store the specified message and source data. - * - * @param message The message for the exception. - * @param source The original exception that lead to this exception. This - * can be null. - */ - public SWORDAuthenticationException(String message, Exception source) - { - super(message, source); - } - - /** - * Create a new instance and store the specified message. - * - * @param message The message for the exception. - */ - public SWORDAuthenticationException(String message) - { - super(message); - } - + /** + * Create a new instance and store the specified message and source data. + * + * @param message The message for the exception. + * @param source The original exception that lead to this exception. This + * can be null. + */ + public SWORDAuthenticationException(String message, Exception source) + { + super(message, source); + } + + /** + * Create a new instance and store the specified message. + * + * @param message The message for the exception. + */ + public SWORDAuthenticationException(String message) + { + super(message); + } + } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/SWORDEntry.java b/dspace-sword/src/main/java/org/purl/sword/base/SWORDEntry.java index a23f964891..23da5f4d03 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/SWORDEntry.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/SWORDEntry.java @@ -24,498 +24,502 @@ import org.purl.sword.atom.Entry; public class SWORDEntry extends Entry { - /** - * Specifies whether the document was run in noOp mode, i.e. - * if the document records that no operation was taken for - * the deposit other than to generate a response. - */ - protected SwordNoOp swordNoOp; - - /** - * Used to supply a verbose description. - */ - protected SwordVerboseDescription swordVerboseDescription; - - /** - * Used for a human readable statement about what treatment - * the deposited resource has received. Include either a - * text description or a URI. - */ - protected SwordTreatment swordTreatment; - - /** - * The user agent - */ - protected SwordUserAgent swordUserAgent; - - /** - * The packaging information - */ - private SwordPackaging swordPackaging; - - /** - * Create a new SWORDEntry with the given namespace and element. This method is - * not normally used, instead the default constructor should be used as this will - * set the namespace and element correctly. - * - * @param namespace The namespace of the element - * @param element The element name - */ - public SWORDEntry(String namespace, String element, String namespaceUri) - { - super(namespace, element, namespaceUri); - } - - /** - * A default constructor. - */ - public SWORDEntry() - { - super(); - } - - public SWORDEntry(XmlName name) - { - super(name); - } - - protected void initialise() - { - super.initialise(); - swordNoOp = null; - swordPackaging = null; - swordVerboseDescription = null; - swordTreatment = null; - swordUserAgent = null; - } - - /** - * Get the current value of NoOp. - * - * @return True if the value is set, false otherwise. - */ - public boolean isNoOp() - { - if( swordNoOp == null ) - { - return false; - } - return swordNoOp.getContent(); - } - - /** - * Call this method to set noOp. It should be called even by internal - * methods so that the object can determine if the value has been set - * or whether it just holds the default value. - * - * @param noOp - */ - public void setNoOp(boolean noOp) - { - swordNoOp = new SwordNoOp(noOp); - } - - /** - * Determine if the noOp value has been set. This should be called - * if you want to know whether false for noOp means that it is the - * default value (i.e. no code has set it) or it is a value that - * has been actively set. - * - * @return True if the value has been set. Otherwise, false. - */ - public boolean isNoOpSet() - { - if( swordNoOp == null ) - { - return false; - } - return swordNoOp.isSet(); - } - - /** - * Get the Verbose Description for this entry. - * - * @return The description. - */ - public String getVerboseDescription() - { - if( swordVerboseDescription == null ) - { - return null; - } - return swordVerboseDescription.getContent(); - } - - /** - * Set the verbose description. - * - * @param verboseDescription The description. - */ - public void setVerboseDescription(String verboseDescription) - { - swordVerboseDescription = new SwordVerboseDescription(verboseDescription); - } - - /** - * Get the treatment value. - * - * @return The treatment. - */ - public String getTreatment() - { - if( swordTreatment == null ) - { - return null; - } - return swordTreatment.getContent(); - } - - /** - * Set the treatment value. - * - * @param treatment The treatment. - */ - public void setTreatment(String treatment) - { - swordTreatment = new SwordTreatment(treatment); - } - - /** - * Get the user agent - * - * @return the user agent - */ - public String getUserAgent() - { - if( swordUserAgent == null ) - { - return null; - } - return swordUserAgent.getContent(); - } - - /** - * Set the user agent - * - * @param userAgent the user agent - */ - public void setUserAgent(String userAgent) - { - swordUserAgent = new SwordUserAgent(userAgent); - } - - /** - * Get the packaging format - * - * @return the packaging format - */ - public String getPackaging() - { - if( swordPackaging == null ) - { - return null; - } - return swordPackaging.getContent(); - } - - /** - * Set the packaging format - * - * @param packaging the packaging format - */ - public void setPackaging(String packaging) - { - this.swordPackaging = new SwordPackaging(packaging); - } - - protected void marshallElements(Element entry) - { - super.marshallElements(entry); - - if( swordTreatment != null ) - { - entry.appendChild(swordTreatment.marshall()); - } - - if( swordVerboseDescription != null ) - { - entry.appendChild(swordVerboseDescription.marshall()); - } - - if (swordNoOp != null) - { - entry.appendChild(swordNoOp.marshall()); - } - - if( swordUserAgent != null ) - { - entry.appendChild(swordUserAgent.marshall()); - } - - if( swordPackaging != null ) - { - entry.appendChild(swordPackaging.marshall()); - } - - } - - /** - * Overrides the unmarshall method in the parent Entry. This will - * call the parent method to parse the general Atom elements and - * attributes. This method will then parse the remaining sword - * extensions that exist in the element. - * - * @param entry The entry to parse. - * - * @throws UnmarshallException If the entry is not an atom:entry - * or if there is an exception extracting the data. - */ - public SwordValidationInfo unmarshallWithValidation(Element entry, Properties validationProperties) - throws UnmarshallException - { - SwordValidationInfo result = super.unmarshallWithoutValidate(entry, validationProperties); - - processUnexpectedAttributes(entry, result); - - // retrieve all of the sub-elements - Elements elements = entry.getChildElements(); - Element element = null; - int length = elements.size(); - - for(int i = 0; i < length; i++ ) - { - element = elements.get(i); - - if (isInstanceOf(element, SwordTreatment.elementName())) - { - if( swordTreatment == null ) + /** + * Specifies whether the document was run in noOp mode, i.e. + * if the document records that no operation was taken for + * the deposit other than to generate a response. + */ + protected SwordNoOp swordNoOp; + + /** + * Used to supply a verbose description. + */ + protected SwordVerboseDescription swordVerboseDescription; + + /** + * Used for a human readable statement about what treatment + * the deposited resource has received. Include either a + * text description or a URI. + */ + protected SwordTreatment swordTreatment; + + /** + * The user agent + */ + protected SwordUserAgent swordUserAgent; + + /** + * The packaging information + */ + private SwordPackaging swordPackaging; + + /** + * Create a new SWORDEntry with the given namespace and element. This method is + * not normally used, instead the default constructor should be used as this will + * set the namespace and element correctly. + * + * @param namespace The namespace of the element + * @param element The element name + * @param namespaceUri The namespace URI. + */ + public SWORDEntry(String namespace, String element, String namespaceUri) + { + super(namespace, element, namespaceUri); + } + + /** + * A default constructor. + */ + public SWORDEntry() + { + super(); + } + + public SWORDEntry(XmlName name) + { + super(name); + } + + protected void initialise() + { + super.initialise(); + swordNoOp = null; + swordPackaging = null; + swordVerboseDescription = null; + swordTreatment = null; + swordUserAgent = null; + } + + /** + * Get the current value of NoOp. + * + * @return True if the value is set, false otherwise. + */ + public boolean isNoOp() + { + if ( swordNoOp == null ) + { + return false; + } + return swordNoOp.getContent(); + } + + /** + * Call this method to set noOp. It should be called even by internal + * methods so that the object can determine if the value has been set + * or whether it just holds the default value. + * + * @param noOp True if the NoOp header should be used. + */ + public void setNoOp(boolean noOp) + { + swordNoOp = new SwordNoOp(noOp); + } + + /** + * Determine if the noOp value has been set. This should be called + * if you want to know whether false for noOp means that it is the + * default value (i.e. no code has set it) or it is a value that + * has been actively set. + * + * @return True if the value has been set. Otherwise, false. + */ + public boolean isNoOpSet() + { + if ( swordNoOp == null ) + { + return false; + } + return swordNoOp.isSet(); + } + + /** + * Get the Verbose Description for this entry. + * + * @return The description. + */ + public String getVerboseDescription() + { + if ( swordVerboseDescription == null ) + { + return null; + } + return swordVerboseDescription.getContent(); + } + + /** + * Set the verbose description. + * + * @param verboseDescription The description. + */ + public void setVerboseDescription(String verboseDescription) + { + swordVerboseDescription = new SwordVerboseDescription(verboseDescription); + } + + /** + * Get the treatment value. + * + * @return The treatment. + */ + public String getTreatment() + { + if ( swordTreatment == null ) + { + return null; + } + return swordTreatment.getContent(); + } + + /** + * Set the treatment value. + * + * @param treatment The treatment. + */ + public void setTreatment(String treatment) + { + swordTreatment = new SwordTreatment(treatment); + } + + /** + * Get the user agent + * + * @return the user agent + */ + public String getUserAgent() + { + if ( swordUserAgent == null ) + { + return null; + } + return swordUserAgent.getContent(); + } + + /** + * Set the user agent + * + * @param userAgent the user agent + */ + public void setUserAgent(String userAgent) + { + swordUserAgent = new SwordUserAgent(userAgent); + } + + /** + * Get the packaging format + * + * @return the packaging format + */ + public String getPackaging() + { + if ( swordPackaging == null ) + { + return null; + } + return swordPackaging.getContent(); + } + + /** + * Set the packaging format + * + * @param packaging the packaging format + */ + public void setPackaging(String packaging) + { + this.swordPackaging = new SwordPackaging(packaging); + } + + protected void marshallElements(Element entry) + { + super.marshallElements(entry); + + if ( swordTreatment != null ) + { + entry.appendChild(swordTreatment.marshall()); + } + + if ( swordVerboseDescription != null ) + { + entry.appendChild(swordVerboseDescription.marshall()); + } + + if (swordNoOp != null) + { + entry.appendChild(swordNoOp.marshall()); + } + + if ( swordUserAgent != null ) + { + entry.appendChild(swordUserAgent.marshall()); + } + + if ( swordPackaging != null ) + { + entry.appendChild(swordPackaging.marshall()); + } + + } + + /** + * Overrides the unmarshall method in the parent Entry. This will + * call the parent method to parse the general Atom elements and + * attributes. This method will then parse the remaining sword + * extensions that exist in the element. + * + * @param entry The entry to parse. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException If the entry is not an atom:entry + * or if there is an exception extracting the data. + */ + public SwordValidationInfo unmarshallWithValidation(Element entry, Properties validationProperties) + throws UnmarshallException + { + SwordValidationInfo result = super.unmarshallWithoutValidate(entry, validationProperties); + + processUnexpectedAttributes(entry, result); + + // retrieve all of the sub-elements + Elements elements = entry.getChildElements(); + Element element = null; + int length = elements.size(); + + for (int i = 0; i < length; i++ ) + { + element = elements.get(i); + + if (isInstanceOf(element, SwordTreatment.elementName())) + { + if ( swordTreatment == null ) + { + swordTreatment = new SwordTreatment(); + result.addUnmarshallElementInfo( + swordTreatment.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordTreatment.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, SwordNoOp.elementName())) + { + if ( swordNoOp == null ) + { + swordNoOp = new SwordNoOp(); + result.addUnmarshallElementInfo(swordNoOp.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, SwordVerboseDescription.elementName())) + { + if ( swordVerboseDescription == null ) + { + swordVerboseDescription = new SwordVerboseDescription(); + result.addUnmarshallElementInfo(swordVerboseDescription.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordVerboseDescription.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, SwordUserAgent.elementName())) + { + if ( swordUserAgent == null ) + { + swordUserAgent = new SwordUserAgent(); + result.addUnmarshallElementInfo(swordUserAgent.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordUserAgent.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (isInstanceOf(element, SwordPackaging.elementName())) + { + if ( swordPackaging == null ) + { + swordPackaging = new SwordPackaging(); + result.addUnmarshallElementInfo(swordPackaging.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordPackaging.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + else if (validationProperties != null ) + { + XmlName name = new XmlName(element); + if ( ! isElementChecked(name) ) + { + SwordValidationInfo info = new SwordValidationInfo(name, + SwordValidationInfo.UNKNOWN_ELEMENT, + SwordValidationInfoType.INFO); + info.setContentDescription(element.getValue()); + result.addUnmarshallElementInfo(info); + } + } + + } // for + return result; + } + + public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) + throws UnmarshallException + { + + SwordValidationInfo result = unmarshallWithValidation(entry, validationProperties); + if ( validationProperties != null ) + { + result = validate(result, validationProperties); + } + return result; + } + + /** + * + * @param elementName + * name of element to check + * @return true if element is checked + */ + protected boolean isElementChecked(XmlName elementName) + { + if ( elementName == null ) + { + return false; + } + + return elementName.equals(SwordNoOp.elementName()) | + elementName.equals(SwordUserAgent.elementName()) | + elementName.equals(SwordTreatment.elementName()) | + elementName.equals(SwordVerboseDescription.elementName()) | + elementName.equals(SwordPackaging.elementName()) | + super.isElementChecked(elementName); + } + + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, validationContext); + } + + protected SwordValidationInfo validate(SwordValidationInfo info, + Properties validationContext) + { + boolean validateAll = (info == null); + + SwordValidationInfo swordEntry = super.validate(info, validationContext); + + if ( swordUserAgent == null ) + { + String agent = validationContext.getProperty(HttpHeaders.USER_AGENT); + + if ( agent != null ) { - swordTreatment = new SwordTreatment(); - result.addUnmarshallElementInfo( - swordTreatment.unmarshall(element, validationProperties)); + swordEntry.addValidationInfo(new SwordValidationInfo(SwordUserAgent.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING + + " Clients SHOULD provide a User-Agent request-header (as described in [HTTP1.1] section 14.43). If provided, servers SHOULD store the value in the sword:userAgent element.", + SwordValidationInfoType.WARNING)); } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordTreatment.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, SwordNoOp.elementName())) - { - if( swordNoOp == null ) - { - swordNoOp = new SwordNoOp(); - result.addUnmarshallElementInfo(swordNoOp.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, SwordVerboseDescription.elementName())) - { - if( swordVerboseDescription == null ) - { - swordVerboseDescription = new SwordVerboseDescription(); - result.addUnmarshallElementInfo(swordVerboseDescription.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordVerboseDescription.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, SwordUserAgent.elementName())) - { - if( swordUserAgent == null ) - { - swordUserAgent = new SwordUserAgent(); - result.addUnmarshallElementInfo(swordUserAgent.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordUserAgent.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (isInstanceOf(element, SwordPackaging.elementName())) - { - if( swordPackaging == null ) - { - swordPackaging = new SwordPackaging(); - result.addUnmarshallElementInfo(swordPackaging.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordPackaging.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - else if (validationProperties != null ) - { - XmlName name = new XmlName(element); - if( ! isElementChecked(name) ) - { - SwordValidationInfo info = new SwordValidationInfo(name, - SwordValidationInfo.UNKNOWN_ELEMENT, - SwordValidationInfoType.INFO); - info.setContentDescription(element.getValue()); - result.addUnmarshallElementInfo(info); - } - } - - } // for - return result; - } - - public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) - throws UnmarshallException - { - - SwordValidationInfo result = unmarshallWithValidation(entry, validationProperties); - if( validationProperties != null ) - { - result = validate(result, validationProperties); - } - return result; - } - - /** - * - * @param elementName - */ - protected boolean isElementChecked(XmlName elementName) - { - if( elementName == null ) - { - return false; - } - - return elementName.equals(SwordNoOp.elementName()) | - elementName.equals(SwordUserAgent.elementName()) | - elementName.equals(SwordTreatment.elementName()) | - elementName.equals(SwordVerboseDescription.elementName()) | - elementName.equals(SwordPackaging.elementName()) | - super.isElementChecked(elementName); - } - - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, validationContext); - } - - protected SwordValidationInfo validate(SwordValidationInfo info, - Properties validationContext) - { - boolean validateAll = (info == null); - - SwordValidationInfo swordEntry = super.validate(info, validationContext); - - if( swordUserAgent == null ) - { - String agent = validationContext.getProperty(HttpHeaders.USER_AGENT); - - if( agent != null ) - { - swordEntry.addValidationInfo(new SwordValidationInfo(SwordUserAgent.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING + - " Clients SHOULD provide a User-Agent request-header (as described in [HTTP1.1] section 14.43). If provided, servers SHOULD store the value in the sword:userAgent element.", - SwordValidationInfoType.WARNING)); - } - } - else if( swordUserAgent != null && validateAll ) - { - info.addValidationInfo(swordUserAgent.validate(validationContext)); - } - - // additional rules for sword elements - if( swordTreatment == null ) - { - swordEntry.addValidationInfo(new SwordValidationInfo(SwordTreatment.elementName(), - SwordValidationInfo.MISSING_ELEMENT_ERROR + " MUST be present and contain either a human-readable statement describing treatment the deposited resource has received or a URI that dereferences to such a description.", - SwordValidationInfoType.ERROR)); - } - else if( swordTreatment != null && validateAll ) - { - info.addValidationInfo(swordTreatment.validate(validationContext)); - } - - // additional rules for sword elements - if( swordVerboseDescription == null ) - { - String verbose = validationContext.getProperty(HttpHeaders.X_VERBOSE); - if( verbose != null ) - { - swordEntry.addValidationInfo(new SwordValidationInfo(SwordVerboseDescription.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the client made the POST request with an X-Verbose:true header, the server SHOULD supply a verbose description of the deposit process.", - SwordValidationInfoType.WARNING)); - } - } - else if( swordVerboseDescription != null && validateAll ) - { - info.addValidationInfo(swordVerboseDescription.validate(validationContext)); - } - - if( swordNoOp == null ) - { - String noOp = validationContext.getProperty(HttpHeaders.X_NO_OP); - if( noOp != null ) - { - swordEntry.addValidationInfo(new SwordValidationInfo(SwordNoOp.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the client made the POST request with an X-No-Op:true header, the server SHOULD reflect this by including a sword:noOp element with a value of 'true' in the response. See Part A Section 3.1. Servers MAY use a value of 'false' to indicate that the deposit proceeded but MUST NOT use this element to signify an error.", - SwordValidationInfoType.WARNING)); - } - } - else if( swordNoOp != null && validateAll ) - { - info.addValidationInfo(swordNoOp.validate(validationContext)); - } - - if( swordPackaging == null ) - { - swordEntry.addValidationInfo(new SwordValidationInfo(SwordPackaging.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the POST request results in the creation of packaged resource, the server MAY use this element to declare the packaging type. If used it SHOULD take a value from [SWORD-TYPES].", - SwordValidationInfoType.INFO)); - } - else if( swordPackaging != null && validateAll ) - { - info.addValidationInfo(swordPackaging.validate(validationContext)); - } - - return swordEntry; - } - - /** - * Overrides the unmarshall method in the parent Entry. This will - * call the parent method to parse the general Atom elements and - * attributes. This method will then parse the remaining sword - * extensions that exist in the element. - * - * @param entry The entry to parse. - * - * @throws UnmarshallException If the entry is not an atom:entry - * or if there is an exception extracting the data. - */ - @Override - public void unmarshall(Element entry) - throws UnmarshallException - { - unmarshall(entry, null); - } + } + else if ( swordUserAgent != null && validateAll ) + { + info.addValidationInfo(swordUserAgent.validate(validationContext)); + } + + // additional rules for sword elements + if ( swordTreatment == null ) + { + swordEntry.addValidationInfo(new SwordValidationInfo(SwordTreatment.elementName(), + SwordValidationInfo.MISSING_ELEMENT_ERROR + " MUST be present and contain either a human-readable statement describing treatment the deposited resource has received or a URI that dereferences to such a description.", + SwordValidationInfoType.ERROR)); + } + else if ( swordTreatment != null && validateAll ) + { + info.addValidationInfo(swordTreatment.validate(validationContext)); + } + + // additional rules for sword elements + if ( swordVerboseDescription == null ) + { + String verbose = validationContext.getProperty(HttpHeaders.X_VERBOSE); + if ( verbose != null ) + { + swordEntry.addValidationInfo(new SwordValidationInfo(SwordVerboseDescription.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the client made the POST request with an X-Verbose:true header, the server SHOULD supply a verbose description of the deposit process.", + SwordValidationInfoType.WARNING)); + } + } + else if ( swordVerboseDescription != null && validateAll ) + { + info.addValidationInfo(swordVerboseDescription.validate(validationContext)); + } + + if ( swordNoOp == null ) + { + String noOp = validationContext.getProperty(HttpHeaders.X_NO_OP); + if ( noOp != null ) + { + swordEntry.addValidationInfo(new SwordValidationInfo(SwordNoOp.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the client made the POST request with an X-No-Op:true header, the server SHOULD reflect this by including a sword:noOp element with a value of 'true' in the response. See Part A Section 3.1. Servers MAY use a value of 'false' to indicate that the deposit proceeded but MUST NOT use this element to signify an error.", + SwordValidationInfoType.WARNING)); + } + } + else if ( swordNoOp != null && validateAll ) + { + info.addValidationInfo(swordNoOp.validate(validationContext)); + } + + if ( swordPackaging == null ) + { + swordEntry.addValidationInfo(new SwordValidationInfo(SwordPackaging.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING + " If the POST request results in the creation of packaged resource, the server MAY use this element to declare the packaging type. If used it SHOULD take a value from [SWORD-TYPES].", + SwordValidationInfoType.INFO)); + } + else if ( swordPackaging != null && validateAll ) + { + info.addValidationInfo(swordPackaging.validate(validationContext)); + } + + return swordEntry; + } + + /** + * Overrides the unmarshall method in the parent Entry. This will + * call the parent method to parse the general Atom elements and + * attributes. This method will then parse the remaining sword + * extensions that exist in the element. + * + * @param entry The entry to parse. + * + * @throws UnmarshallException If the entry is not an atom:entry + * or if there is an exception extracting the data. + */ + @Override + public void unmarshall(Element entry) + throws UnmarshallException + { + unmarshall(entry, null); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorDocument.java b/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorDocument.java index 321d7bb394..ee278a67be 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorDocument.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorDocument.java @@ -19,233 +19,237 @@ import nu.xom.Element; */ public class SWORDErrorDocument extends SWORDEntry { - /** - * Local name for the element. - */ - @Deprecated - public static final String ELEMENT_NAME = "error"; - - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_SWORD, "error", Namespaces.NS_SWORD); - - private static final XmlName ATTRIBUTE_HREF_NAME = - new XmlName(Namespaces.PREFIX_SWORD, "href", Namespaces.NS_SWORD); - - /** - * The Error URI + /** + * Local name for the element. */ - private String errorURI; - - /** - * Create the error document (intended to be used when unmarshalling an error document - * as this will set the errorURI) - */ - public SWORDErrorDocument() { - super(XML_NAME.getPrefix(), - XML_NAME.getLocalName(), - XML_NAME.getNamespace()); - } - - /** - * Create the error document - * - * @param errorURI The URI of the error - */ - public SWORDErrorDocument(String errorURI) { - this(); - this.errorURI = errorURI; - } - - /** - * Get the element name. - */ - public static XmlName elementName() - { - return XML_NAME; - } - - /** - * Overrides the marshal method in the parent SWORDEntry. This will - * call the parent marshal method and then add the additional - * elements that have been added in this subclass. - */ - public Element marshall() - { - Element entry = new Element(getQualifiedName(), Namespaces.NS_SWORD); - entry.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD); - entry.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM); - Attribute error = new Attribute("href", errorURI); - entry.addAttribute(error); - super.marshallElements(entry); - return entry; - } - - /** - * Overrides the unmarshal method in the parent SWORDEntry. This will - * call the parent method to parse the general Atom elements and - * attributes. This method will then parse the remaining sword - * extensions that exist in the element. - * - * @param entry The entry to parse. - * - * @throws UnmarshallException If the entry is not an atom:entry - * or if there is an exception extracting the data. - */ - public void unmarshall(Element entry) throws UnmarshallException - { - unmarshall(entry, null); - } - - /** - * - * @param entry - * @param validationProperties - * @throws org.purl.sword.base.UnmarshallException - */ - public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) - throws UnmarshallException - { - SwordValidationInfo result = super.unmarshall(entry, validationProperties); - result.clearValidationItems(); - - errorURI = entry.getAttributeValue(ATTRIBUTE_HREF_NAME.getLocalName()); - - if( validationProperties != null ) - { - result = validate(result, validationProperties); - } - - return result; - } - - /** - * This method overrides the XmlElement definition so that it can allow - * the definition of the href attribute. All other attributes are - * shown as 'Unknown Attribute' info elements. - * - * @param element The element that contains the attributes - * @param info The info object that will hold the validation info. - */ - @Override - protected void processUnexpectedAttributes(Element element, SwordValidationInfo info) - { - int attributeCount = element.getAttributeCount(); - Attribute attribute = null; - - for( int i = 0; i < attributeCount; i++ ) + @Deprecated + public static final String ELEMENT_NAME = "error"; + + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_SWORD, "error", Namespaces.NS_SWORD); + + private static final XmlName ATTRIBUTE_HREF_NAME = + new XmlName(Namespaces.PREFIX_SWORD, "href", Namespaces.NS_SWORD); + + /** + * The Error URI + */ + private String errorURI; + + /** + * Create the error document (intended to be used when unmarshalling an error document + * as this will set the errorURI) + */ + public SWORDErrorDocument() { + super(XML_NAME.getPrefix(), + XML_NAME.getLocalName(), + XML_NAME.getNamespace()); + } + + /** + * Create the error document + * + * @param errorURI The URI of the error + */ + public SWORDErrorDocument(String errorURI) { + this(); + this.errorURI = errorURI; + } + + /** + * Get the element name. + * + * @return the element name. + */ + public static XmlName elementName() + { + return XML_NAME; + } + + /** + * Overrides the marshal method in the parent SWORDEntry. This will + * call the parent marshal method and then add the additional + * elements that have been added in this subclass. + */ + public Element marshall() + { + Element entry = new Element(getQualifiedName(), Namespaces.NS_SWORD); + entry.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD); + entry.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM); + Attribute error = new Attribute("href", errorURI); + entry.addAttribute(error); + super.marshallElements(entry); + return entry; + } + + /** + * Overrides the unmarshal method in the parent SWORDEntry. This will + * call the parent method to parse the general Atom elements and + * attributes. This method will then parse the remaining sword + * extensions that exist in the element. + * + * @param entry The entry to parse. + * + * @throws UnmarshallException If the entry is not an atom:entry + * or if there is an exception extracting the data. + */ + public void unmarshall(Element entry) throws UnmarshallException + { + unmarshall(entry, null); + } + + /** + * + * @param entry an element to unmarshall. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @throws org.purl.sword.base.UnmarshallException passed through. + */ + public SwordValidationInfo unmarshall(Element entry, Properties validationProperties) + throws UnmarshallException + { + SwordValidationInfo result = super.unmarshall(entry, validationProperties); + result.clearValidationItems(); + + errorURI = entry.getAttributeValue(ATTRIBUTE_HREF_NAME.getLocalName()); + + if ( validationProperties != null ) { - attribute = element.getAttribute(i); - if( ! ATTRIBUTE_HREF_NAME.getLocalName().equals(attribute.getQualifiedName()) ) - { - - XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), - attribute.getLocalName(), - attribute.getNamespaceURI()); - - SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO); - item.setContentDescription(attribute.getValue()); - info.addUnmarshallAttributeInfo(item); - } + result = validate(result, validationProperties); } - } - - /** - * - * @param validationContext - */ - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, validationContext); - } - - /** - * - * @param info - * @param validationContext - */ - protected SwordValidationInfo validate(SwordValidationInfo info, - Properties validationContext) - { - - if( errorURI == null ) - { - info.addValidationInfo(new SwordValidationInfo(xmlName, ATTRIBUTE_HREF_NAME, - SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, - SwordValidationInfoType.WARNING)); - } - else - { - boolean validUri = true; - if(errorURI.startsWith("http://purl.org/net/sword/error/")) - { - // check that the list of codes - if( ! (errorURI.equals(ErrorCodes.ERROR_CONTENT) || - errorURI.equals(ErrorCodes.ERROR_CHECKSUM_MISMATCH) || - errorURI.equals(ErrorCodes.ERROR_BAD_REQUEST) || - errorURI.equals(ErrorCodes.TARGET_OWNER_UKNOWN) || - errorURI.equals(ErrorCodes.MEDIATION_NOT_ALLOWED)) ) + + return result; + } + + /** + * This method overrides the XmlElement definition so that it can allow + * the definition of the href attribute. All other attributes are + * shown as 'Unknown Attribute' info elements. + * + * @param element The element that contains the attributes + * @param info The info object that will hold the validation info. + */ + @Override + protected void processUnexpectedAttributes(Element element, SwordValidationInfo info) + { + int attributeCount = element.getAttributeCount(); + Attribute attribute = null; + + for ( int i = 0; i < attributeCount; i++ ) + { + attribute = element.getAttribute(i); + if ( ! ATTRIBUTE_HREF_NAME.getLocalName().equals(attribute.getQualifiedName()) ) { - info.addValidationInfo(new SwordValidationInfo(xmlName, - ATTRIBUTE_HREF_NAME, - "Errors in the SWORD namespace are reserved and legal values are enumerated in the SWORD 1.3 specification. Implementations MAY define their own errors, but MUST use a different namespace to do so.", - SwordValidationInfoType.ERROR)); - validUri = false; + + XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), + attribute.getLocalName(), + attribute.getNamespaceURI()); + + SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO); + item.setContentDescription(attribute.getValue()); + info.addUnmarshallAttributeInfo(item); } - } - - if( validUri ) - { - SwordValidationInfo item = new SwordValidationInfo(xmlName, ATTRIBUTE_HREF_NAME); - item.setContentDescription(errorURI); - info.addAttributeValidationInfo(item); - } - } - return info; - } - - - /** - * Get the error URI - * - * @return the error URI - */ - public String getErrorURI() - { - return errorURI; - } - - /** - * set the error URI - * - * @param error the error URI - */ - public void setErrorURI(String error) - { - errorURI = error; - } - - /** - * Main method to perform a brief test of the class - * - * @param args - */ - /*public static void main(String[] args) - { - SWORDErrorDocumentTest sed = new SWORDErrorDocumentTest(ErrorCodes.MEDIATION_NOT_ALLOWED); - sed.setNoOp(true); - sed.setTreatment("Short back and shine"); - sed.setId("123456789"); - Title t = new Title(); - t.setContent("My first book"); - sed.setTitle(t); - Author a = new Author(); - a.setName("Lewis, Stuart"); - a.setEmail("stuart@example.com"); - sed.addAuthors(a); - - System.out.println(sed.marshall().toXML()); - } - */ + } + } + + /** + * + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, validationContext); + } + + /** + * + * @param info add results to this. + * @param validationContext unused. + * @return SWORD validation info + */ + protected SwordValidationInfo validate(SwordValidationInfo info, + Properties validationContext) + { + + if ( errorURI == null ) + { + info.addValidationInfo(new SwordValidationInfo(xmlName, ATTRIBUTE_HREF_NAME, + SwordValidationInfo.MISSING_ATTRIBUTE_WARNING, + SwordValidationInfoType.WARNING)); + } + else + { + boolean validUri = true; + if (errorURI.startsWith("http://purl.org/net/sword/error/")) + { + // check that the list of codes + if ( ! (errorURI.equals(ErrorCodes.ERROR_CONTENT) || + errorURI.equals(ErrorCodes.ERROR_CHECKSUM_MISMATCH) || + errorURI.equals(ErrorCodes.ERROR_BAD_REQUEST) || + errorURI.equals(ErrorCodes.TARGET_OWNER_UKNOWN) || + errorURI.equals(ErrorCodes.MEDIATION_NOT_ALLOWED)) ) + { + info.addValidationInfo(new SwordValidationInfo(xmlName, + ATTRIBUTE_HREF_NAME, + "Errors in the SWORD namespace are reserved and legal values are enumerated in the SWORD 1.3 specification. Implementations MAY define their own errors, but MUST use a different namespace to do so.", + SwordValidationInfoType.ERROR)); + validUri = false; + } + } + + if ( validUri ) + { + SwordValidationInfo item = new SwordValidationInfo(xmlName, ATTRIBUTE_HREF_NAME); + item.setContentDescription(errorURI); + info.addAttributeValidationInfo(item); + } + } + return info; + } + + + /** + * Get the error URI + * + * @return the error URI + */ + public String getErrorURI() + { + return errorURI; + } + + /** + * set the error URI + * + * @param error the error URI + */ + public void setErrorURI(String error) + { + errorURI = error; + } + + /** + * Main method to perform a brief test of the class + * + * @param args the command line arguments given + */ +/*public static void main(String[] args) + { + SWORDErrorDocumentTest sed = new SWORDErrorDocumentTest(ErrorCodes.MEDIATION_NOT_ALLOWED); + sed.setNoOp(true); + sed.setTreatment("Short back and shine"); + sed.setId("123456789"); + Title t = new Title(); + t.setContent("My first book"); + sed.setTitle(t); + Author a = new Author(); + a.setName("Lewis, Stuart"); + a.setEmail("stuart@example.com"); + sed.addAuthors(a); + + System.out.println(sed.marshall().toXML()); + } +*/ } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorException.java b/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorException.java index fb725a5f84..8287eed11b 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorException.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/SWORDErrorException.java @@ -15,17 +15,17 @@ package org.purl.sword.base; */ public class SWORDErrorException extends Exception { - /** The error URI (defined in ErrorCodes class) */ - private String errorURI; - - /** The HTTP error code (defined in HTTPServletResponse class) */ - private int status; - - /** The error message given by the repository */ - private String description; - - - /** + /** The error URI (defined in ErrorCodes class) */ + private String errorURI; + + /** The HTTP error code (defined in HTTPServletResponse class) */ + private int status; + + /** The error message given by the repository */ + private String description; + + + /** * Create a new instance and store the specified data. * * @param errorURI The errorURI of the exception being thrown @@ -47,33 +47,33 @@ public class SWORDErrorException extends Exception } - /** - * @return the errorURI - */ - public String getErrorURI() { - return errorURI; - } + /** + * @return the errorURI + */ + public String getErrorURI() { + return errorURI; + } - /** - * @return the status - */ - public int getStatus() { - return status; - } - - /** - * Set the status - * - * @param status The HTTP status code - */ - public void setStatus(int status) { - this.status = status; - } + /** + * @return the status + */ + public int getStatus() { + return status; + } + + /** + * Set the status + * + * @param status The HTTP status code + */ + public void setStatus(int status) { + this.status = status; + } - /** - * @return the description - */ - public String getDescription() { - return description; - } -} \ No newline at end of file + /** + * @return the description + */ + public String getDescription() { + return description; + } +} diff --git a/dspace-sword/src/main/java/org/purl/sword/base/Service.java b/dspace-sword/src/main/java/org/purl/sword/base/Service.java index 42b8de782b..0ce9a124ca 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/Service.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/Service.java @@ -28,573 +28,579 @@ import org.purl.sword.atom.Generator; public class Service extends XmlElement implements SwordElementInterface { - private SwordVersion swordVersion; - - private SwordNoOp swordNoOp; - - private SwordVerbose swordVerbose; - - private SwordMaxUploadSize swordMaxUploadSize; - - /** - * The details of the server software that generated the service document. - */ - private Generator generator; - - /** - * List of Workspaces. - */ - private List workspaces; - - /** Logger */ - private static Logger log = Logger.getLogger(Service.class); - - /** - * MaxUploadSize - */ - @Deprecated - public static final String ELEMENT_GENERATOR = "generator"; - - /** - * Name for this element. - */ - @Deprecated - public static final String ELEMENT_NAME = "service"; - - /** - * The XML NAME (prefix, local name and namespace) for this element. - */ - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_APP, "service", Namespaces.NS_APP); - - - /** - * Create a new instance. - */ - public Service() - { - super(XML_NAME); - initialise(); - } - - /** - * Create a new instance. - * - * @param version The service compliance level. - */ - public Service(String version) - { - this(); - setVersion(version); - } - - /** - * Create a new instance with the specified compliance level, noOp and - * verbose values. - * - * @param version The service compliance level. - * @param noOp The noOp. - * @param verbose The verbose element. - */ - public Service(String version, boolean noOp, boolean verbose) - { - this(); - setVersion(version); - setNoOp(noOp); - setVerbose(verbose); - } - - public static XmlName elementName() - { - return XML_NAME; - } - /** - * Initialise the data structures in this tool. - */ - private void initialise() - { - workspaces = new ArrayList(); - swordVersion = null; - swordNoOp = null; - swordVerbose = null; - swordMaxUploadSize = null; - generator = null; - } - - - /** - * Get the SWORD version. - * - * @return The version. - */ - public final String getVersion() - { - if( swordVersion == null ) - { - return null; - } - return swordVersion.getContent(); - } - - /** - * Set the SWORD version. - * - * @param version The version. - */ - public final void setVersion(String version) - { - if( version == null ) - { - // clear the value - swordVersion = null; - return; - } - - swordVersion = new SwordVersion(version); - } - - /** - * Get the NoOp value. - * - * @return The value. - */ - public final boolean isNoOp() - { - if( swordNoOp == null ) - { - return false; - } - - return swordNoOp.getContent(); - } - - /** - * Set the NoOp value. - * - * @param noOp The value. - */ - public final void setNoOp(boolean noOp) - { - swordNoOp = new SwordNoOp(noOp); - } - - /** - * Determine if the NoOp value has been set. This should be called to - * check if an item has been programmatically set and does not have a - * default value. - * - * @return True if it has been set programmatically. Otherwise, false. - */ - public final boolean isNoOpSet() - { - if( swordNoOp == null ) - { - return false; - } - - return swordNoOp.isSet(); - } - - /** - * Get the Verbose setting. - * - * @return The value. - */ - public final boolean isVerbose() - { - if( swordVerbose == null ) - { - return false; - } - - return swordVerbose.getContent(); - } - - /** - * Set the Verbose value. - * - * @param verbose The value. - */ - public final void setVerbose(boolean verbose) - { - swordVerbose = new SwordVerbose(verbose); - } - - /** - * Determine if the Verbose value has been set. This should be called to - * check if an item has been programmatically set and does not have a - * default value. - * - * @return True if it has been set programmatically. Otherwise, false. - */ - public final boolean isVerboseSet() - { - if( swordVerbose == null ) - { - return false; - } - - return swordVerbose.isSet(); - } - - /** - * Set the maximum file upload size in kB - * - * @param maxUploadSize Max upload file size in kB - */ - public final void setMaxUploadSize(int maxUploadSize) - { - swordMaxUploadSize = new SwordMaxUploadSize(maxUploadSize); - } - - /** - * Get the maximum upload file size (in kB) - * - * @return the maximum file upload size. If no value has been set, this will - * be equal to Integer.MIN_VALUE. - */ - public final int getMaxUploadSize() - { - if( swordMaxUploadSize == null ) - { - return Integer.MIN_VALUE; - } - return swordMaxUploadSize.getContent(); - } - - public final Generator getGenerator() - { - return generator; - } - - public final void setGenerator(Generator generator) - { - this.generator = generator; - } - - /** - * Get an Iterator over the workspaces. - * - * @return The workspace. - */ - public final Iterator getWorkspaces() - { - return workspaces.iterator(); - } - - /** - * Get a List of workspaces - * - * @return The workspaces in a List - */ - public final List getWorkspacesList() - { - return workspaces; - } - - /** - * Add a workspace. - * - * @param workspace The workspace. - */ - public final void addWorkspace(Workspace workspace) - { - this.workspaces.add(workspace); - } - - /** - * Clear the list of workspaces. - */ - public final void clearWorkspaces() - { - this.workspaces.clear(); - } - - /** - * Marshal the data in this object to an Element object. - * - * @return A XOM Element that holds the data for this Content element. - */ - public final Element marshall( ) - { - Element service = new Element(getQualifiedName(), Namespaces.NS_APP); - service.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM); - service.addNamespaceDeclaration(Namespaces.PREFIX_DC_TERMS, Namespaces.NS_DC_TERMS); - service.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD); - - if( swordVersion != null ) - { - service.appendChild(swordVersion.marshall()); - } - - if( swordVerbose != null ) - { - service.appendChild(swordVerbose.marshall()); - } - - if( swordNoOp != null ) - { - service.appendChild(swordNoOp.marshall()); - } - - if( swordMaxUploadSize != null ) - { - service.appendChild(swordMaxUploadSize.marshall()); - } - - if( generator != null ) - { - service.appendChild(generator.marshall()); - } - - for (Workspace item : workspaces) - { - service.appendChild(item.marshall()); - } + private SwordVersion swordVersion; + + private SwordNoOp swordNoOp; + + private SwordVerbose swordVerbose; + + private SwordMaxUploadSize swordMaxUploadSize; + + /** + * The details of the server software that generated the service document. + */ + private Generator generator; + + /** + * List of Workspaces. + */ + private List workspaces; + + /** Logger */ + private static Logger log = Logger.getLogger(Service.class); + + /** + * MaxUploadSize + */ + @Deprecated + public static final String ELEMENT_GENERATOR = "generator"; + + /** + * Name for this element. + */ + @Deprecated + public static final String ELEMENT_NAME = "service"; + + /** + * The XML NAME (prefix, local name and namespace) for this element. + */ + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_APP, "service", Namespaces.NS_APP); + + + /** + * Create a new instance. + */ + public Service() + { + super(XML_NAME); + initialise(); + } + + /** + * Create a new instance. + * + * @param version The service compliance level. + */ + public Service(String version) + { + this(); + setVersion(version); + } + + /** + * Create a new instance with the specified compliance level, noOp and + * verbose values. + * + * @param version The service compliance level. + * @param noOp The noOp. + * @param verbose The verbose element. + */ + public Service(String version, boolean noOp, boolean verbose) + { + this(); + setVersion(version); + setNoOp(noOp); + setVerbose(verbose); + } + + public static XmlName elementName() + { + return XML_NAME; + } + /** + * Initialise the data structures in this tool. + */ + private void initialise() + { + workspaces = new ArrayList(); + swordVersion = null; + swordNoOp = null; + swordVerbose = null; + swordMaxUploadSize = null; + generator = null; + } + + + /** + * Get the SWORD version. + * + * @return The version. + */ + public final String getVersion() + { + if ( swordVersion == null ) + { + return null; + } + return swordVersion.getContent(); + } + + /** + * Set the SWORD version. + * + * @param version The version. + */ + public final void setVersion(String version) + { + if ( version == null ) + { + // clear the value + swordVersion = null; + return; + } + + swordVersion = new SwordVersion(version); + } + + /** + * Get the NoOp value. + * + * @return The value. + */ + public final boolean isNoOp() + { + if ( swordNoOp == null ) + { + return false; + } + + return swordNoOp.getContent(); + } + + /** + * Set the NoOp value. + * + * @param noOp The value. + */ + public final void setNoOp(boolean noOp) + { + swordNoOp = new SwordNoOp(noOp); + } + + /** + * Determine if the NoOp value has been set. This should be called to + * check if an item has been programmatically set and does not have a + * default value. + * + * @return True if it has been set programmatically. Otherwise, false. + */ + public final boolean isNoOpSet() + { + if ( swordNoOp == null ) + { + return false; + } + + return swordNoOp.isSet(); + } + + /** + * Get the Verbose setting. + * + * @return The value. + */ + public final boolean isVerbose() + { + if ( swordVerbose == null ) + { + return false; + } + + return swordVerbose.getContent(); + } + + /** + * Set the Verbose value. + * + * @param verbose The value. + */ + public final void setVerbose(boolean verbose) + { + swordVerbose = new SwordVerbose(verbose); + } + + /** + * Determine if the Verbose value has been set. This should be called to + * check if an item has been programmatically set and does not have a + * default value. + * + * @return True if it has been set programmatically. Otherwise, false. + */ + public final boolean isVerboseSet() + { + if ( swordVerbose == null ) + { + return false; + } + + return swordVerbose.isSet(); + } + + /** + * Set the maximum file upload size in kB + * + * @param maxUploadSize Max upload file size in kB + */ + public final void setMaxUploadSize(int maxUploadSize) + { + swordMaxUploadSize = new SwordMaxUploadSize(maxUploadSize); + } + + /** + * Get the maximum upload file size (in kB) + * + * @return the maximum file upload size. If no value has been set, this will + * be equal to Integer.MIN_VALUE. + */ + public final int getMaxUploadSize() + { + if ( swordMaxUploadSize == null ) + { + return Integer.MIN_VALUE; + } + return swordMaxUploadSize.getContent(); + } + + public final Generator getGenerator() + { + return generator; + } + + public final void setGenerator(Generator generator) + { + this.generator = generator; + } + + /** + * Get an Iterator over the workspaces. + * + * @return The workspace. + */ + public final Iterator getWorkspaces() + { + return workspaces.iterator(); + } + + /** + * Get a List of workspaces + * + * @return The workspaces in a List + */ + public final List getWorkspacesList() + { + return workspaces; + } + + /** + * Add a workspace. + * + * @param workspace The workspace. + */ + public final void addWorkspace(Workspace workspace) + { + this.workspaces.add(workspace); + } + + /** + * Clear the list of workspaces. + */ + public final void clearWorkspaces() + { + this.workspaces.clear(); + } + + /** + * Marshal the data in this object to an Element object. + * + * @return A XOM Element that holds the data for this Content element. + */ + public final Element marshall( ) + { + Element service = new Element(getQualifiedName(), Namespaces.NS_APP); + service.addNamespaceDeclaration(Namespaces.PREFIX_ATOM, Namespaces.NS_ATOM); + service.addNamespaceDeclaration(Namespaces.PREFIX_DC_TERMS, Namespaces.NS_DC_TERMS); + service.addNamespaceDeclaration(Namespaces.PREFIX_SWORD, Namespaces.NS_SWORD); + + if ( swordVersion != null ) + { + service.appendChild(swordVersion.marshall()); + } + + if ( swordVerbose != null ) + { + service.appendChild(swordVerbose.marshall()); + } + + if ( swordNoOp != null ) + { + service.appendChild(swordNoOp.marshall()); + } + + if ( swordMaxUploadSize != null ) + { + service.appendChild(swordMaxUploadSize.marshall()); + } + + if ( generator != null ) + { + service.appendChild(generator.marshall()); + } + + for (Workspace item : workspaces) + { + service.appendChild(item.marshall()); + } + + return service; + } - return service; - } - - /** - * Unmarshal the content element into the data in this object. - * - * @throws UnmarshallException If the element does not contain a - * content element or if there are problems - * accessing the data. - */ - public final void unmarshall( Element service ) - throws UnmarshallException - { - unmarshall(service, null); - } - - /** - * - * @param service - * @param validationProperties - * @throws org.purl.sword.base.UnmarshallException - */ - public final SwordValidationInfo unmarshall( Element service, Properties validationProperties) - throws UnmarshallException - { - if (!isInstanceOf(service, xmlName)) - { - return handleIncorrectElement(service, validationProperties); - } - - ArrayList validationItems = - new ArrayList(); - - try - { - initialise(); - - // Retrieve all of the sub-elements - Elements elements = service.getChildElements(); - Element element = null; - int length = elements.size(); - - for (int i = 0; i < length; i++ ) - { - element = elements.get(i); - - if (isInstanceOf(element, SwordVersion.elementName() ) ) + /** + * Unmarshal the content element into the data in this object. + * + * @throws UnmarshallException If the element does not contain a + * content element or if there are problems + * accessing the data. + */ + public final void unmarshall( Element service ) + throws UnmarshallException + { + unmarshall(service, null); + } + + /** + * + * @param service + * element to unmarshall + * @param validationProperties + * FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException If the element does not contain a + * content element or if there are problems + * accessing the data. + */ + public final SwordValidationInfo unmarshall(Element service, Properties validationProperties) + throws UnmarshallException + { + if (!isInstanceOf(service, xmlName)) + { + return handleIncorrectElement(service, validationProperties); + } + + ArrayList validationItems = + new ArrayList(); + + try + { + initialise(); + + // Retrieve all of the sub-elements + Elements elements = service.getChildElements(); + Element element = null; + int length = elements.size(); + + for (int i = 0; i < length; i++ ) { - //validationItems.add(unmarshallVersion(element, validate)); - if( swordVersion == null ) + element = elements.get(i); + + if (isInstanceOf(element, SwordVersion.elementName() ) ) { - swordVersion = new SwordVersion(); - validationItems.add(swordVersion.unmarshall(element, validationProperties)); + //validationItems.add(unmarshallVersion(element, validate)); + if ( swordVersion == null ) + { + swordVersion = new SwordVersion(); + validationItems.add(swordVersion.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordVersion.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } } - else if( validationProperties != null ) + else if (isInstanceOf(element, SwordVerbose.elementName())) { - SwordValidationInfo info = new SwordValidationInfo(SwordVersion.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); + if ( swordVerbose == null ) + { + swordVerbose = new SwordVerbose(); + validationItems.add(swordVerbose.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordVerbose.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if (isInstanceOf(element, SwordNoOp.elementName()) ) + { + if ( swordNoOp == null ) + { + swordNoOp = new SwordNoOp(); + validationItems.add(swordNoOp.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if (isInstanceOf(element, SwordMaxUploadSize.elementName())) + { + if ( swordMaxUploadSize == null ) + { + swordMaxUploadSize = new SwordMaxUploadSize(); + validationItems.add(swordMaxUploadSize.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if (isInstanceOf(element, Generator.elementName())) + { + if ( generator == null ) + { + generator = new Generator(); + validationItems.add(generator.unmarshall(element, validationProperties)); + } + else if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if (isInstanceOf(element, Workspace.elementName() )) + { + Workspace workspace = new Workspace( ); + validationItems.add(workspace.unmarshall(element, validationProperties)); + workspaces.add(workspace); + } + else if ( validationProperties != null ) + { + // report on any additional items. They are permitted because of + // the Atom/APP specification. Report the items for information + XmlName name = new XmlName(element.getNamespacePrefix(), + element.getLocalName(), + element.getNamespaceURI()); + + validationItems.add(new SwordValidationInfo(name, + SwordValidationInfo.UNKNOWN_ELEMENT, + SwordValidationInfoType.INFO)); } } - else if (isInstanceOf(element, SwordVerbose.elementName())) + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in Service: " + ex.getMessage()); + ex.printStackTrace(); + throw new UnmarshallException("Unable to parse element in Service", ex); + } + + // now process the validation information + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, validationProperties); + } + return result; + + } + + + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, validationContext); + } + + /** + * + * @param existing add results to this. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return validation information + */ + protected SwordValidationInfo validate(List existing, + Properties validationContext) + { + boolean validateAll = (existing != null); + + SwordValidationInfo result = new SwordValidationInfo(xmlName); + + // process the basic rules + if ( swordVersion == null ) + { + SwordValidationInfo info = new SwordValidationInfo(SwordVersion.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING, + SwordValidationInfoType.WARNING); + result.addValidationInfo(info); + } + + if ( generator == null ) + { + SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING, + SwordValidationInfoType.WARNING); + result.addValidationInfo(info); + } + + + if ( workspaces == null || workspaces.size() == 0 ) + { + SwordValidationInfo info = new SwordValidationInfo(Workspace.elementName(), + "This element SHOULD be included unless the authenticated user does not have permission to deposit.", + SwordValidationInfoType.WARNING); + result.addValidationInfo(info); + } + + if ( validateAll ) + { + if ( swordVersion != null ) { - if( swordVerbose == null ) - { - swordVerbose = new SwordVerbose(); - validationItems.add(swordVerbose.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordVerbose.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } + result.addValidationInfo(swordVersion.validate(validationContext)); } - else if (isInstanceOf(element, SwordNoOp.elementName()) ) + + if ( swordNoOp != null ) { - if( swordNoOp == null ) - { - swordNoOp = new SwordNoOp(); - validationItems.add(swordNoOp.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } + result.addValidationInfo(swordNoOp.validate(validationContext)); } - else if (isInstanceOf(element, SwordMaxUploadSize.elementName())) + + if ( swordVerbose != null ) { - if( swordMaxUploadSize == null ) - { - swordMaxUploadSize = new SwordMaxUploadSize(); - validationItems.add(swordMaxUploadSize.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordNoOp.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } + result.addValidationInfo(swordVerbose.validate(validationContext)); } - else if (isInstanceOf(element, Generator.elementName())) + + if ( swordMaxUploadSize != null ) { - if( generator == null ) - { - generator = new Generator(); - validationItems.add(generator.unmarshall(element, validationProperties)); - } - else if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } + result.addValidationInfo(swordMaxUploadSize.validate(validationContext)); } - else if (isInstanceOf(element, Workspace.elementName() )) + + if ( generator != null ) { - Workspace workspace = new Workspace( ); - validationItems.add(workspace.unmarshall(element, validationProperties)); - workspaces.add(workspace); + result.addValidationInfo(generator.validate(validationContext)); } - else if( validationProperties != null ) + + Iterator iterator = workspaces.iterator(); + while ( iterator.hasNext() ) { - // report on any additional items. They are permitted because of - // the Atom/APP specification. Report the items for information - XmlName name = new XmlName(element.getNamespacePrefix(), - element.getLocalName(), - element.getNamespaceURI()); - - validationItems.add(new SwordValidationInfo(name, - SwordValidationInfo.UNKNOWN_ELEMENT, - SwordValidationInfoType.INFO)); + result.addValidationInfo(iterator.next().validate(validationContext)); } - } - } - catch( Exception ex ) - { - log.error("Unable to parse an element in Service: " + ex.getMessage()); - ex.printStackTrace(); - throw new UnmarshallException("Unable to parse element in Service", ex); - } - - // now process the validation information - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, validationProperties); - } - return result; - - } - - - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, validationContext); - } - - /** - * - * @param existing - */ - protected SwordValidationInfo validate(List existing, - Properties validationContext) - { - - boolean validateAll = (existing != null); - - SwordValidationInfo result = new SwordValidationInfo(xmlName); - - // process the basic rules - if( swordVersion == null ) - { - SwordValidationInfo info = new SwordValidationInfo(SwordVersion.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING, - SwordValidationInfoType.WARNING); - result.addValidationInfo(info); - } - - if( generator == null ) - { - SwordValidationInfo info = new SwordValidationInfo(Generator.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING, - SwordValidationInfoType.WARNING); - result.addValidationInfo(info); - } - - - if( workspaces == null || workspaces.size() == 0 ) - { - SwordValidationInfo info = new SwordValidationInfo(Workspace.elementName(), - "This element SHOULD be included unless the authenticated user does not have permission to deposit.", - SwordValidationInfoType.WARNING); - result.addValidationInfo(info); - } - - if( validateAll ) - { - if( swordVersion != null ) - { - result.addValidationInfo(swordVersion.validate(validationContext)); - } - - if( swordNoOp != null ) - { - result.addValidationInfo(swordNoOp.validate(validationContext)); - } - - if( swordVerbose != null ) - { - result.addValidationInfo(swordVerbose.validate(validationContext)); - } - - if( swordMaxUploadSize != null ) - { - result.addValidationInfo(swordMaxUploadSize.validate(validationContext)); - } - - if( generator != null ) - { - result.addValidationInfo(generator.validate(validationContext)); - } - - Iterator iterator = workspaces.iterator(); - while( iterator.hasNext() ) - { - result.addValidationInfo(iterator.next().validate(validationContext)); - } - } - - result.addUnmarshallValidationInfo(existing, null); - return result; - } + } + + result.addUnmarshallValidationInfo(existing, null); + return result; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/ServiceDocument.java b/dspace-sword/src/main/java/org/purl/sword/base/ServiceDocument.java index 2307e5d4a0..498cf606ad 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/ServiceDocument.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/ServiceDocument.java @@ -26,138 +26,149 @@ import nu.xom.Serializer; * @author Neil Taylor */ public class ServiceDocument { - /** - * The Service object that is held by this object. - */ - private Service service; + /** + * The Service object that is held by this object. + */ + private Service service; - /** - * Create a new instance and set the initial service level to Zero. - */ - public ServiceDocument() { - - } + /** + * Create a new instance and set the initial service level to Zero. + */ + public ServiceDocument() { + + } - /** - * Create a new instance and set the specified service level. - * - * @param version - * The SWORD version. - */ - public ServiceDocument(String version) { - service = new Service(version); - } + /** + * Create a new instance and set the specified service level. + * + * @param version + * The SWORD version. + */ + public ServiceDocument(String version) { + service = new Service(version); + } - /** - * Create a new instance and store the specified Service document. - * - * @param service - * The Service object. - */ - public ServiceDocument(Service service) { - this.service = service; - } + /** + * Create a new instance and store the specified Service document. + * + * @param service + * The Service object. + */ + public ServiceDocument(Service service) { + this.service = service; + } - /** - * Set the service object associated with this document. - * - * @param service - * The new Service object. - */ - public void setService(Service service) { - this.service = service; - } + /** + * Set the service object associated with this document. + * + * @param service + * The new Service object. + */ + public void setService(Service service) { + this.service = service; + } - /** - * Retrieve the Service object associated with this document. - * - * @return The Service object. - */ - public Service getService() { - return service; - } + /** + * Retrieve the Service object associated with this document. + * + * @return The Service object. + */ + public Service getService() { + return service; + } - /** - * Return the Service Document in its XML form. - * - * @return The ServiceDocument - */ - public String toString() { - return marshall(); - } + /** + * Return the Service Document in its XML form. + * + * @return The ServiceDocument + */ + public String toString() { + return marshall(); + } - /** - * Marshall the data in the Service element and generate a String - * representation. The returned string is UTF-8 format. - * - * @return A string of XML, or null if there was an error - * marshalling the data. - */ - public String marshall() { - try { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - Serializer serializer = new Serializer(stream, "UTF-8"); - serializer.setIndent(3); - //serializer.setMaxLength(64); + /** + * Marshall the data in the Service element and generate a String + * representation. The returned string is UTF-8 format. + * + * @return A string of XML, or null if there was an error + * marshalling the data. + */ + public String marshall() { + try { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Serializer serializer = new Serializer(stream, "UTF-8"); + serializer.setIndent(3); + //serializer.setMaxLength(64); - Document doc = new Document(service.marshall()); - serializer.write(doc); + Document doc = new Document(service.marshall()); + serializer.write(doc); - return stream.toString(); - } catch (IOException ex) { - System.err.println(ex); - } + return stream.toString(); + } catch (IOException ex) { + System.err.println(ex); + } - return null; - } + return null; + } - /** - * Convert the specified XML string into a set of objects used within the - * service. A new Service object will be created and stored. This will - * dispose of any previous Service object associated with this object. - * - * @param xml - * The XML string. - * @throws UnmarshallException - * If there was a problem unmarshalling the data. This might be - * as a result of an error in parsing the XML string, extracting - * information. - */ - public void unmarshall(String xml) throws UnmarshallException + /** + * Convert the specified XML string into a set of objects used within the + * service. A new Service object will be created and stored. This will + * dispose of any previous Service object associated with this object. + * + * @param xml + * The XML string. + * @throws UnmarshallException + * If there was a problem unmarshalling the data. This might be + * as a result of an error in parsing the XML string, extracting + * information. + */ + public void unmarshall(String xml) throws UnmarshallException { unmarshall(xml, null); } /** - * - * @param xml - * @param validationProperties - * @throws org.purl.sword.base.UnmarshallException + * Convert the specified XML string into a set of objects used within the + * service. A new Service object will be created and stored. This will + * dispose of any previous Service object associated with this object. + * + * @param xml The XML string. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException + * If there was a problem unmarshalling the data. This might be + * as a result of an error in parsing the XML string, extracting + * information. */ public SwordValidationInfo unmarshall(String xml, Properties validationProperties) throws UnmarshallException { - try { - Builder builder = new Builder(); - Document doc = builder.build(xml, Namespaces.PREFIX_APP); + try { + Builder builder = new Builder(); + Document doc = builder.build(xml, Namespaces.PREFIX_APP); Element root = doc.getRootElement(); - return unmarshall(root, validationProperties); - } catch (ParsingException ex) { - throw new UnmarshallException("Unable to parse the XML", ex); - } catch (IOException ex) { - throw new UnmarshallException("Error acessing the file?", ex); - } - } + return unmarshall(root, validationProperties); + } catch (ParsingException ex) { + throw new UnmarshallException("Unable to parse the XML", ex); + } catch (IOException ex) { + throw new UnmarshallException("Error acessing the file?", ex); + } + } /** * Unmarshall the specified element. This version does not generate any - * valiation information. + * validation information. * * @param element - * @throws org.purl.sword.base.UnmarshallException + * element to unmarshall + * @throws UnmarshallException + * If there was a problem unmarshalling the data. This might be + * as a result of an error in parsing the XML string, extracting + * information. */ - public void unmarshall(Element element) + public void unmarshall(Element element) throws UnmarshallException { unmarshall(element, null); @@ -168,24 +179,30 @@ public class ServiceDocument { * information. * * @param element + * element to unmarshall. * @param validationProperties - * @throws org.purl.sword.base.UnmarshallException + * FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * @throws UnmarshallException + * If there was a problem unmarshalling the data. This might be + * as a result of an error in parsing the XML string, extracting + * information. */ public SwordValidationInfo unmarshall(Element element, Properties validationProperties) throws UnmarshallException { - service = new Service(); - try { - return service.unmarshall(element, validationProperties); - } catch (UnmarshallException e) { - throw new UnmarshallException("Unable to parse the XML", e); - } - } + service = new Service(); + try { + return service.unmarshall(element, validationProperties); + } catch (UnmarshallException e) { + throw new UnmarshallException("Unable to parse the XML", e); + } + } public SwordValidationInfo validate() { - if( service == null ) + if ( service == null ) { return null; } @@ -194,7 +211,7 @@ public class ServiceDocument { public SwordValidationInfo validate(Properties validationContext) { - if( service == null) + if ( service == null) { return null; } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/SwordAcceptPackaging.java b/dspace-sword/src/main/java/org/purl/sword/base/SwordAcceptPackaging.java index ffc209925f..98c5122d1e 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/SwordAcceptPackaging.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/SwordAcceptPackaging.java @@ -24,274 +24,277 @@ import org.apache.log4j.Logger; public class SwordAcceptPackaging extends XmlElement implements SwordElementInterface { - /** - * The content in the element. - */ - private String content; - - /** - * The type of the element. - */ - private QualityValue qualityValue; - - /** - * The log. - */ - private static Logger log = Logger.getLogger(SwordAcceptPackaging.class); - - /** */ - public static final String ELEMENT_NAME = "acceptPackaging"; - - protected static final XmlName ATTRIBUTE_Q_NAME = new XmlName(Namespaces.PREFIX_SWORD, - "q", - Namespaces.NS_SWORD); - - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_SWORD, ELEMENT_NAME, Namespaces.NS_SWORD); - - public SwordAcceptPackaging() + /** + * The content in the element. + */ + private String content; + + /** + * The type of the element. + */ + private QualityValue qualityValue; + + /** + * The log. + */ + private static Logger log = Logger.getLogger(SwordAcceptPackaging.class); + + /** */ + public static final String ELEMENT_NAME = "acceptPackaging"; + + protected static final XmlName ATTRIBUTE_Q_NAME = new XmlName(Namespaces.PREFIX_SWORD, + "q", + Namespaces.NS_SWORD); + + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_SWORD, ELEMENT_NAME, Namespaces.NS_SWORD); + + public SwordAcceptPackaging() + { + this(null, new QualityValue()); + } + + public SwordAcceptPackaging(String name, float value) + { + this(name, new QualityValue(value)); + } + + public SwordAcceptPackaging(String name, QualityValue value) + { + super(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace()); + initialise(); + setContent(name); + setQualityValue(value); + } + + public static XmlName elementName() + { + return XML_NAME; + } + + protected final void initialise() + { + qualityValue = null; + content = null; + } + + /** + * Marshal the data in this object to an Element object. + * + * @return The data expressed in an Element. + */ + public Element marshall() { - this(null, new QualityValue()); + Element element = new Element(getQualifiedName(), xmlName.getNamespace()); + if ( qualityValue != null ) + { + Attribute qualityValueAttribute = new Attribute(ATTRIBUTE_Q_NAME.getLocalName(), qualityValue.toString()); + element.addAttribute(qualityValueAttribute); + } + + if ( content != null ) + { + element.appendChild(content); + } + return element; } - - public SwordAcceptPackaging(String name, float value) + + /** + * Unmarshal the text element into this object. + * + * This unmarshaller only handles plain text content, although it can + * recognise the three different type elements of text, html and xhtml. This + * is an area that can be improved in a future implementation, if necessary. + * + * @param acceptPackaging The text element. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + * + * @throws UnmarshallException If the specified element is not of + * the correct type, where the localname is used + * to specify the valid name. Also thrown + * if there is an issue accessing the data. + */ + public SwordValidationInfo unmarshall(Element acceptPackaging, + Properties validationProperties) throws UnmarshallException { - this(name, new QualityValue(value)); + if ( ! isInstanceOf(acceptPackaging, xmlName) ) + { + handleIncorrectElement(acceptPackaging, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + ArrayList attributeItems = new ArrayList(); + + try + { + // get the attributes + int attributeCount = acceptPackaging.getAttributeCount(); + Attribute attribute = null; + float qv = -1; + + for ( int i = 0; i < attributeCount; i++ ) + { + attribute = acceptPackaging.getAttribute(i); + if ( ATTRIBUTE_Q_NAME.getLocalName().equals(attribute.getQualifiedName())) + { + try + { + qv = Float.parseFloat(attribute.getValue()); + qualityValue = new QualityValue(qv); + + SwordValidationInfo attr = new SwordValidationInfo(xmlName, ATTRIBUTE_Q_NAME); + attr.setContentDescription("" + qv); + attributeItems.add(attr); + } + catch (NumberFormatException nfe ) + { + SwordValidationInfo attr = new SwordValidationInfo(xmlName, ATTRIBUTE_Q_NAME, + nfe.getMessage(), SwordValidationInfoType.ERROR); + attr.setContentDescription(attribute.getValue()); + attributeItems.add(attr); + } + + } + else + { + SwordValidationInfo attr = new SwordValidationInfo(xmlName, + new XmlName(attribute), + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO ); + attr.setContentDescription(attribute.getValue()); + + attributeItems.add(attr); + } + } + + int length = acceptPackaging.getChildCount(); + if ( length > 0 ) + { + try + { + content = unmarshallString(acceptPackaging); + } + catch ( UnmarshallException ume ) + { + log.error("Error accessing the content of the acceptPackaging element"); + validationItems.add(new SwordValidationInfo(xmlName, + "Error unmarshalling element: " + ume.getMessage(), + SwordValidationInfoType.ERROR)); + } + } + + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); + throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, attributeItems, validationProperties); + } + return result; } - - public SwordAcceptPackaging(String name, QualityValue value) + + public void unmarshall(Element element) + throws UnmarshallException { - super(XML_NAME.getPrefix(), XML_NAME.getLocalName(), XML_NAME.getNamespace()); - initialise(); - setContent(name); - setQualityValue(value); + unmarshall(element, null); } - - public static XmlName elementName() + + @Override + public SwordValidationInfo validate(Properties validationContext) { - return XML_NAME; + return validate(null, null, validationContext); } - - protected final void initialise() + + /** + * + * @param existing add results to this. + * @param attributeItems FIXME: PLEASE DOCUMENT. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return SWORD validation info + */ + protected SwordValidationInfo validate(List existing, + List attributeItems, + Properties validationContext) { - qualityValue = null; - content = null; + SwordValidationInfo result = new SwordValidationInfo(xmlName); + result.setContentDescription(content); + + // item specific rules + if ( content == null ) + { + result.addValidationInfo( + new SwordValidationInfo(xmlName, + SwordValidationInfo.MISSING_CONTENT, + SwordValidationInfoType.WARNING)); + } + else + { + // check that the content is one of the Sword types + if ( ! SwordContentPackageTypes.instance().isValidType(content) ) + { + result.addValidationInfo(new SwordValidationInfo(xmlName, + "The URI is not one of the types specified in http://purl.org/NET/sword-types", SwordValidationInfoType.WARNING)); + } + } + + result.addUnmarshallValidationInfo(existing, attributeItems); + return result; + } + + + /** + * Get the content in this TextConstruct. + * + * @return The content, expressed as a string. + */ + public final String getContent() { + return content; + } + + /** + * Set the content. This only supports text content. + * + * @param content The content. + */ + public final void setContent(String content) + { + this.content = content; + } + + /** + * Get the type. + * + * @return The type. + */ + public final QualityValue getQualityValue() + { + return qualityValue; + } + + /** + * Set the type. + * + * @param value The type. + */ + public final void setQualityValue(QualityValue value) + { + this.qualityValue = value; + } + + /** + * Get a string representation. + * + * @return The string. + */ + @Override + public String toString() + { + return "Summary - content: " + getContent() + " value: " + getQualityValue(); } - - /** - * Marshal the data in this object to an Element object. - * - * @return The data expressed in an Element. - */ - public Element marshall() - { - Element element = new Element(getQualifiedName(), xmlName.getNamespace()); - if( qualityValue != null ) - { - Attribute qualityValueAttribute = new Attribute(ATTRIBUTE_Q_NAME.getLocalName(), qualityValue.toString()); - element.addAttribute(qualityValueAttribute); - } - - if( content != null ) - { - element.appendChild(content); - } - return element; - } - - /** - * Unmarshal the text element into this object. - * - * This unmarshaller only handles plain text content, although it can - * recognise the three different type elements of text, html and xhtml. This - * is an area that can be improved in a future implementation, if necessary. - * - * @param acceptPackaging The text element. - * @param validationProperties - * - * @throws UnmarshallException If the specified element is not of - * the correct type, where the localname is used - * to specify the valid name. Also thrown - * if there is an issue accessing the data. - */ - public SwordValidationInfo unmarshall(Element acceptPackaging, - Properties validationProperties) throws UnmarshallException - { - if( ! isInstanceOf(acceptPackaging, xmlName) ) - { - handleIncorrectElement(acceptPackaging, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - ArrayList attributeItems = new ArrayList(); - - try - { - // get the attributes - int attributeCount = acceptPackaging.getAttributeCount(); - Attribute attribute = null; - float qv = -1; - - for( int i = 0; i < attributeCount; i++ ) - { - attribute = acceptPackaging.getAttribute(i); - if( ATTRIBUTE_Q_NAME.getLocalName().equals(attribute.getQualifiedName())) - { - try - { - qv = Float.parseFloat(attribute.getValue()); - qualityValue = new QualityValue(qv); - - SwordValidationInfo attr = new SwordValidationInfo(xmlName, ATTRIBUTE_Q_NAME); - attr.setContentDescription("" + qv); - attributeItems.add(attr); - } - catch(NumberFormatException nfe ) - { - SwordValidationInfo attr = new SwordValidationInfo(xmlName, ATTRIBUTE_Q_NAME, - nfe.getMessage(), SwordValidationInfoType.ERROR); - attr.setContentDescription(attribute.getValue()); - attributeItems.add(attr); - } - - } - else - { - SwordValidationInfo attr = new SwordValidationInfo(xmlName, - new XmlName(attribute), - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO ); - attr.setContentDescription(attribute.getValue()); - - attributeItems.add(attr); - } - } - - int length = acceptPackaging.getChildCount(); - if( length > 0 ) - { - try - { - content = unmarshallString(acceptPackaging); - } - catch( UnmarshallException ume ) - { - log.error("Error accessing the content of the acceptPackaging element"); - validationItems.add(new SwordValidationInfo(xmlName, - "Error unmarshalling element: " + ume.getMessage(), - SwordValidationInfoType.ERROR)); - } - } - - } - catch( Exception ex ) - { - log.error("Unable to parse an element in " + getQualifiedName() + ": " + ex.getMessage()); - throw new UnmarshallException("Unable to parse an element in " + getQualifiedName(), ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, attributeItems, validationProperties); - } - return result; - } - - public void unmarshall(Element element) - throws UnmarshallException - { - unmarshall(element, null); - } - - @Override - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, null, validationContext); - } - - /** - * - * @param existing - * @param attributeItems - */ - protected SwordValidationInfo validate(List existing, - List attributeItems, - Properties validationContext) - { - SwordValidationInfo result = new SwordValidationInfo(xmlName); - result.setContentDescription(content); - - // item specific rules - if( content == null ) - { - result.addValidationInfo( - new SwordValidationInfo(xmlName, - SwordValidationInfo.MISSING_CONTENT, - SwordValidationInfoType.WARNING)); - } - else - { - // check that the content is one of the Sword types - if( ! SwordContentPackageTypes.instance().isValidType(content) ) - { - result.addValidationInfo(new SwordValidationInfo(xmlName, - "The URI is not one of the types specified in http://purl.org/NET/sword-types", SwordValidationInfoType.WARNING)); - } - } - - result.addUnmarshallValidationInfo(existing, attributeItems); - return result; - } - - - /** - * Get the content in this TextConstruct. - * - * @return The content, expressed as a string. - */ - public final String getContent() { - return content; - } - - /** - * Set the content. This only supports text content. - * - * @param content The content. - */ - public final void setContent(String content) - { - this.content = content; - } - - /** - * Get the type. - * - * @return The type. - */ - public final QualityValue getQualityValue() - { - return qualityValue; - } - - /** - * Set the type. - * - * @param value The type. - */ - public final void setQualityValue(QualityValue value) - { - this.qualityValue = value; - } - - /** - * Get a string representation. - * - * @return The string. - */ - @Override - public String toString() - { - return "Summary - content: " + getContent() + " value: " + getQualityValue(); - } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/SwordContentPackageTypes.java b/dspace-sword/src/main/java/org/purl/sword/base/SwordContentPackageTypes.java index 9eac3aa1ff..c26cd57e34 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/SwordContentPackageTypes.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/SwordContentPackageTypes.java @@ -31,12 +31,12 @@ public class SwordContentPackageTypes { { types = new Properties(); InputStream stream = SwordContentPackageTypes.class.getClassLoader().getResourceAsStream("swordContentPackageTypes.properties"); - if( stream != null ) + if ( stream != null ) { types.loadFromXML(stream); } } - catch(Exception ex) + catch (Exception ex) { log.error("Unable to load sword types property file: " + ex.getMessage()); } @@ -50,7 +50,7 @@ public class SwordContentPackageTypes { public static SwordContentPackageTypes instance() { - if( instance == null ) + if ( instance == null ) { instance = new SwordContentPackageTypes(); } @@ -67,12 +67,8 @@ public class SwordContentPackageTypes { return types.isEmpty(); } - /** - * - */ public Enumeration elements() { - return types.elements(); } @@ -80,7 +76,4 @@ public class SwordContentPackageTypes { { return types.keys(); } - - - } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/SwordValidationInfo.java b/dspace-sword/src/main/java/org/purl/sword/base/SwordValidationInfo.java index 63078b6958..1570b34951 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/SwordValidationInfo.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/SwordValidationInfo.java @@ -81,7 +81,7 @@ public class SwordValidationInfo { */ public SwordValidationInfo(XmlName element) { - this(element, null, "", SwordValidationInfoType.VALID); + this(element, null, "", SwordValidationInfoType.VALID); } /** @@ -108,7 +108,7 @@ public class SwordValidationInfo { String theMessage, SwordValidationInfoType theType) { - this(element, null, theMessage, theType); + this(element, null, theMessage, theType); } /** @@ -124,15 +124,15 @@ public class SwordValidationInfo { String theMessage, SwordValidationInfoType theType) { - this.elementName = element; - this.attributeName = attribute; - - message = theMessage; - type = theType; - elementInfo = new ArrayList(); - attributeInfo = new ArrayList(); - unmarshallElementInfo = new ArrayList(); - unmarshallAttributeInfo = new ArrayList(); + this.elementName = element; + this.attributeName = attribute; + + message = theMessage; + type = theType; + elementInfo = new ArrayList(); + attributeInfo = new ArrayList(); + unmarshallElementInfo = new ArrayList(); + unmarshallAttributeInfo = new ArrayList(); } /** @@ -215,17 +215,17 @@ public class SwordValidationInfo { public void addValidationInfo(SwordValidationInfo item) { - if( type.compareTo(item.getType()) < 0 ) - { - type = item.getType(); - } - - elementInfo.add(item); + if ( type.compareTo(item.getType()) < 0 ) + { + type = item.getType(); + } + + elementInfo.add(item); } public void addAttributeValidationInfo(SwordValidationInfo attribute) { - if( type.compareTo(attribute.getType()) < 0 ) + if ( type.compareTo(attribute.getType()) < 0 ) { type = attribute.getType(); } @@ -234,26 +234,26 @@ public class SwordValidationInfo { public void addUnmarshallElementInfo(SwordValidationInfo unmarshallElement) { - if( unmarshallElement == null ) - { - // not part of the validation process - end here - return; - } - - if( type.compareTo(unmarshallElement.getType()) < 0 ) - { - type = unmarshallElement.getType(); - } - unmarshallElementInfo.add(unmarshallElement); + if ( unmarshallElement == null ) + { + // not part of the validation process - end here + return; + } + + if ( type.compareTo(unmarshallElement.getType()) < 0 ) + { + type = unmarshallElement.getType(); + } + unmarshallElementInfo.add(unmarshallElement); } public void addUnmarshallAttributeInfo(SwordValidationInfo unmarshallAttribute) { - if( type.compareTo(unmarshallAttribute.getType()) < 0 ) - { - type = unmarshallAttribute.getType(); - } - unmarshallAttributeInfo.add(unmarshallAttribute); + if ( type.compareTo(unmarshallAttribute.getType()) < 0 ) + { + type = unmarshallAttribute.getType(); + } + unmarshallAttributeInfo.add(unmarshallAttribute); } /** @@ -289,10 +289,10 @@ public class SwordValidationInfo { protected void resetType(Iterator iterator) { SwordValidationInfo item = null; - while( iterator.hasNext() ) + while ( iterator.hasNext() ) { item = iterator.next(); - if( item != null && type.compareTo(item.getType()) < 0 ) + if ( item != null && type.compareTo(item.getType()) < 0 ) { type = item.getType(); } @@ -312,6 +312,7 @@ public class SwordValidationInfo { /** * + * @return the iterator. */ public Iterator getValidationAttributeInfoIterator() { @@ -320,6 +321,7 @@ public class SwordValidationInfo { /** * + * @return the iterator. */ public Iterator getUnmarshallElementInfoIterator() { @@ -328,6 +330,7 @@ public class SwordValidationInfo { /** * + * @return the iterator. */ public Iterator getUnmarshallAttributeInfoIterator() { @@ -350,117 +353,116 @@ public class SwordValidationInfo { /** * - * @param elementItems - * @param attributeItems + * @param elementItems FIXME: PLEASE DOCUMENT. + * @param attributeItems FIXME: PLEASE DOCUMENT. */ public void addUnmarshallValidationInfo( List elementItems, List attributeItems) { - if( elementItems != null ) - { - Iterator items = elementItems.iterator(); + if ( elementItems != null ) + { + Iterator items = elementItems.iterator(); - while( items.hasNext() ) - { - addUnmarshallElementInfo(items.next()); - } - } + while ( items.hasNext() ) + { + addUnmarshallElementInfo(items.next()); + } + } - if( attributeItems != null ) - { - Iterator attributes = attributeItems.iterator(); + if ( attributeItems != null ) + { + Iterator attributes = attributeItems.iterator(); + + while ( attributes.hasNext() ) + { + addUnmarshallAttributeInfo(attributes.next()); + } + } + } - while( attributes.hasNext() ) - { - addUnmarshallAttributeInfo(attributes.next()); - } - } - } + public void addUnmarshallValidationInfo(SwordValidationInfo other) + { + addUnmarshallValidationInfo(other.elementInfo, other.attributeInfo); + } - public void addUnmarshallValidationInfo(SwordValidationInfo other) - { - addUnmarshallValidationInfo(other.elementInfo, other.attributeInfo); - } - - @Override - public String toString() - { - return "" + getType(); - } + @Override + public String toString() + { + return "" + getType(); + } /** * Utility method that will recursively print out the list of items * for the specified validation info object. * * @param info The validation info object to display. + * @param buffer string buffer to append to * @param indent The level of indent, expressed as a number of space characters. */ public void createString(SwordValidationInfo info, StringBuffer buffer, String indent) { - String prefix = info.getElement().getPrefix(); - buffer.append(indent); + String prefix = info.getElement().getPrefix(); + buffer.append(indent); - buffer.append("["); - buffer.append(info.getType()); - buffer.append("]"); + buffer.append("["); + buffer.append(info.getType()); + buffer.append("]"); - if( prefix != null && prefix.trim().length() > 0 ) - { - buffer.append(prefix); - buffer.append(":"); - } + if ( prefix != null && prefix.trim().length() > 0 ) + { + buffer.append(prefix); + buffer.append(":"); + } - buffer.append(info.getElement().getLocalName()); - buffer.append(" "); - if (info.getAttribute() != null) { - buffer.append(info.getAttribute().getLocalName()); - buffer.append("=\""); - if( info.getContentDescription() != null ) - { - buffer.append(info.getContentDescription()); - } - buffer.append("\""); - } - else - { - if( info.getContentDescription() != null ) - { - buffer.append(" Value: '"); - buffer.append(info.getContentDescription()); - buffer.append("'"); - } - } - buffer.append("\n" + indent + "message: " ); - buffer.append(info.getMessage()); - buffer.append("\n"); - - // process the list of attributes first - Iterator iterator = info.getValidationAttributeInfoIterator(); - while( iterator.hasNext()) - { - createString(iterator.next(), buffer, " " + indent); - } + buffer.append(info.getElement().getLocalName()); + buffer.append(" "); + if (info.getAttribute() != null) { + buffer.append(info.getAttribute().getLocalName()); + buffer.append("=\""); + if ( info.getContentDescription() != null ) + { + buffer.append(info.getContentDescription()); + } + buffer.append("\""); + } + else + { + if ( info.getContentDescription() != null ) + { + buffer.append(" Value: '"); + buffer.append(info.getContentDescription()); + buffer.append("'"); + } + } + buffer.append("\n" + indent + "message: " ); + buffer.append(info.getMessage()); + buffer.append("\n"); + + // process the list of attributes first + Iterator iterator = info.getValidationAttributeInfoIterator(); + while ( iterator.hasNext()) + { + createString(iterator.next(), buffer, " " + indent); + } - iterator = info.getUnmarshallAttributeInfoIterator(); - while( iterator.hasNext()) - { - createString(iterator.next(), buffer, " " + indent); - } + iterator = info.getUnmarshallAttributeInfoIterator(); + while ( iterator.hasNext()) + { + createString(iterator.next(), buffer, " " + indent); + } - // next, process the element messages - iterator = info.getValidationElementInfoIterator(); - while( iterator.hasNext()) - { - createString(iterator.next(), buffer, " " + indent); - } + // next, process the element messages + iterator = info.getValidationElementInfoIterator(); + while ( iterator.hasNext()) + { + createString(iterator.next(), buffer, " " + indent); + } - iterator = info.getUnmarshallElementInfoIterator(); - while( iterator.hasNext()) - { - createString(iterator.next(), buffer, " " + indent); - } + iterator = info.getUnmarshallElementInfoIterator(); + while ( iterator.hasNext()) + { + createString(iterator.next(), buffer, " " + indent); + } } - - } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/UnmarshallException.java b/dspace-sword/src/main/java/org/purl/sword/base/UnmarshallException.java index c3b0df4806..7409491f06 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/UnmarshallException.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/UnmarshallException.java @@ -15,26 +15,26 @@ package org.purl.sword.base; */ public class UnmarshallException extends Exception { - /** - * Create a new instance and store the specified message and source data. - * - * @param message The message for the exception. - * @param source The original exception that lead to this exception. This - * can be null. - */ - public UnmarshallException(String message, Exception source) - { - super(message, source); - } - - /** - * Create a new instance and store the specified message. - * - * @param message The message for the exception. - */ - public UnmarshallException(String message) - { - super(message); - } + /** + * Create a new instance and store the specified message and source data. + * + * @param message The message for the exception. + * @param source The original exception that lead to this exception. This + * can be null. + */ + public UnmarshallException(String message, Exception source) + { + super(message, source); + } + + /** + * Create a new instance and store the specified message. + * + * @param message The message for the exception. + */ + public UnmarshallException(String message) + { + super(message); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/Workspace.java b/dspace-sword/src/main/java/org/purl/sword/base/Workspace.java index f4cd6ebefa..de27b15366 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/Workspace.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/Workspace.java @@ -26,287 +26,289 @@ import org.purl.sword.atom.Title; */ public class Workspace extends XmlElement implements SwordElementInterface { - /** - * The title for the workspace. - */ - private Title title; - - /** - * A list of collections associated with this workspace. - */ - private List collections; - - /** - * The logger. - */ - private static Logger log = Logger.getLogger(Workspace.class); - - /** - * Local name part of this element. - */ - @Deprecated - public static final String ELEMENT_NAME = "workspace"; - - private static final XmlName XML_NAME = - new XmlName(Namespaces.PREFIX_APP, "workspace", Namespaces.NS_APP); - - /** - * Create a new instance of the workspace, with no title. - */ - public Workspace( ) - { - super(XML_NAME); - initialise(); - } - - public static XmlName elementName() + /** + * The title for the workspace. + */ + private Title title; + + /** + * A list of collections associated with this workspace. + */ + private List collections; + + /** + * The logger. + */ + private static Logger log = Logger.getLogger(Workspace.class); + + /** + * Local name part of this element. + */ + @Deprecated + public static final String ELEMENT_NAME = "workspace"; + + private static final XmlName XML_NAME = + new XmlName(Namespaces.PREFIX_APP, "workspace", Namespaces.NS_APP); + + /** + * Create a new instance of the workspace, with no title. + */ + public Workspace( ) + { + super(XML_NAME); + initialise(); + } + + public static XmlName elementName() { return XML_NAME; } - - /** - * Create a new instance of the workspace with the specified title. - * - * @param title The title. - */ - public Workspace( String title ) - { - this(); - - setTitle(title); - } - - /** - * Initialise the object, ready for use. - */ - protected final void initialise() - { - collections = new ArrayList(); - title = null; - } - - /** - * Set the title. The type for the title will be set to - * ContentType.TEXT - * - * @param title The title. - */ - public final void setTitle( String title ) - { - if( this.title == null) - { - this.title = new Title(); - } - this.title.setContent(title); - this.title.setType(ContentType.TEXT); - - } - - /** - * Get the content of the Title element. - * - * @return The title. - */ - public final String getTitle( ) - { - if( title == null ) - { - return null; - } - - return title.getContent(); - } - - /** - * Add a collection to the Workspace. - * - * @param collection The collection. - */ - public void addCollection( Collection collection ) - { - collections.add(collection); - } - - /** - * Get an Iterator over the collections. - * - * @return An iterator. - */ - public Iterator collectionIterator( ) - { - return collections.iterator(); - } - - /** - * Get a list of the collections - * - * @return A list. - */ - public List getCollections( ) - { - return collections; - } - - /** - * Marshal the data in this element to an Element. - * - * @return An element that contains the data in this object. - */ - public Element marshall( ) - { - // convert data into XOM elements and return the 'root', i.e. the one - // that represents the collection. - Element workspace = new Element(xmlName.getQualifiedName(), xmlName.getNamespace()); - - if( title != null ) - { - workspace.appendChild(title.marshall()); - } - - for( Collection item : collections ) - { - workspace.appendChild(item.marshall()); - } - - return workspace; - } - - /** - * Unmarshal the workspace element into the data in this object. - * - * @throws UnmarshallException If the element does not contain a - * workspace element or if there are problems - * accessing the data. - */ - public void unmarshall( Element workspace ) - throws UnmarshallException - { - unmarshall(workspace, null); - } - - /** - * - * @param workspace - * @param validationProperties - * @throws org.purl.sword.base.UnmarshallException - */ - public SwordValidationInfo unmarshall( Element workspace, Properties validationProperties ) - throws UnmarshallException - { - if( ! isInstanceOf(workspace, xmlName)) - { - return handleIncorrectElement(workspace, validationProperties); - } - - ArrayList validationItems = new ArrayList(); - - try - { - initialise(); - - // FIXME - process the attributes - - // retrieve all of the sub-elements - Elements elements = workspace.getChildElements(); - Element element = null; - int length = elements.size(); - - for(int i = 0; i < length; i++ ) - { - element = elements.get(i); - if( isInstanceOf(element, Title.elementName() ) ) + + /** + * Create a new instance of the workspace with the specified title. + * + * @param title The title. + */ + public Workspace( String title ) + { + this(); + + setTitle(title); + } + + /** + * Initialise the object, ready for use. + */ + protected final void initialise() + { + collections = new ArrayList(); + title = null; + } + + /** + * Set the title. The type for the title will be set to + * ContentType.TEXT + * + * @param title The title. + */ + public final void setTitle( String title ) + { + if ( this.title == null) + { + this.title = new Title(); + } + this.title.setContent(title); + this.title.setType(ContentType.TEXT); + } + + /** + * Get the content of the Title element. + * + * @return The title. + */ + public final String getTitle( ) + { + if ( title == null ) + { + return null; + } + + return title.getContent(); + } + + /** + * Add a collection to the Workspace. + * + * @param collection The collection. + */ + public void addCollection( Collection collection ) + { + collections.add(collection); + } + + /** + * Get an Iterator over the collections. + * + * @return An iterator. + */ + public Iterator collectionIterator( ) + { + return collections.iterator(); + } + + /** + * Get a list of the collections + * + * @return A list. + */ + public List getCollections( ) + { + return collections; + } + + /** + * Marshal the data in this element to an Element. + * + * @return An element that contains the data in this object. + */ + public Element marshall( ) + { + // convert data into XOM elements and return the 'root', i.e. the one + // that represents the collection. + Element workspace = new Element(xmlName.getQualifiedName(), xmlName.getNamespace()); + + if ( title != null ) + { + workspace.appendChild(title.marshall()); + } + + for ( Collection item : collections ) + { + workspace.appendChild(item.marshall()); + } + + return workspace; + } + + /** + * Unmarshal the workspace element into the data in this object. + * + * @throws UnmarshallException If the element does not contain a + * workspace element or if there are problems + * accessing the data. + */ + public void unmarshall( Element workspace ) + throws UnmarshallException + { + unmarshall(workspace, null); + } + + /** + * + * @param workspace the element to unmarshall. + * @param validationProperties FIXME: PLEASE DOCUMENT. + * @return FIXME: PLEASE DOCUMENT. + * @throws UnmarshallException If the element does not contain a + * workspace element or if there are problems + * accessing the data. + */ + public SwordValidationInfo unmarshall( Element workspace, Properties validationProperties ) + throws UnmarshallException + { + if ( ! isInstanceOf(workspace, xmlName)) + { + return handleIncorrectElement(workspace, validationProperties); + } + + ArrayList validationItems = new ArrayList(); + + try + { + initialise(); + + // FIXME - process the attributes + + // retrieve all of the sub-elements + Elements elements = workspace.getChildElements(); + Element element = null; + int length = elements.size(); + + for (int i = 0; i < length; i++ ) { - if( title == null ) - { - title = new Title(); - validationItems.add(title.unmarshall(element, validationProperties)); - } - else - { - SwordValidationInfo info = - new SwordValidationInfo(Title.elementName(), - SwordValidationInfo.DUPLICATE_ELEMENT, - SwordValidationInfoType.WARNING); - info.setContentDescription(element.getValue()); - validationItems.add(info); - } - } - else if( isInstanceOf(element, Collection.elementName() )) - { - Collection collection = new Collection( ); - validationItems.add(collection.unmarshall(element, validationProperties)); - collections.add(collection); - } - else if( validationProperties != null ) - { - validationItems.add(new SwordValidationInfo(new XmlName(element), + element = elements.get(i); + if ( isInstanceOf(element, Title.elementName() ) ) + { + if ( title == null ) + { + title = new Title(); + validationItems.add(title.unmarshall(element, validationProperties)); + } + else + { + SwordValidationInfo info = + new SwordValidationInfo(Title.elementName(), + SwordValidationInfo.DUPLICATE_ELEMENT, + SwordValidationInfoType.WARNING); + info.setContentDescription(element.getValue()); + validationItems.add(info); + } + } + else if ( isInstanceOf(element, Collection.elementName() )) + { + Collection collection = new Collection( ); + validationItems.add(collection.unmarshall(element, validationProperties)); + collections.add(collection); + } + else if ( validationProperties != null ) + { + validationItems.add(new SwordValidationInfo(new XmlName(element), SwordValidationInfo.UNKNOWN_ELEMENT, SwordValidationInfoType.INFO)); + } } - } - } - catch( Exception ex ) - { - log.error("Unable to parse an element in workspace: " + ex.getMessage()); - throw new UnmarshallException("Unable to parse element in workspace.", ex); - } - - SwordValidationInfo result = null; - if( validationProperties != null ) - { - result = validate(validationItems, validationProperties); - } - return result; - } - - /** - * - * @return A validation object that specifies the status of this object. - */ - @Override - public SwordValidationInfo validate(Properties validationContext) - { - return validate(null, validationContext); - } - - /** - * - * @param existing - */ - protected SwordValidationInfo validate(List existing, - Properties validationContext) - { - boolean validateAll = (existing == null ); - - SwordValidationInfo result = new SwordValidationInfo(xmlName); - - if( collections == null || collections.size() == 0 ) - { - result.addValidationInfo(new SwordValidationInfo(Collection.elementName(), - SwordValidationInfo.MISSING_ELEMENT_WARNING, - SwordValidationInfoType.WARNING )); - } - - if( validateAll ) - { - if( title != null ) - { - result.addValidationInfo(title.validate(validationContext)); - } - - if( collections.size() > 0 ) - { - Iterator iterator = collections.iterator(); - while( iterator.hasNext() ) - { - result.addValidationInfo(iterator.next().validate(validationContext)); - } - } - } - - result.addUnmarshallValidationInfo(existing, null); - return result; - } - - + } + catch ( Exception ex ) + { + log.error("Unable to parse an element in workspace: " + ex.getMessage()); + throw new UnmarshallException("Unable to parse element in workspace.", ex); + } + + SwordValidationInfo result = null; + if ( validationProperties != null ) + { + result = validate(validationItems, validationProperties); + } + return result; + } + + /** + * + * @return A validation object that specifies the status of this object. + */ + @Override + public SwordValidationInfo validate(Properties validationContext) + { + return validate(null, validationContext); + } + + /** + * + * @param existing add results to this. + * @param validationContext FIXME: PLEASE DOCUMENT. + * @return FIXME: PLEASE DOCUMENT. + */ + protected SwordValidationInfo validate(List existing, + Properties validationContext) + { + boolean validateAll = (existing == null ); + + SwordValidationInfo result = new SwordValidationInfo(xmlName); + + if ( collections == null || collections.size() == 0 ) + { + result.addValidationInfo(new SwordValidationInfo(Collection.elementName(), + SwordValidationInfo.MISSING_ELEMENT_WARNING, + SwordValidationInfoType.WARNING )); + } + + if ( validateAll ) + { + if ( title != null ) + { + result.addValidationInfo(title.validate(validationContext)); + } + + if ( collections.size() > 0 ) + { + Iterator iterator = collections.iterator(); + while ( iterator.hasNext() ) + { + result.addValidationInfo(iterator.next().validate(validationContext)); + } + } + } + + result.addUnmarshallValidationInfo(existing, null); + return result; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/XmlElement.java b/dspace-sword/src/main/java/org/purl/sword/base/XmlElement.java index 1bedeeea84..b2824634fb 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/XmlElement.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/XmlElement.java @@ -25,352 +25,359 @@ public abstract class XmlElement { /** Logger */ - private static Logger log = Logger.getLogger(XmlElement.class); - - - /** - * - */ - protected XmlName xmlName; - - - public XmlName getXmlName() - { - // FIXME - should this be a clone? - return xmlName; - } - - /** - * The name to use for the prefix. E.g. atom:title, atom is the prefix. - */ - //protected String prefix; - - /** - * The local name of the element. E.g. atom:title, title is the local name. - */ - //protected String localName; - - /** - * Create a new instance. Set the local name that will be used. - * - * @param localName The local name for the element. - */ - public XmlElement(String localName) - { - this("", localName); - } - - /** - * Create a new instance. Set the prefix and local name. - * - * @param prefix The prefix for the element. - * @param localName The local name for the element. - */ - public XmlElement(String prefix, String localName) - { - this.xmlName = new XmlName(prefix, localName, ""); - } - - /** - * Create a new insatnce. Set the prefix, local name and the namespace URI. - * - * @param prefix The prefix. - * @param localName The element's local name. - * @param namespaceUri The namespace URI. - */ - public XmlElement(String prefix, String localName, String namespaceUri) - { - this.xmlName = new XmlName(prefix, localName, namespaceUri); - } - - /** - * - * @param name - */ - public XmlElement(XmlName name) - { - xmlName = name; - } - - /** - * The Date format that is used to parse dates to and from the ISO format - * in the XML data. - */ - protected static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - - /** - * Array of possible date formats that are permitted for date elements. - */ - protected static final String[] DATE_FORMATS = - { - "yyyy-MM-dd'T'HH:mm:ss'Z'", - "yyyy-MM-dd'T'HH:mm:ss.SZ", - "yyyy-MM-dd'T'HH:mm:ss.Sz", - "yyyy-MM-dd'T'HH:mm:ssZ", - "yyyy-MM-dd'T'HH:mm:ssz", - "yyyy-MM-dd'T'HH:mmZZZZ", - "yyyy-MM-dd'T'HH:mmzzzz", - "yyyy-MM-dd'T'HHZZZZ", - "yyyy-MM-dd'T'HHzzzz", - "yyyy-MM-dd'T'HH:mm:ss.S", - "yyyy-MM-dd'T'HH:mm:ss", - "yyyy-MM-dd'T'HH:mm", - "yyyy-MM-dd'T'HH", - "yyyy-MM-dd", - "yyyy-MM", - "yyyy" - }; - - /** - * Extract a boolean value from the specified element. The boolean value - * is represented as the string 'true' or 'false' as the only child - * of the specified element. - * - * @param element The element that contains the boolean value. - * @return True or false, based on the string in the element's content. - * @throws UnmarshallException If the element does not contain a single child, or if - * the child does not contain the value 'true' or 'false'. - */ - protected boolean unmarshallBoolean( Element element ) - throws UnmarshallException - { - if( element.getChildCount() != 1 ) - { - throw new UnmarshallException("Missing Boolean Value", null); - } - - // ok to get the single child element. This should be a text element. - try - { - Node child = element.getChild(0); - String value = child.getValue(); - if( "true".equals(value) ) - { - return true; - } - else if( "false".equals(value)) - { - return false; - } - else - { - throw new UnmarshallException("Illegal Value"); - } - } - catch( IndexOutOfBoundsException ex ) - { - throw new UnmarshallException("Error accessing Boolean element", ex); - } - } - - /** - * Extract a string value from the specified element. The value - * is the only child of the specified element. - * - * @param element The element that contains the string value. - * @return The string. - * @throws UnmarshallException If the element does not contain a single child. - */ - protected String unmarshallString( Element element ) - throws UnmarshallException - { - if( element.getChildCount() != 1 ) - { - throw new UnmarshallException("Missing String Value", null); - } - - // ok to get the single child element. This should be a text element. - try - { - Node child = element.getChild(0); - return child.getValue(); - } - catch( IndexOutOfBoundsException ex ) - { - throw new UnmarshallException("Error accessing String element", ex); - } - - } - - /** - * Extract an integer value from the specified element. The integer value - * is represented as a string in the only child - * of the specified element. - * - * @param element The element that contains the integer. - * @return The integer. - * @throws UnmarshallException If the element does not contain a single child, or if - * the child does not contain the valid integer. - */ - protected int unmarshallInteger( Element element ) - throws UnmarshallException - { - if( element.getChildCount() != 1 ) - { - throw new UnmarshallException("Missing Integer Value", null); - } - - // ok to get the single child element. This should be a text element. - try - { - Node child = element.getChild(0); - return Integer.parseInt( child.getValue() ); - } - catch( IndexOutOfBoundsException ex ) - { - throw new UnmarshallException("Error accessing Integer", ex); - } - catch( NumberFormatException nfex ) - { - throw new UnmarshallException("Error formatting the number", nfex); - } - } - - /** - * Determines if the specified element is an instance of the element name. If - * you are checking the name title in the ATOM namespace, then the local name - * should be 'title' and the namespaceURI is the URI for the ATOM namespace. - * - * @param element The specified element. - * @param localName The local name for the element. - * @param namespaceURI The namespace for the element. - * @return True if the element matches the localname and namespace. Otherwise, false. - */ - protected boolean isInstanceOf(Element element, String localName, String namespaceURI ) - { - return (localName.equals(element.getLocalName()) && - namespaceURI.equals(element.getNamespaceURI()) ); - } - - /** - * - * @param element - * @param xmlName - */ - protected boolean isInstanceOf(Element element, XmlName xmlName) - { - return (xmlName.getLocalName().equals(element.getLocalName()) && - xmlName.getNamespace().equals(element.getNamespaceURI())); - } - - /** - * Retrieve the qualified name for this object. This uses the - * prefix and local name stored in this object. - * - * @return A string of the format 'prefix:localName' - */ - public String getQualifiedName() - { - return getQualifiedName(xmlName.getLocalName()); - } - - /** - * Retrieve the qualified name. The prefix for this object is prepended - * onto the specified local name. - * - * @param name the specified local name. - * @return A string of the format 'prefix:name' - */ - public String getQualifiedName(String name) - { - return xmlName.getQualifiedName(); + private static Logger log = Logger.getLogger(XmlElement.class); - } - - /** - * Get the qualified name for the given prefix and name - * - * @param prefix the prefix - * @param name the name - * @return the qualified name - */ - public String getQualifiedNameWithPrefix(String prefix, String name) - { - return prefix + ":" + name; - } - - - public abstract SwordValidationInfo validate(Properties validationContext); - - protected void processUnexpectedAttributes(Element element, List attributeItems) - { - int attributeCount = element.getAttributeCount(); - Attribute attribute = null; - - for( int i = 0; i < attributeCount; i++ ) - { - attribute = element.getAttribute(i); - XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), - attribute.getLocalName(), - attribute.getNamespaceURI()); - - SwordValidationInfo info = new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO); - info.setContentDescription(attribute.getValue()); - attributeItems.add(info); - } - } - - /** - * Add the information to the unmarshall attribute section of the specified - * info object. - * - * @param element - * @param info - */ - protected void processUnexpectedAttributes(Element element, SwordValidationInfo info) - { - int attributeCount = element.getAttributeCount(); - Attribute attribute = null; - - for( int i = 0; i < attributeCount; i++ ) - { - attribute = element.getAttribute(i); - XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), - attribute.getLocalName(), - attribute.getNamespaceURI()); - - SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, - SwordValidationInfo.UNKNOWN_ATTRIBUTE, - SwordValidationInfoType.INFO); - item.setContentDescription(attribute.getValue()); - info.addUnmarshallAttributeInfo(item); - } - } - - protected SwordValidationInfo handleIncorrectElement(Element element, Properties validationProperties) - throws UnmarshallException - { - log.error("Unexpected element. Expected: " + getQualifiedName() + ". Got: " + - ((element != null) ? element.getQualifiedName() : "null" )); - - if( validationProperties != null ) - { - SwordValidationInfo info = new SwordValidationInfo( - new XmlName(element.getNamespacePrefix(), element.getLocalName(), element.getNamespaceURI()), - "This is not the expected element. Received: " + element.getQualifiedName() + " for namespaceUri: " + element.getNamespaceURI(), - SwordValidationInfoType.ERROR - ); - return info; - } - else - { - throw new UnmarshallException( "Not a " + getQualifiedName() + " element" ); - } - } - - protected SwordValidationInfo createValidAttributeInfo(String name, String content) - { - XmlName attributeName = new XmlName(xmlName.getPrefix(), - name, - xmlName.getNamespace()); - - SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName); - item.setContentDescription(content); - //attributeItems.add(item); - return item; - } - - + + /** + * + */ + protected XmlName xmlName; + + + public XmlName getXmlName() + { + // FIXME - should this be a clone? + return xmlName; + } + + /** + * The name to use for the prefix. E.g. atom:title, atom is the prefix. + */ + //protected String prefix; + + /** + * The local name of the element. E.g. atom:title, title is the local name. + */ + //protected String localName; + + /** + * Create a new instance. Set the local name that will be used. + * + * @param localName The local name for the element. + */ + public XmlElement(String localName) + { + this("", localName); + } + + /** + * Create a new instance. Set the prefix and local name. + * + * @param prefix The prefix for the element. + * @param localName The local name for the element. + */ + public XmlElement(String prefix, String localName) + { + this.xmlName = new XmlName(prefix, localName, ""); + } + + /** + * Create a new insatnce. Set the prefix, local name and the namespace URI. + * + * @param prefix The prefix. + * @param localName The element's local name. + * @param namespaceUri The namespace URI. + */ + public XmlElement(String prefix, String localName, String namespaceUri) + { + this.xmlName = new XmlName(prefix, localName, namespaceUri); + } + + /** + * Set the name of this XML element. + * + * @param name + * name to set + */ + public XmlElement(XmlName name) + { + xmlName = name; + } + + /** + * The Date format that is used to parse dates to and from the ISO format + * in the XML data. + */ + protected static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + + /** + * Array of possible date formats that are permitted for date elements. + */ + protected static final String[] DATE_FORMATS = + { + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SZ", + "yyyy-MM-dd'T'HH:mm:ss.Sz", + "yyyy-MM-dd'T'HH:mm:ssZ", + "yyyy-MM-dd'T'HH:mm:ssz", + "yyyy-MM-dd'T'HH:mmZZZZ", + "yyyy-MM-dd'T'HH:mmzzzz", + "yyyy-MM-dd'T'HHZZZZ", + "yyyy-MM-dd'T'HHzzzz", + "yyyy-MM-dd'T'HH:mm:ss.S", + "yyyy-MM-dd'T'HH:mm:ss", + "yyyy-MM-dd'T'HH:mm", + "yyyy-MM-dd'T'HH", + "yyyy-MM-dd", + "yyyy-MM", + "yyyy" + }; + + /** + * Extract a boolean value from the specified element. The boolean value + * is represented as the string 'true' or 'false' as the only child + * of the specified element. + * + * @param element The element that contains the boolean value. + * @return True or false, based on the string in the element's content. + * @throws UnmarshallException If the element does not contain a single child, or if + * the child does not contain the value 'true' or 'false'. + */ + protected boolean unmarshallBoolean( Element element ) + throws UnmarshallException + { + if ( element.getChildCount() != 1 ) + { + throw new UnmarshallException("Missing Boolean Value", null); + } + + // ok to get the single child element. This should be a text element. + try + { + Node child = element.getChild(0); + String value = child.getValue(); + if ( "true".equals(value) ) + { + return true; + } + else if ( "false".equals(value)) + { + return false; + } + else + { + throw new UnmarshallException("Illegal Value"); + } + } + catch ( IndexOutOfBoundsException ex ) + { + throw new UnmarshallException("Error accessing Boolean element", ex); + } + } + + /** + * Extract a string value from the specified element. The value + * is the only child of the specified element. + * + * @param element The element that contains the string value. + * @return The string. + * @throws UnmarshallException If the element does not contain a single child. + */ + protected String unmarshallString( Element element ) + throws UnmarshallException + { + if ( element.getChildCount() != 1 ) + { + throw new UnmarshallException("Missing String Value", null); + } + + // ok to get the single child element. This should be a text element. + try + { + Node child = element.getChild(0); + return child.getValue(); + } + catch ( IndexOutOfBoundsException ex ) + { + throw new UnmarshallException("Error accessing String element", ex); + } + } + + /** + * Extract an integer value from the specified element. The integer value + * is represented as a string in the only child + * of the specified element. + * + * @param element The element that contains the integer. + * @return The integer. + * @throws UnmarshallException If the element does not contain a single child, or if + * the child does not contain the valid integer. + */ + protected int unmarshallInteger( Element element ) + throws UnmarshallException + { + if ( element.getChildCount() != 1 ) + { + throw new UnmarshallException("Missing Integer Value", null); + } + + // ok to get the single child element. This should be a text element. + try + { + Node child = element.getChild(0); + return Integer.parseInt( child.getValue() ); + } + catch ( IndexOutOfBoundsException ex ) + { + throw new UnmarshallException("Error accessing Integer", ex); + } + catch ( NumberFormatException nfex ) + { + throw new UnmarshallException("Error formatting the number", nfex); + } + } + + /** + * Determines if the specified element is an instance of the element name. If + * you are checking the name title in the ATOM namespace, then the local name + * should be 'title' and the namespaceURI is the URI for the ATOM namespace. + * + * @param element The specified element. + * @param localName The local name for the element. + * @param namespaceURI The namespace for the element. + * @return True if the element matches the localname and namespace URI. Otherwise, false. + */ + protected boolean isInstanceOf(Element element, String localName, String namespaceURI ) + { + return (localName.equals(element.getLocalName()) && + namespaceURI.equals(element.getNamespaceURI()) ); + } + + /** + * Checks XML element local name and namespace URI. + * + * @param element + * XML element to check + * @param xmlName + * XML element name + * @return True if the element matches the localname and namespace URI. Otherwise, false. + */ + protected boolean isInstanceOf(Element element, XmlName xmlName) + { + return (xmlName.getLocalName().equals(element.getLocalName()) && + xmlName.getNamespace().equals(element.getNamespaceURI())); + } + + /** + * Retrieve the qualified name for this object. This uses the + * prefix and local name stored in this object. + * + * @return A string of the format 'prefix:localName' + */ + public String getQualifiedName() + { + return getQualifiedName(xmlName.getLocalName()); + } + + /** + * Retrieve the qualified name. The prefix for this object is prepended + * onto the specified local name. + * + * @param name the specified local name. + * @return A string of the format 'prefix:name' + */ + public String getQualifiedName(String name) + { + return xmlName.getQualifiedName(); + } + + /** + * Get the qualified name for the given prefix and name + * + * @param prefix the prefix + * @param name the name + * @return the qualified name + */ + public String getQualifiedNameWithPrefix(String prefix, String name) + { + return prefix + ":" + name; + } + + + public abstract SwordValidationInfo validate(Properties validationContext); + + protected void processUnexpectedAttributes(Element element, List attributeItems) + { + int attributeCount = element.getAttributeCount(); + Attribute attribute = null; + + for ( int i = 0; i < attributeCount; i++ ) + { + attribute = element.getAttribute(i); + XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), + attribute.getLocalName(), + attribute.getNamespaceURI()); + + SwordValidationInfo info = new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO); + info.setContentDescription(attribute.getValue()); + attributeItems.add(info); + } + } + + /** + * Add the information to the unmarshall attribute section of the specified + * info object. + * + * @param element + * XML element to process + * @param info + * validation information item about elements/attributes + */ + protected void processUnexpectedAttributes(Element element, SwordValidationInfo info) + { + int attributeCount = element.getAttributeCount(); + Attribute attribute = null; + + for ( int i = 0; i < attributeCount; i++ ) + { + attribute = element.getAttribute(i); + XmlName attributeName = new XmlName(attribute.getNamespacePrefix(), + attribute.getLocalName(), + attribute.getNamespaceURI()); + + SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName, + SwordValidationInfo.UNKNOWN_ATTRIBUTE, + SwordValidationInfoType.INFO); + item.setContentDescription(attribute.getValue()); + info.addUnmarshallAttributeInfo(item); + } + } + + protected SwordValidationInfo handleIncorrectElement(Element element, Properties validationProperties) + throws UnmarshallException + { + log.error( + "Unexpected element. Expected: " + getQualifiedName() +". Got: " + + ((element != null) ? element.getQualifiedName() : "null" )); + + if ( validationProperties != null ) + { + SwordValidationInfo info = new SwordValidationInfo( + new XmlName(element.getNamespacePrefix(), element.getLocalName(), + element.getNamespaceURI()), + "This is not the expected element. Received: " + + element.getQualifiedName() + " for namespaceUri: " + + element.getNamespaceURI(), SwordValidationInfoType.ERROR + ); + return info; + } + else + { + throw new UnmarshallException( "Not a " + getQualifiedName() + " element" ); + } + } + + protected SwordValidationInfo createValidAttributeInfo(String name, String content) + { + XmlName attributeName = new XmlName(xmlName.getPrefix(), + name, + xmlName.getNamespace()); + + SwordValidationInfo item = new SwordValidationInfo(xmlName, attributeName); + item.setContentDescription(content); + //attributeItems.add(item); + return item; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/base/XmlName.java b/dspace-sword/src/main/java/org/purl/sword/base/XmlName.java index e2869f597b..9bd3be20c6 100644 --- a/dspace-sword/src/main/java/org/purl/sword/base/XmlName.java +++ b/dspace-sword/src/main/java/org/purl/sword/base/XmlName.java @@ -30,10 +30,12 @@ public class XmlName { /** * Create a new instance with the specified prefix and local name. + * * @param prefix The namespace prefix. * @param localName The element's local name. + * @param namespace The element's namespace. */ - public XmlName(String prefix, String localName, String namespace ) + public XmlName(String prefix, String localName, String namespace) { this.prefix = prefix; this.localName = localName; @@ -111,7 +113,7 @@ public class XmlName { public String getQualifiedName() { String qName = ""; - if( prefix != null && prefix.trim().length() > 0 ) + if ( prefix != null && prefix.trim().length() > 0 ) { qName = prefix + ":"; } @@ -123,7 +125,7 @@ public class XmlName { public boolean equals(Object other) { - if( other instanceof XmlName ) + if ( other instanceof XmlName ) { XmlName otherName = (XmlName) other; return StringUtils.equals(this.namespace, otherName.namespace) && diff --git a/dspace-sword/src/main/java/org/purl/sword/client/Client.java b/dspace-sword/src/main/java/org/purl/sword/client/Client.java index dc78ed3ba7..d49682b687 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/Client.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/Client.java @@ -42,435 +42,439 @@ import org.purl.sword.base.UnmarshallException; * @author Neil Taylor */ public class Client implements SWORDClient { - /** - * The status field for the response code from the recent network access. - */ - private Status status; + /** + * The status field for the response code from the recent network access. + */ + private Status status; - /** - * The name of the server to contact. - */ - private String server; + /** + * The name of the server to contact. + */ + private String server; - /** - * The port number for the server. - */ - private int port; + /** + * The port number for the server. + */ + private int port; - /** - * Specifies if the network access should use HTTP authentication. - */ - private boolean doAuthentication; + /** + * Specifies if the network access should use HTTP authentication. + */ + private boolean doAuthentication; - /** - * The username to use for Basic Authentication. - */ - private String username; + /** + * The username to use for Basic Authentication. + */ + private String username; - /** - * User password that is to be used. - */ - private String password; + /** + * User password that is to be used. + */ + private String password; - /** - * The userAgent to identify this application. - */ - private String userAgent; + /** + * The userAgent to identify this application. + */ + private String userAgent; - /** - * The client that is used to send data to the specified server. - */ - private final DefaultHttpClient client; + /** + * The client that is used to send data to the specified server. + */ + private final DefaultHttpClient client; - /** - * The default connection timeout. This can be modified by using the - * setSocketTimeout method. - */ - public static final int DEFAULT_TIMEOUT = 20000; + /** + * The default connection timeout. This can be modified by using the + * setSocketTimeout method. + */ + public static final int DEFAULT_TIMEOUT = 20000; - /** - * Logger. - */ - private static final Logger log = Logger.getLogger(Client.class); + /** + * Logger. + */ + private static final Logger log = Logger.getLogger(Client.class); - /** - * Create a new Client. The client will not use authentication by default. - */ - public Client() { - client = new DefaultHttpClient(); + /** + * Create a new Client. The client will not use authentication by default. + */ + public Client() { + client = new DefaultHttpClient(); HttpParams params = client.getParams(); - params.setParameter("http.socket.timeout", - Integer.valueOf(DEFAULT_TIMEOUT)); + params.setParameter("http.socket.timeout", + Integer.valueOf(DEFAULT_TIMEOUT)); HttpHost proxyHost = (HttpHost) params.getParameter(ConnRoutePNames.DEFAULT_PROXY); // XXX does this really work? - log.debug("proxy host: " + proxyHost.getHostName()); - log.debug("proxy port: " + proxyHost.getPort()); + log.debug("proxy host: " + proxyHost.getHostName()); + log.debug("proxy port: " + proxyHost.getPort()); doAuthentication = false; - } + } - /** - * Initialise the server that will be used to send the network access. - * - * @param server - * @param port - */ - public void setServer(String server, int port) { - this.server = server; - this.port = port; - } + /** + * Initialise the server that will be used to send the network access. + * + * @param server + * server address/hostname + * @param port + * server port + */ + public void setServer(String server, int port) { + this.server = server; + this.port = port; + } - /** - * Set the user credentials that will be used when making the access to the - * server. - * - * @param username - * The username. - * @param password - * The password. - */ - public void setCredentials(String username, String password) { - this.username = username; - this.password = password; - doAuthentication = true; - } + /** + * Set the user credentials that will be used when making the access to the + * server. + * + * @param username + * The username. + * @param password + * The password. + */ + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + doAuthentication = true; + } - /** - * Set the basic credentials. You must have previously set the server and - * port using setServer. - * - * @param username - * @param password - */ - private void setBasicCredentials(String username, String password) { - log.debug("server: " + server + " port: " + port + " u: '" + username - + "' p '" + password + "'"); - client.getCredentialsProvider().setCredentials(new AuthScope(server, port), - new UsernamePasswordCredentials(username, password)); - } + /** + * Set the basic credentials. You must have previously set the server and + * port using setServer. + * + * @param username + * The username. + * @param password + * The password. + */ + private void setBasicCredentials(String username, String password) { + log.debug("server: " + server + " port: " + port + " u: '" + username + + "' p '" + password + "'"); + client.getCredentialsProvider().setCredentials(new AuthScope(server, port), + new UsernamePasswordCredentials(username, password)); + } - /** - * Set a proxy that should be used by the client when trying to access the - * server. If this is not set, the client will attempt to make a direct - * direct connection to the server. The port is set to 80. - * - * @param host - * The hostname. - */ - public void setProxy(String host) { - setProxy(host, 80); - } + /** + * Set a proxy that should be used by the client when trying to access the + * server. If this is not set, the client will attempt to make a direct + * direct connection to the server. The port is set to 80. + * + * @param host + * The hostname. + */ + public void setProxy(String host) { + setProxy(host, 80); + } - /** - * Set a proxy that should be used by the client when trying to access the - * server. If this is not set, the client will attempt to make a direct - * direct connection to the server. - * - * @param host - * The name of the host. - * @param port - * The port. - */ - public void setProxy(String host, int port) { + /** + * Set a proxy that should be used by the client when trying to access the + * server. If this is not set, the client will attempt to make a direct + * direct connection to the server. + * + * @param host + * The name of the host. + * @param port + * The port. + */ + public void setProxy(String host, int port) { client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(host, port)); // XXX does this really work? - } + } - /** - * Clear the proxy setting. - */ - public void clearProxy() { + /** + * Clear the proxy setting. + */ + public void clearProxy() { client.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); // XXX does this really work? - } + } - /** - * Clear any user credentials that have been set for this client. - */ - public void clearCredentials() { - client.getCredentialsProvider().clear(); - doAuthentication = false; - } + /** + * Clear any user credentials that have been set for this client. + */ + public void clearCredentials() { + client.getCredentialsProvider().clear(); + doAuthentication = false; + } public void setUserAgent(String userAgent){ this.userAgent = userAgent; } - /** - * Set the connection timeout for the socket. - * - * @param milliseconds - * The time, expressed as a number of milliseconds. - */ - public void setSocketTimeout(int milliseconds) { - client.getParams().setParameter("http.socket.timeout", - Integer.valueOf(milliseconds)); - } + /** + * Set the connection timeout for the socket. + * + * @param milliseconds + * The time, expressed as a number of milliseconds. + */ + public void setSocketTimeout(int milliseconds) { + client.getParams().setParameter("http.socket.timeout", + Integer.valueOf(milliseconds)); + } - /** - * Retrieve the service document. The service document is located at the - * specified URL. This calls getServiceDocument(url,onBehalfOf). - * - * @param url - * The location of the service document. - * @return The ServiceDocument, or null if there was a - * problem accessing the document. e.g. invalid access. - * - * @throws SWORDClientException - * If there is an error accessing the resource. - */ - public ServiceDocument getServiceDocument(String url) - throws SWORDClientException { - return getServiceDocument(url, null); - } + /** + * Retrieve the service document. The service document is located at the + * specified URL. This calls getServiceDocument(url,onBehalfOf). + * + * @param url + * The location of the service document. + * @return The ServiceDocument, or null if there was a + * problem accessing the document. e.g. invalid access. + * + * @throws SWORDClientException + * If there is an error accessing the resource. + */ + public ServiceDocument getServiceDocument(String url) + throws SWORDClientException { + return getServiceDocument(url, null); + } - /** - * Retrieve the service document. The service document is located at the - * specified URL. This calls getServiceDocument(url,onBehalfOf). - * - * @param url - * The location of the service document. - * @return The ServiceDocument, or null if there was a - * problem accessing the document. e.g. invalid access. - * - * @throws SWORDClientException - * If there is an error accessing the resource. - */ - public ServiceDocument getServiceDocument(String url, String onBehalfOf) - throws SWORDClientException { - URL serviceDocURL = null; - try { - serviceDocURL = new URL(url); - } catch (MalformedURLException e) { - // Try relative URL - URL baseURL = null; - try { - baseURL = new URL("http", server, Integer.valueOf(port), "/"); - serviceDocURL = new URL(baseURL, (url == null) ? "" : url); - } catch (MalformedURLException e1) { - // No dice, can't even form base URL... - throw new SWORDClientException(url + " is not a valid URL (" - + e1.getMessage() - + "), and could not form a relative one from: " - + baseURL + " / " + url, e1); - } - } - - HttpGet httpget = new HttpGet(serviceDocURL.toExternalForm()); - if (doAuthentication) { - // this does not perform any check on the username password. It - // relies on the server to determine if the values are correct. - setBasicCredentials(username, password); - } + /** + * Retrieve the service document. The service document is located at the + * specified URL. This calls getServiceDocument(url,onBehalfOf). + * + * @param url + * The location of the service document. + * @return The ServiceDocument, or null if there was a + * problem accessing the document. e.g. invalid access. + * + * @throws SWORDClientException + * If there is an error accessing the resource. + */ + public ServiceDocument getServiceDocument(String url, String onBehalfOf) + throws SWORDClientException { + URL serviceDocURL = null; + try { + serviceDocURL = new URL(url); + } catch (MalformedURLException e) { + // Try relative URL + URL baseURL = null; + try { + baseURL = new URL("http", server, Integer.valueOf(port), "/"); + serviceDocURL = new URL(baseURL, (url == null) ? "" : url); + } catch (MalformedURLException e1) { + // No dice, can't even form base URL... + throw new SWORDClientException(url + " is not a valid URL (" + + e1.getMessage() + + "), and could not form a relative one from: " + + baseURL + " / " + url, e1); + } + } + + HttpGet httpget = new HttpGet(serviceDocURL.toExternalForm()); + if (doAuthentication) { + // this does not perform any check on the username password. It + // relies on the server to determine if the values are correct. + setBasicCredentials(username, password); + } Properties properties = new Properties(); - if (containsValue(onBehalfOf)) { - log.debug("Setting on-behalf-of: " + onBehalfOf);httpget.addHeader(url, url); - httpget.addHeader(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf); + if (containsValue(onBehalfOf)) { + log.debug("Setting on-behalf-of: " + onBehalfOf);httpget.addHeader(url, url); + httpget.addHeader(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf); properties.put(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf); - } + } - if (containsValue(userAgent)) { - log.debug("Setting userAgent: " + userAgent); - httpget.addHeader(HttpHeaders.USER_AGENT, userAgent); + if (containsValue(userAgent)) { + log.debug("Setting userAgent: " + userAgent); + httpget.addHeader(HttpHeaders.USER_AGENT, userAgent); properties.put(HttpHeaders.USER_AGENT, userAgent); - } + } - ServiceDocument doc = null; + ServiceDocument doc = null; - try { - HttpResponse response = client.execute(httpget); + try { + HttpResponse response = client.execute(httpget); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); - // store the status code - status = new Status(statusCode, statusLine.getReasonPhrase()); + // store the status code + status = new Status(statusCode, statusLine.getReasonPhrase()); - if (status.getCode() == HttpStatus.SC_OK) { - String message = readResponse(response.getEntity().getContent()); - log.debug("returned message is: " + message); - doc = new ServiceDocument(); - lastUnmarshallInfo = doc.unmarshall(message, properties); - } else { - throw new SWORDClientException( - "Received error from service document request: " - + status); - } - } catch (IOException ioex) { - throw new SWORDClientException(ioex.getMessage(), ioex); - } catch (UnmarshallException uex) { - throw new SWORDClientException(uex.getMessage(), uex); - } finally { - httpget.releaseConnection(); - } + if (status.getCode() == HttpStatus.SC_OK) { + String message = readResponse(response.getEntity().getContent()); + log.debug("returned message is: " + message); + doc = new ServiceDocument(); + lastUnmarshallInfo = doc.unmarshall(message, properties); + } else { + throw new SWORDClientException( + "Received error from service document request: " + + status); + } + } catch (IOException ioex) { + throw new SWORDClientException(ioex.getMessage(), ioex); + } catch (UnmarshallException uex) { + throw new SWORDClientException(uex.getMessage(), uex); + } finally { + httpget.releaseConnection(); + } - return doc; - } + return doc; + } private SwordValidationInfo lastUnmarshallInfo; /** - * + * @return SWORD validation info */ public SwordValidationInfo getLastUnmarshallInfo() { return lastUnmarshallInfo; } - /** - * Post a file to the server. The different elements of the post are encoded - * in the specified message. - * - * @param message - * The message that contains the post information. - * - * @throws SWORDClientException - * if there is an error during the post operation. - */ - public DepositResponse postFile(PostMessage message) - throws SWORDClientException { - if (message == null) { - throw new SWORDClientException("Message cannot be null."); - } + /** + * Post a file to the server. The different elements of the post are encoded + * in the specified message. + * + * @param message + * The message that contains the post information. + * + * @throws SWORDClientException + * if there is an error during the post operation. + */ + public DepositResponse postFile(PostMessage message) + throws SWORDClientException { + if (message == null) { + throw new SWORDClientException("Message cannot be null."); + } - HttpPost httppost = new HttpPost(message.getDestination()); + HttpPost httppost = new HttpPost(message.getDestination()); - if (doAuthentication) { - setBasicCredentials(username, password); - } + if (doAuthentication) { + setBasicCredentials(username, password); + } - DepositResponse response = null; + DepositResponse response = null; - String messageBody = ""; - - try { - if (message.isUseMD5()) { - String md5 = ChecksumUtils.generateMD5(message.getFilepath()); - if (message.getChecksumError()) { - md5 = "1234567890"; - } - log.debug("checksum error is: " + md5); - if (md5 != null) { - httppost.addHeader(HttpHeaders.CONTENT_MD5, md5); - } - } + String messageBody = ""; + + try { + if (message.isUseMD5()) { + String md5 = ChecksumUtils.generateMD5(message.getFilepath()); + if (message.getChecksumError()) { + md5 = "1234567890"; + } + log.debug("checksum error is: " + md5); + if (md5 != null) { + httppost.addHeader(HttpHeaders.CONTENT_MD5, md5); + } + } - String filename = message.getFilename(); - if (! "".equals(filename)) { - httppost.addHeader(HttpHeaders.CONTENT_DISPOSITION, + String filename = message.getFilename(); + if (! "".equals(filename)) { + httppost.addHeader(HttpHeaders.CONTENT_DISPOSITION, " filename=" + filename); - } + } - if (containsValue(message.getSlug())) { - httppost.addHeader(HttpHeaders.SLUG, message.getSlug()); - } + if (containsValue(message.getSlug())) { + httppost.addHeader(HttpHeaders.SLUG, message.getSlug()); + } - if(message.getCorruptRequest()) + if (message.getCorruptRequest()) { // insert a header with an invalid boolean value httppost.addHeader(HttpHeaders.X_NO_OP, "Wibble"); - }else{ + } else { httppost.addHeader(HttpHeaders.X_NO_OP, Boolean - .toString(message.isNoOp())); + .toString(message.isNoOp())); } - httppost.addHeader(HttpHeaders.X_VERBOSE, Boolean - .toString(message.isVerbose())); + httppost.addHeader(HttpHeaders.X_VERBOSE, Boolean + .toString(message.isVerbose())); - String packaging = message.getPackaging(); - if (packaging != null && packaging.length() > 0) { - httppost.addHeader(HttpHeaders.X_PACKAGING, packaging); - } + String packaging = message.getPackaging(); + if (packaging != null && packaging.length() > 0) { + httppost.addHeader(HttpHeaders.X_PACKAGING, packaging); + } - String onBehalfOf = message.getOnBehalfOf(); - if (containsValue(onBehalfOf)) { - httppost.addHeader(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf); - } - - String userAgent = message.getUserAgent(); - if (containsValue(userAgent)) { - httppost.addHeader(HttpHeaders.USER_AGENT, userAgent); - } + String onBehalfOf = message.getOnBehalfOf(); + if (containsValue(onBehalfOf)) { + httppost.addHeader(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf); + } + + String userAgent = message.getUserAgent(); + if (containsValue(userAgent)) { + httppost.addHeader(HttpHeaders.USER_AGENT, userAgent); + } - FileEntity requestEntity = new FileEntity( + FileEntity requestEntity = new FileEntity( new File(message.getFilepath()), ContentType.create(message.getFiletype())); - httppost.setEntity(requestEntity); + httppost.setEntity(requestEntity); - HttpResponse httpResponse = client.execute(httppost); + HttpResponse httpResponse = client.execute(httppost); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); - status = new Status(statusCode, statusLine.getReasonPhrase()); + status = new Status(statusCode, statusLine.getReasonPhrase()); - log.info("Checking the status code: " + status.getCode()); + log.info("Checking the status code: " + status.getCode()); - if (status.getCode() == HttpStatus.SC_ACCEPTED - || status.getCode() == HttpStatus.SC_CREATED) { - messageBody = readResponse(httpResponse.getEntity().getContent()); - response = new DepositResponse(status.getCode()); - response.setLocation(httpResponse.getFirstHeader("Location").getValue()); - // added call for the status code. - lastUnmarshallInfo = response.unmarshall(messageBody, new Properties()); - } - else { - messageBody = readResponse(httpResponse.getEntity().getContent()); - response = new DepositResponse(status.getCode()); - response.unmarshallErrorDocument(messageBody); - } - return response; + if (status.getCode() == HttpStatus.SC_ACCEPTED + || status.getCode() == HttpStatus.SC_CREATED) { + messageBody = readResponse(httpResponse.getEntity().getContent()); + response = new DepositResponse(status.getCode()); + response.setLocation(httpResponse.getFirstHeader("Location").getValue()); + // added call for the status code. + lastUnmarshallInfo = response.unmarshall(messageBody, new Properties()); + } + else { + messageBody = readResponse(httpResponse.getEntity().getContent()); + response = new DepositResponse(status.getCode()); + response.unmarshallErrorDocument(messageBody); + } + return response; - } catch (NoSuchAlgorithmException nex) { - throw new SWORDClientException("Unable to use MD5. " - + nex.getMessage(), nex); - } catch (IOException ioex) { - throw new SWORDClientException(ioex.getMessage(), ioex); - } catch (UnmarshallException uex) { - throw new SWORDClientException(uex.getMessage() + "(
    " + messageBody + "
    )", uex); - } finally { - httppost.releaseConnection(); - } - } + } catch (NoSuchAlgorithmException nex) { + throw new SWORDClientException("Unable to use MD5. " + + nex.getMessage(), nex); + } catch (IOException ioex) { + throw new SWORDClientException(ioex.getMessage(), ioex); + } catch (UnmarshallException uex) { + throw new SWORDClientException(uex.getMessage() + "(
    " + messageBody + "
    )", uex); + } finally { + httppost.releaseConnection(); + } + } - /** - * Read a response from the stream and return it as a string. - * - * @param stream - * The stream that contains the response. - * @return The string extracted from the screen. - * - * @throws UnsupportedEncodingException - * @throws IOException - */ - private String readResponse(InputStream stream) - throws UnsupportedEncodingException, IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader( - stream, "UTF-8")); - String line = null; - StringBuffer buffer = new StringBuffer(); - while ((line = reader.readLine()) != null) { - buffer.append(line); - buffer.append("\n"); - } - return buffer.toString(); - } + /** + * Read a response from the stream and return it as a string. + * + * @param stream + * The stream that contains the response. + * @return The string extracted from the screen. + * + * @throws UnsupportedEncodingException + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + */ + private String readResponse(InputStream stream) + throws UnsupportedEncodingException, IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader( + stream, "UTF-8")); + String line = null; + StringBuffer buffer = new StringBuffer(); + while ((line = reader.readLine()) != null) { + buffer.append(line); + buffer.append("\n"); + } + return buffer.toString(); + } - /** - * Return the status information that was returned from the most recent - * request sent to the server. - * - * @return The status code returned from the most recent access. - */ - public Status getStatus() { - return status; - } - - /** - * Check to see if the specified item contains a non-empty string. - * - * @param item - * The string to check. - * @return True if the string is not null and has a length greater than 0 - * after any whitespace is trimmed from the start and end. - * Otherwise, false. - */ - private boolean containsValue(String item) { - return ((item != null) && (item.trim().length() > 0)); - } + /** + * Return the status information that was returned from the most recent + * request sent to the server. + * + * @return The status code returned from the most recent access. + */ + public Status getStatus() { + return status; + } + /** + * Check to see if the specified item contains a non-empty string. + * + * @param item + * The string to check. + * @return True if the string is not null and has a length greater than 0 + * after any whitespace is trimmed from the start and end. + * Otherwise, false. + */ + private boolean containsValue(String item) { + return ((item != null) && (item.trim().length() > 0)); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/ClientFactory.java b/dspace-sword/src/main/java/org/purl/sword/client/ClientFactory.java index e827b65ab0..687ec330fd 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/ClientFactory.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/ClientFactory.java @@ -17,144 +17,116 @@ import org.apache.log4j.PropertyConfigurator; */ public class ClientFactory { - /** - * Create a new instance. - */ - public ClientFactory() { - // configure the logger from the property file. The GUI client will - // reload these properties if it is set to capture the output and - // display it in a panel. + /** + * Create a new instance. + */ + public ClientFactory() { + // configure the logger from the property file. The GUI client will + // reload these properties if it is set to capture the output and + // display it in a panel. PropertyConfigurator.configure(this.getClass().getClassLoader() - .getResource(ClientConstants.LOGGING_PROPERTY_FILE)); - } + .getResource(ClientConstants.LOGGING_PROPERTY_FILE)); + } - /** - * Generate a string that specifies the command line options for this - * program. - * - * @return A list of the options for this program. - */ - public static String usage() { - StringBuffer buffer = new StringBuffer(); - buffer.append("swordclient: version "); - buffer.append(ClientConstants.CLIENT_VERSION); - buffer.append("\n"); + /** + * Generate a string that specifies the command line options for this + * program. + * + * @return A list of the options for this program. + */ + public static String usage() { + StringBuffer buffer = new StringBuffer(); + buffer.append("swordclient: version "); + buffer.append(ClientConstants.CLIENT_VERSION); + buffer.append("\n"); - buffer.append("GUI Mode: "); - buffer.append("swordclient [-gui] [-nocapture]"); - buffer.append("\n\n"); + buffer.append("GUI Mode: "); + buffer.append("swordclient [-gui] [-nocapture]"); + buffer.append("\n\n"); - buffer.append("Command Mode: Service - Request a Service Document\n"); - buffer - .append("swordclient -cmd -t service [user-options] [proxy-options] -href url [-onBehalfOf name] "); - buffer.append("\n\n"); + buffer.append("Command Mode: Service - Request a Service Document\n"); + buffer.append("swordclient -cmd -t service [user-options] [proxy-options] -href url [-onBehalfOf name] "); + buffer.append("\n\n"); - buffer - .append("Command Mode: Post - Post a file to a remote service.\n"); - buffer - .append("swordclient -cmd -t post [user-options] [proxy-options] [post-options] \n"); - buffer - .append(" [-file file] [-filetype type] [-onBehalfOf name]"); - buffer.append("\n\n"); + buffer.append("Command Mode: Post - Post a file to a remote service.\n"); + buffer.append("swordclient -cmd -t post [user-options] [proxy-options] [post-options] \n"); + buffer.append(" [-file file] [-filetype type] [-onBehalfOf name]"); + buffer.append("\n\n"); - buffer - .append("Command Mode: MultiPost - Post a file to multiple remote services.\n"); - buffer - .append("swordclient -cmd -t multipost [user-options] [proxy-options] [post-options] \n"); - buffer.append(" [-dest dest]"); + buffer.append("Command Mode: MultiPost - Post a file to multiple remote services.\n"); + buffer.append("swordclient -cmd -t multipost [user-options] [proxy-options] [post-options] \n"); + buffer.append(" [-dest dest]"); - buffer.append("\n\n"); - buffer.append("User options: \n"); - buffer - .append(" -u username Specify a username to access the remote service.\n"); - buffer - .append(" -p password Specify a password to access the remote service.\n"); - buffer.append(" Required if -u option is used."); + buffer.append("\n\n"); + buffer.append("User options: \n"); + buffer.append(" -u username Specify a username to access the remote service.\n"); + buffer.append(" -p password Specify a password to access the remote service.\n"); + buffer.append(" Required if -u option is used."); - buffer.append("\n\n"); - buffer.append("Proxy options: \n"); - buffer - .append(" -host host Hostname of a proxy, wwwproxy.aber.ac.uk.\n"); - buffer - .append(" -port port Proxy port number, e.g. 8080.\n"); + buffer.append("\n\n"); + buffer.append("Proxy options: \n"); + buffer.append(" -host host Hostname of a proxy, wwwproxy.aber.ac.uk.\n"); + buffer.append(" -port port Proxy port number, e.g. 8080.\n"); - buffer.append("\n\n"); - buffer.append("Post options: \n"); - buffer - .append(" -noOp Specified to indicate that the post is a test operation.\n"); - buffer - .append(" -md5 Use an MD5 checksum in the message header.\n"); - buffer - .append(" -checksumError Mis-calculate the file checksum for server test purposes.\n"); - buffer.append(" -formatNamespace ns The format namespace value.\n"); - buffer.append(" -slug name The slug value.\n"); - buffer - .append(" -verbose Request a verbose response from the server.\n"); + buffer.append("\n\n"); + buffer.append("Post options: \n"); + buffer.append(" -noOp Specified to indicate that the post is a test operation.\n"); + buffer.append(" -md5 Use an MD5 checksum in the message header.\n"); + buffer.append(" -checksumError Mis-calculate the file checksum for server test purposes.\n"); + buffer.append(" -formatNamespace ns The format namespace value.\n"); + buffer.append(" -slug name The slug value.\n"); + buffer.append(" -verbose Request a verbose response from the server.\n"); - buffer.append("\n\n"); - buffer.append("Other options: \n"); - buffer.append(" -help Show this message.\n"); - buffer - .append(" -t type The type of operation: service, post or multipost.\n"); - buffer - .append(" -href url The URL for the service or post document.\n"); - buffer - .append(" Required for service. The post and multipost operations \n"); - buffer - .append(" will prompt you if the value is not provided.\n"); - buffer - .append(" -filetype type The filetype, e.g. application/zip. The post and multipost\n"); - buffer - .append(" will prompt you for the value if it is not provided.\n"); - buffer - .append(" -onBehalfOf name Specify this parameter to set the On Behalf Of value.\n"); - buffer - .append(" -dest dest Specify the destination for a deposit. This can be repeated\n"); - buffer - .append(" multiple times. The format is: \n"); - buffer - .append(" []:@\n"); - buffer - .append(" e.g. sword[nst]:swordpass@http://sword.aber.ac.uk/post/\n"); - buffer - .append(" nst:pass@http://sword.aber.ac.uk/post\n"); - buffer - .append(" -nocapture Do not capture System.out and System.err to a debug panel\n"); - buffer.append(" in the GUI panel."); + buffer.append("\n\n"); + buffer.append("Other options: \n"); + buffer.append(" -help Show this message.\n"); + buffer.append(" -t type The type of operation: service, post or multipost.\n"); + buffer.append(" -href url The URL for the service or post document.\n"); + buffer.append(" Required for service. The post and multipost operations \n"); + buffer.append(" will prompt you if the value is not provided.\n"); + buffer.append(" -filetype type The filetype, e.g. application/zip. The post and multipost\n"); + buffer.append(" will prompt you for the value if it is not provided.\n"); + buffer.append(" -onBehalfOf name Specify this parameter to set the On Behalf Of value.\n"); + buffer.append(" -dest dest Specify the destination for a deposit. This can be repeated\n"); + buffer.append(" multiple times. The format is: \n"); + buffer.append(" []:@\n"); + buffer.append(" e.g. sword[nst]:swordpass@http://sword.aber.ac.uk/post/\n"); + buffer.append(" nst:pass@http://sword.aber.ac.uk/post\n"); + buffer.append(" -nocapture Do not capture System.out and System.err to a debug panel\n"); + buffer.append(" in the GUI panel."); - return buffer.toString(); - } + return buffer.toString(); + } - /** - * Create a client. If GUI mode is set, a GUI client is created. Otherwise, - * a command line client is created. - * - * @param options - * The list of options extracted from the command line. - * - * @return A new client. - */ - public ClientType createClient(ClientOptions options) { + /** + * Create a client. If GUI mode is set, a GUI client is created. Otherwise, + * a command line client is created. + * + * @param options + * The list of options extracted from the command line. + * + * @return A new client. + */ + public ClientType createClient(ClientOptions options) { return new CmdClient(); - } + } - /** - * Start the application and determine which client should be loaded. The - * application currently has two modes: GUI and client. The GUI mode is the - * default option. - * - * @param args - * The command line arguments. - */ - public static void main(String[] args) { - ClientFactory factory = new ClientFactory(); + /** + * Start the application and determine which client should be loaded. The + * application currently has two modes: GUI and client. The GUI mode is the + * default option. + * + * @param args the command line arguments given + */ + public static void main(String[] args) { + ClientFactory factory = new ClientFactory(); - ClientOptions options = new ClientOptions(); - if (options.parseOptions(args)) { - ClientType client = factory.createClient(options); - client.run(options); - } else { - System.out.println(usage()); - } - } + ClientOptions options = new ClientOptions(); + if (options.parseOptions(args)) { + ClientType client = factory.createClient(options); + client.run(options); + } else { + System.out.println(usage()); + } + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/ClientOptions.java b/dspace-sword/src/main/java/org/purl/sword/client/ClientOptions.java index 1bf82e02da..4747b22305 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/ClientOptions.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/ClientOptions.java @@ -21,607 +21,605 @@ import org.apache.log4j.Logger; */ public class ClientOptions { - /** - * Label for the service operation. - */ - public static final String TYPE_SERVICE = "service"; - - /** - * Label for the post operation. - */ - public static final String TYPE_POST = "post"; - - /** - * Label for the multipost operation. - */ - public static final String TYPE_MULTI_POST = "multipost"; - - /** - * The access type. - */ - private String accessType = null; - - /** - * Proxy host name. - */ - private String proxyHost = null; - - /** - * Proxy host port. - */ - private int proxyPort = 8080; - - /** - * Username to access the service/post server. - */ - private String username = null; - - /** - * Password to access the service/post server. - */ - private String password = null; - - /** - * HREF of the server to access. - */ - private String href = null; - - /** - * Filename to post. - */ - private String filename = null; - - /** - * Filetype. - */ - private String filetype = null; - - /** - * Specifies that the output streams are not to be captured by the GUI client. - */ - private boolean noCapture = false; - - - /** - * SLUG Header field. - */ - private String slug = null; - - /** - * NoOp, used to indicate an operation on the server that does not - * require the file to be stored. - */ - private boolean noOp = false; - - /** - * Request verbose output from the server. - */ - private boolean verbose = false; - - /** - * OnBehalfOf user id. - */ - private String onBehalfOf = null; - - /** - * Format namespace to be used for the posted file. - */ - private String formatNamespace = null; - - /** - * Introduce a checksum error. This is used to simulate an error with the - * MD5 value. - */ - private boolean checksumError = false; - - /** - * Logger. - */ - private static Logger log = Logger.getLogger(ClientOptions.class); - - /** - * List of multiple destination items. Used if the mode is set to multipost. - */ - private List multiPost = new ArrayList(); - - /** - * Pattern string to extract the data from a destination parameter in multipost mode. - */ - private static final Pattern multiPattern = Pattern.compile("(.*?)(\\[(.*?)\\]){0,1}(:(.*)){0,1}@(http://.*)"); - - /** - * Flag that indicates if the GUI mode has been set. This is - * true by default. - */ - private boolean guiMode = true; - - /** - * Flat that indicates if the MD5 option has been selected. This - * is true by default. - */ - private boolean md5 = false; - - /** - * Parse the list of options contained in the specified array. - * - * @param args The array of options. - * - * @return True if the options were parsed successfully. - */ - public boolean parseOptions( String[] args ) - { - try - { - // iterate over the args - for( int i = 0; i < args.length; i++ ) - { - - if( "-md5".equals(args[i])) - { - md5 = true; - } - - if( "-noOp".equals(args[i])) - { - noOp = true; - } - - if( "-verbose".equals(args[i])) - { - verbose = true; - } - - if( "-cmd".equals(args[i]) ) - { - guiMode = false; - } - - if( "-gui".equals(args[i]) ) - { - guiMode = true; - } - - if( "-host".equals(args[i]) ) - { - i++; - proxyHost = args[i]; - } - - if( "-port".equals(args[i]) ) - { - i++; - proxyPort = Integer.parseInt(args[i]); - } - - if( "-u".equals(args[i]) ) - { - i++; - username = args[i]; - } - - if( "-p".equals(args[i])) - { - i++; - password = args[i]; - } - - if( "-href".equals(args[i])) - { - i++; - href = args[i]; - } - - if( "-help".equals(args[i]) ) - { - // force the calling code to display the usage information - return false; - } - - if( "-t".equals(args[i])) - { - i++; - accessType = args[i]; - } - - if( "-file".equals(args[i])) - { - i++; - filename = args[i]; - } - - if( "-filetype".equals(args[i])) - { - i++; - filetype = args[i]; - } - - if( "-slug".equals(args[i])) - { - i++; - slug = args[i]; - } - - if( "-onBehalfOf".equals(args[i])) - { - i++; - onBehalfOf = args[i]; - } - - if( "-formatNamespace".equals(args[i])) - { - i++; - formatNamespace = args[i]; - } - - if( "-checksumError".equals(args[i])) - { - i++; - checksumError = true; - } - - if( "-dest".equals(args[i])) - { - i++; - Matcher m = multiPattern.matcher(args[i]); - if( ! m.matches() ) + /** + * Label for the service operation. + */ + public static final String TYPE_SERVICE = "service"; + + /** + * Label for the post operation. + */ + public static final String TYPE_POST = "post"; + + /** + * Label for the multipost operation. + */ + public static final String TYPE_MULTI_POST = "multipost"; + + /** + * The access type. + */ + private String accessType = null; + + /** + * Proxy host name. + */ + private String proxyHost = null; + + /** + * Proxy host port. + */ + private int proxyPort = 8080; + + /** + * Username to access the service/post server. + */ + private String username = null; + + /** + * Password to access the service/post server. + */ + private String password = null; + + /** + * HREF of the server to access. + */ + private String href = null; + + /** + * Filename to post. + */ + private String filename = null; + + /** + * Filetype. + */ + private String filetype = null; + + /** + * Specifies that the output streams are not to be captured by the GUI client. + */ + private boolean noCapture = false; + + + /** + * SLUG Header field. + */ + private String slug = null; + + /** + * NoOp, used to indicate an operation on the server that does not + * require the file to be stored. + */ + private boolean noOp = false; + + /** + * Request verbose output from the server. + */ + private boolean verbose = false; + + /** + * OnBehalfOf user id. + */ + private String onBehalfOf = null; + + /** + * Format namespace to be used for the posted file. + */ + private String formatNamespace = null; + + /** + * Introduce a checksum error. This is used to simulate an error with the + * MD5 value. + */ + private boolean checksumError = false; + + /** + * Logger. + */ + private static Logger log = Logger.getLogger(ClientOptions.class); + + /** + * List of multiple destination items. Used if the mode is set to multipost. + */ + private List multiPost = new ArrayList(); + + /** + * Pattern string to extract the data from a destination parameter in multipost mode. + */ + private static final Pattern multiPattern = Pattern.compile("(.*?)(\\[(.*?)\\]) {0,1}(:(.*)) {0,1}@(http://.*)"); + + /** + * Flag that indicates if the GUI mode has been set. This is + * true by default. + */ + private boolean guiMode = true; + + /** + * Flat that indicates if the MD5 option has been selected. This + * is true by default. + */ + private boolean md5 = false; + + /** + * Parse the list of options contained in the specified array. + * + * @param args The array of options. + * + * @return True if the options were parsed successfully. + */ + public boolean parseOptions( String[] args ) + { + try + { + // iterate over the args + for ( int i = 0; i < args.length; i++ ) + { + if ( "-md5".equals(args[i])) { - log.debug("Error with dest parameter. Ignoring value: " + args[i]); + md5 = true; } - else + + if ( "-noOp".equals(args[i])) { - int numGroups = m.groupCount(); - for( int g = 0; g <= numGroups; g++ ) + noOp = true; + } + + if ( "-verbose".equals(args[i])) + { + verbose = true; + } + + if ( "-cmd".equals(args[i]) ) + { + guiMode = false; + } + + if ( "-gui".equals(args[i]) ) + { + guiMode = true; + } + + if ( "-host".equals(args[i]) ) + { + i++; + proxyHost = args[i]; + } + + if ( "-port".equals(args[i]) ) + { + i++; + proxyPort = Integer.parseInt(args[i]); + } + + if ( "-u".equals(args[i]) ) + { + i++; + username = args[i]; + } + + if ( "-p".equals(args[i])) + { + i++; + password = args[i]; + } + + if ( "-href".equals(args[i])) + { + i++; + href = args[i]; + } + + if ( "-help".equals(args[i]) ) + { + // force the calling code to display the usage information + return false; + } + + if ( "-t".equals(args[i])) + { + i++; + accessType = args[i]; + } + + if ( "-file".equals(args[i])) + { + i++; + filename = args[i]; + } + + if ( "-filetype".equals(args[i])) + { + i++; + filetype = args[i]; + } + + if ( "-slug".equals(args[i])) + { + i++; + slug = args[i]; + } + + if ( "-onBehalfOf".equals(args[i])) + { + i++; + onBehalfOf = args[i]; + } + + if ( "-formatNamespace".equals(args[i])) + { + i++; + formatNamespace = args[i]; + } + + if ( "-checksumError".equals(args[i])) + { + i++; + checksumError = true; + } + + if ( "-dest".equals(args[i])) + { + i++; + Matcher m = multiPattern.matcher(args[i]); + if ( ! m.matches() ) { - log.debug("Group (" + g + ") is: " + m.group(g)); + log.debug("Error with dest parameter. Ignoring value: " + args[i]); + } + else + { + int numGroups = m.groupCount(); + for ( int g = 0; g <= numGroups; g++ ) + { + log.debug("Group (" + g + ") is: " + m.group(g)); + } + + String username = m.group(1); + String onBehalfOf = m.group(3); + String password = m.group(5); + String url = m.group(6); + PostDestination destination = new PostDestination(url, username, password, onBehalfOf); + + multiPost.add(destination); } - - String username = m.group(1); - String onBehalfOf = m.group(3); - String password = m.group(5); - String url = m.group(6); - PostDestination destination = new PostDestination(url, username, password, onBehalfOf); - - multiPost.add(destination); } - } - - if( "-nocapture".equals(args[i]) ) - { - i++; - noCapture = true; - } - - } - - // apply any settings - if( href == null && "service".equals(accessType) ) - { - log.error( "No href specified."); - return false; - } - - if( multiPost.size() == 0 && "multipost".equals(accessType)) - { - log.error("No destinations specified"); + + if ( "-nocapture".equals(args[i]) ) + { + i++; + noCapture = true; + } + } + + // apply any settings + if ( href == null && "service".equals(accessType) ) + { + log.error( "No href specified."); + return false; + } + + if ( multiPost.size() == 0 && "multipost".equals(accessType)) + { + log.error("No destinations specified"); + return false; + } + + if ( accessType == null && ! guiMode ) + { + log.error("No access type specified"); + return false; + } + + if ( ( username == null && password != null ) || (username != null && password == null)) + { + log.error("The username and/or password are not specified. If one is specified, the other must also be specified."); + return false; + } + } + catch ( ArrayIndexOutOfBoundsException ex ) + { + log.error("Error with parameters."); return false; - } - - if( accessType == null && ! guiMode ) - { - log.error("No access type specified"); - return false; - } - - if( ( username == null && password != null ) || (username != null && password == null)) - { - log.error("The username and/or password are not specified. If one is specified, the other must also be specified."); - return false; - } - } - catch( ArrayIndexOutOfBoundsException ex ) - { - log.error("Error with parameters."); - return false; - } - - return true; - } - - /** - * Get the access type. - * @return The value, or null if the value is not set. - */ - public String getAccessType() - { - return accessType; - } - - /** - * Set the access type. - * @param accessType The value, or null to clear the value. - */ - public void setAccessType(String accessType) - { - this.accessType = accessType; - } - - /** - * Get the proxy host. - * @return The value, or null if the value is not set. - */ - public String getProxyHost() - { - return proxyHost; - } - - /** - * Set the proxy host. - * @param proxyHost The value, or null to clear the value. - */ - public void setProxyHost(String proxyHost) - { - this.proxyHost = proxyHost; - } - - /** - * Get the proxy port. - * @return The proxy port. Default value is 80. - */ - public int getProxyPort() - { - return proxyPort; - } - - /** - * Set the proxy port. - * @param proxyPort The proxy port. - */ - public void setProxyPort(int proxyPort) - { - this.proxyPort = proxyPort; - } - - /** - * Get the username. - * @return The value, or null if the value is not set. - */ - public String getUsername() - { - return username; - } - - /** - * Set the username. - * @param username The value, or null to clear the value. - */ - public void setUsername(String username) - { - this.username = username; - } - - /** - * Get the password. - * @return The value, or null if the value is not set. - */ - public String getPassword() - { - return password; - } - - /** - * Set the password. - * @param password The value, or null to clear the value. - */ - public void setPassword(String password) - { - this.password = password; - } - - /** - * Get the HREF of the service to access. - * @return The value, or null if the value is not set. - */ - public String getHref() - { - return href; - } - - /** - * Set the HREF of the service to access. - * @param href The value, or null to clear the value. - */ - public void setHref(String href) - { - this.href = href; - } - - /** - * Get the name of the file to post. - * @return The value, or null if the value is not set. - */ - public String getFilename() - { - return filename; - } - - /** - * Set the name of the file to post. - * @param filename The value, or null to clear the value. - */ - public void setFilename(String filename) - { - this.filename = filename; - } - - /** - * Get the type of the file to post. - * @return The filetype, or null if the value is not set. - */ - public String getFiletype() - { - return filetype; - } - - /** - * Set the type of the file to post. - * @param filetype The value, or null to clear the value. - */ - public void setFiletype(String filetype) - { - this.filetype = filetype; - } - - /** - * Determine if the tool is to be run in GUI mode. - * @return True if the tool is set for GUI mode. - */ - public boolean isGuiMode() - { - return guiMode; - } - - /** - * Set the tool to run in GUI mode. - * @param guiMode True if the tool is to run in gui mode. - */ - public void setGuiMode(boolean guiMode) - { - this.guiMode = guiMode; - } - - /** - * Get the MD5 setting. True if the tool is to use MD5 for post operations. - * @return The MD5 setting. - */ - public boolean isMd5() { - return md5; - } - - /** - * Set the MD5 setting. - * @param md5 True if the tool should use MD5 for post operations. - */ - public void setMd5(boolean md5) { - this.md5 = md5; - } - - /** - * Determine if the NoOp header should be sent. - * @return True if the header should be sent. - */ - public boolean isNoOp() { - return noOp; - } - - /** - * Set the NoOp setting. - * @param noOp True if the NoOp header should be used. - */ - public void setNoOp(boolean noOp) { - this.noOp = noOp; - } - - /** - * Determine if the verbose option is set. - * @return True if verbose option is set. - */ - public boolean isVerbose() { - return verbose; - } - - /** - * Set the verbose option. - * @param verbose True if verbose should be set. - */ - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - /** - * Get the onBehalfOf value. - * @return The value, or null to clear the value. - */ - public String getOnBehalfOf() { - return onBehalfOf; - } - - /** - * Set the onBehalf of Value. - * @param onBehalfOf The value, or null to clear the value. - */ - public void setOnBehalfOf(String onBehalfOf) { - this.onBehalfOf = onBehalfOf; - } - - /** - * Get the format namespace value. - * @return The value, or null if the value is not set. - */ - public String getFormatNamespace() { - return formatNamespace; - } - - /** - * Set the format namespace value. - * @param formatNamespace The value, or null to clear the value. - */ - public void setFormatNamespace(String formatNamespace) { - this.formatNamespace = formatNamespace; - } - - /** - * Get the checksum error value. - * @return True if an error should be introduced into the checksum. - */ - public boolean getChecksumError() { - return checksumError; - } - - /** - * Set the checksum error value. - * @param checksumError True if the error should be introduced. - */ - public void setChecksumError(boolean checksumError) { - this.checksumError = checksumError; - } - - /** - * Get the current slug header. - * @return The slug value, or null if the value is not set. - */ - public String getSlug( ) - { - return this.slug; - } - - /** - * Set the text that is to be used for the slug header. - * @param slug The value, or null to clear the value. - */ - public void setSlug(String slug) - { - this.slug = slug; - } - - /** - * Get the list of post destinations. - * @return An iterator over the list of PostDestination objects. - */ - public Iterator getMultiPost() - { - return multiPost.iterator(); - } - - - /** - * Determine if the noCapture option is set. This indicates that the code - * should not attempt to redirect stdout and stderr to a different output - * destination. Intended for use in a GUI client. - * - * @return The noCapture setting. True if set. - */ - public boolean isNoCapture() - { - return noCapture; - } + } + + return true; + } + + /** + * Get the access type. + * @return The value, or null if the value is not set. + */ + public String getAccessType() + { + return accessType; + } + + /** + * Set the access type. + * @param accessType The value, or null to clear the value. + */ + public void setAccessType(String accessType) + { + this.accessType = accessType; + } + + /** + * Get the proxy host. + * @return The value, or null if the value is not set. + */ + public String getProxyHost() + { + return proxyHost; + } + + /** + * Set the proxy host. + * @param proxyHost The value, or null to clear the value. + */ + public void setProxyHost(String proxyHost) + { + this.proxyHost = proxyHost; + } + + /** + * Get the proxy port. + * @return The proxy port. Default value is 80. + */ + public int getProxyPort() + { + return proxyPort; + } + + /** + * Set the proxy port. + * @param proxyPort The proxy port. + */ + public void setProxyPort(int proxyPort) + { + this.proxyPort = proxyPort; + } + + /** + * Get the username. + * @return The value, or null if the value is not set. + */ + public String getUsername() + { + return username; + } + + /** + * Set the username. + * @param username The value, or null to clear the value. + */ + public void setUsername(String username) + { + this.username = username; + } + + /** + * Get the password. + * @return The value, or null if the value is not set. + */ + public String getPassword() + { + return password; + } + + /** + * Set the password. + * @param password The value, or null to clear the value. + */ + public void setPassword(String password) + { + this.password = password; + } + + /** + * Get the HREF of the service to access. + * @return The value, or null if the value is not set. + */ + public String getHref() + { + return href; + } + + /** + * Set the HREF of the service to access. + * @param href The value, or null to clear the value. + */ + public void setHref(String href) + { + this.href = href; + } + + /** + * Get the name of the file to post. + * @return The value, or null if the value is not set. + */ + public String getFilename() + { + return filename; + } + + /** + * Set the name of the file to post. + * @param filename The value, or null to clear the value. + */ + public void setFilename(String filename) + { + this.filename = filename; + } + + /** + * Get the type of the file to post. + * @return The filetype, or null if the value is not set. + */ + public String getFiletype() + { + return filetype; + } + + /** + * Set the type of the file to post. + * @param filetype The value, or null to clear the value. + */ + public void setFiletype(String filetype) + { + this.filetype = filetype; + } + + /** + * Determine if the tool is to be run in GUI mode. + * @return True if the tool is set for GUI mode. + */ + public boolean isGuiMode() + { + return guiMode; + } + + /** + * Set the tool to run in GUI mode. + * @param guiMode True if the tool is to run in gui mode. + */ + public void setGuiMode(boolean guiMode) + { + this.guiMode = guiMode; + } + + /** + * Get the MD5 setting. True if the tool is to use MD5 for post operations. + * @return The MD5 setting. + */ + public boolean isMd5() { + return md5; + } + + /** + * Set the MD5 setting. + * @param md5 True if the tool should use MD5 for post operations. + */ + public void setMd5(boolean md5) { + this.md5 = md5; + } + + /** + * Determine if the NoOp header should be sent. + * @return True if the header should be sent. + */ + public boolean isNoOp() { + return noOp; + } + + /** + * Set the NoOp setting. + * @param noOp True if the NoOp header should be used. + */ + public void setNoOp(boolean noOp) { + this.noOp = noOp; + } + + /** + * Determine if the verbose option is set. + * @return True if verbose option is set. + */ + public boolean isVerbose() { + return verbose; + } + + /** + * Set the verbose option. + * @param verbose True if verbose should be set. + */ + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + /** + * Get the onBehalfOf value. + * @return The value, or null to clear the value. + */ + public String getOnBehalfOf() { + return onBehalfOf; + } + + /** + * Set the onBehalf of Value. + * @param onBehalfOf The value, or null to clear the value. + */ + public void setOnBehalfOf(String onBehalfOf) { + this.onBehalfOf = onBehalfOf; + } + + /** + * Get the format namespace value. + * @return The value, or null if the value is not set. + */ + public String getFormatNamespace() { + return formatNamespace; + } + + /** + * Set the format namespace value. + * @param formatNamespace The value, or null to clear the value. + */ + public void setFormatNamespace(String formatNamespace) { + this.formatNamespace = formatNamespace; + } + + /** + * Get the checksum error value. + * @return True if an error should be introduced into the checksum. + */ + public boolean getChecksumError() { + return checksumError; + } + + /** + * Set the checksum error value. + * @param checksumError True if the error should be introduced. + */ + public void setChecksumError(boolean checksumError) { + this.checksumError = checksumError; + } + + /** + * Get the current slug header. + * @return The slug value, or null if the value is not set. + */ + public String getSlug( ) + { + return this.slug; + } + + /** + * Set the text that is to be used for the slug header. + * @param slug The value, or null to clear the value. + */ + public void setSlug(String slug) + { + this.slug = slug; + } + + /** + * Get the list of post destinations. + * @return An iterator over the list of PostDestination objects. + */ + public Iterator getMultiPost() + { + return multiPost.iterator(); + } + + + /** + * Determine if the noCapture option is set. This indicates that the code + * should not attempt to redirect stdout and stderr to a different output + * destination. Intended for use in a GUI client. + * + * @return The noCapture setting. True if set. + */ + public boolean isNoCapture() + { + return noCapture; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/CmdClient.java b/dspace-sword/src/main/java/org/purl/sword/client/CmdClient.java index 520f5b4554..fb48a91542 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/CmdClient.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/CmdClient.java @@ -42,336 +42,336 @@ import org.purl.sword.base.SwordAcceptPackaging; */ public class CmdClient implements ClientType { - /** - * The client that is used to process the service and post requests. - */ - private SWORDClient client; + /** + * The client that is used to process the service and post requests. + */ + private SWORDClient client; - /** - * List of the options that can be specified on the command line. - */ - private ClientOptions options; - - /** - * The logger. - */ - private static Logger log = Logger.getLogger(CmdClient.class); - - /** - * Create a new instance of the class and create an instance of the - * client. - */ - public CmdClient( ) - { - client = new Client( ); - } + /** + * List of the options that can be specified on the command line. + */ + private ClientOptions options; + + /** + * The logger. + */ + private static Logger log = Logger.getLogger(CmdClient.class); + + /** + * Create a new instance of the class and create an instance of the + * client. + */ + public CmdClient( ) + { + client = new Client( ); + } - /** - * Process the options that have been initialised from the command line. - * This will call one of service(), post() or multiPost(). - */ - public void process() - { - if (options.getProxyHost() != null) - { - client.setProxy(options.getProxyHost(), options.getProxyPort()); - } + /** + * Process the options that have been initialised from the command line. + * This will call one of service(), post() or multiPost(). + */ + public void process() + { + if (options.getProxyHost() != null) + { + client.setProxy(options.getProxyHost(), options.getProxyPort()); + } - try - { - String accessType = options.getAccessType(); - if (ClientOptions.TYPE_SERVICE.equals(accessType)) - { - service(); - } - else if (ClientOptions.TYPE_POST.equals(accessType)) - { - post(); - } - else if (ClientOptions.TYPE_MULTI_POST.equals(accessType) ) - { - System.out.println("checking multi-post"); - multiPost(); - } - else - { - System.out.println("Access type not recognised."); - } + try + { + String accessType = options.getAccessType(); + if (ClientOptions.TYPE_SERVICE.equals(accessType)) + { + service(); + } + else if (ClientOptions.TYPE_POST.equals(accessType)) + { + post(); + } + else if (ClientOptions.TYPE_MULTI_POST.equals(accessType) ) + { + System.out.println("checking multi-post"); + multiPost(); + } + else + { + System.out.println("Access type not recognised."); + } - } - catch ( MalformedURLException mex ) - { - System.out.println("The specified href was not valid: " + options.getHref() + " message: " + mex.getMessage()); - } - catch (SWORDClientException ex) - { - System.out.println("Exception: " + ex.getMessage()); + } + catch ( MalformedURLException mex ) + { + System.out.println("The specified href was not valid: " + options.getHref() + " message: " + mex.getMessage()); + } + catch (SWORDClientException ex) + { + System.out.println("Exception: " + ex.getMessage()); log.error("Unable to process request", ex); - } - } + } + } - /** - * Process the service operation. Output the results of the service request. - * - * @throws SWORDClientException if there is an error processing the service request. + /** + * Process the service operation. Output the results of the service request. + * + * @throws SWORDClientException if there is an error processing the service request. * @throws MalformedURLException if there is an error with the URL for the service request. - */ - private void service() - throws SWORDClientException, MalformedURLException - { - String href = options.getHref(); - initialiseServer(href, options.getUsername(), options.getPassword()); + */ + private void service() + throws SWORDClientException, MalformedURLException + { + String href = options.getHref(); + initialiseServer(href, options.getUsername(), options.getPassword()); - ServiceDocument document = client.getServiceDocument(href, options.getOnBehalfOf()); - Status status = client.getStatus(); - System.out.println("The status is: " + status); + ServiceDocument document = client.getServiceDocument(href, options.getOnBehalfOf()); + Status status = client.getStatus(); + System.out.println("The status is: " + status); - if (status.getCode() == 200) - { - log.debug("message is: " + document.marshall()); - - System.out.println("\nThe following Details were retrieved: "); - System.out.println("SWORD Version: " - + document.getService().getVersion()); - System.out.println("Supports NoOp? " + document.getService().isNoOp()); - System.out.println("Supports Verbose? " - + document.getService().isVerbose()); - System.out.println("Max Upload File Size " - + document.getService().getMaxUploadSize() +" kB"); + if (status.getCode() == 200) + { + log.debug("message is: " + document.marshall()); + + System.out.println("\nThe following Details were retrieved: "); + System.out.println("SWORD Version: " + + document.getService().getVersion()); + System.out.println("Supports NoOp? " + document.getService().isNoOp()); + System.out.println("Supports Verbose? " + + document.getService().isVerbose()); + System.out.println("Max Upload File Size " + + document.getService().getMaxUploadSize() +" kB"); - Iterator workspaces = document.getService().getWorkspaces(); - for (; workspaces.hasNext();) - { - Workspace workspace = workspaces.next(); - System.out.println("\nWorkspace Title: '" - + workspace.getTitle() + "'"); + Iterator workspaces = document.getService().getWorkspaces(); + for (; workspaces.hasNext();) + { + Workspace workspace = workspaces.next(); + System.out.println("\nWorkspace Title: '" + + workspace.getTitle() + "'"); - System.out.println("\n+ Collections ---"); - // process the collections - Iterator collections = workspace - .collectionIterator(); - for (; collections.hasNext();) - { - Collection collection = collections.next(); - System.out.println("\nCollection location: " - + collection.getLocation()); - System.out.println("Collection title: " - + collection.getTitle()); - System.out - .println("Abstract: " + collection.getAbstract()); - System.out.println("Collection Policy: " - + collection.getCollectionPolicy()); - System.out.println("Treatment: " - + collection.getTreatment()); - System.out.println("Mediation: " - + collection.getMediation()); + System.out.println("\n+ Collections ---"); + // process the collections + Iterator collections = workspace + .collectionIterator(); + for (; collections.hasNext();) + { + Collection collection = collections.next(); + System.out.println("\nCollection location: " + + collection.getLocation()); + System.out.println("Collection title: " + + collection.getTitle()); + System.out + .println("Abstract: " + collection.getAbstract()); + System.out.println("Collection Policy: " + + collection.getCollectionPolicy()); + System.out.println("Treatment: " + + collection.getTreatment()); + System.out.println("Mediation: " + + collection.getMediation()); - String[] accepts = collection.getAccepts(); - if( accepts != null && accepts.length == 0 ) - { - System.out.println("Accepts: none specified"); - } - else - { - for (String s : accepts) - { - System.out.println("Accepts: " + s); - } - } + String[] accepts = collection.getAccepts(); + if ( accepts != null && accepts.length == 0 ) + { + System.out.println("Accepts: none specified"); + } + else + { + for (String s : accepts) + { + System.out.println("Accepts: " + s); + } + } List acceptsPackaging = collection.getAcceptPackaging(); StringBuilder acceptPackagingList = new StringBuilder(); - for(Iterator i = acceptsPackaging.iterator();i.hasNext();) + for (Iterator i = acceptsPackaging.iterator();i.hasNext();) { SwordAcceptPackaging accept = (SwordAcceptPackaging) i.next(); acceptPackagingList.append(accept.getContent()).append(" (").append(accept.getQualityValue()).append("), ").toString(); } System.out.println("Accepts Packaging: "+ acceptPackagingList.toString()); - } - System.out.println("+ End of Collections ---"); - } - } - } - - /** - * Perform a post. If any of the destination URL, the filename and the - * filetype are missing, the user will be prompted to enter the values. - * - * @throws SWORDClientException if there is an error processing the post for a requested + } + System.out.println("+ End of Collections ---"); + } + } + } + + /** + * Perform a post. If any of the destination URL, the filename and the + * filetype are missing, the user will be prompted to enter the values. + * + * @throws SWORDClientException if there is an error processing the post for a requested * destination. * @throws MalformedURLException if there is an error with the URL for the post. - */ - private void post() - throws SWORDClientException, MalformedURLException - { - String url = options.getHref(); - if( url == null ) - { - url = readLine("Please enter the URL for the deposit: "); - } + */ + private void post() + throws SWORDClientException, MalformedURLException + { + String url = options.getHref(); + if ( url == null ) + { + url = readLine("Please enter the URL for the deposit: "); + } - initialiseServer(url, options.getUsername(), options.getPassword()); - String file = options.getFilename(); - if( file == null ) - { - file = readLine("Please enter the filename to deposit: "); - } - String type = options.getFiletype(); - if( type == null ) - { - type = readLine("Please enter the file type, e.g. application/zip: "); - } + initialiseServer(url, options.getUsername(), options.getPassword()); + String file = options.getFilename(); + if ( file == null ) + { + file = readLine("Please enter the filename to deposit: "); + } + String type = options.getFiletype(); + if ( type == null ) + { + type = readLine("Please enter the file type, e.g. application/zip: "); + } - PostMessage message = new PostMessage(); - message.setFilepath(file); - message.setDestination(url); - message.setFiletype(type); - message.setUseMD5(options.isMd5()); - message.setVerbose(options.isVerbose()); - message.setNoOp(options.isNoOp()); - message.setFormatNamespace(options.getFormatNamespace()); - message.setOnBehalfOf(options.getOnBehalfOf()); - message.setChecksumError(options.getChecksumError()); + PostMessage message = new PostMessage(); + message.setFilepath(file); + message.setDestination(url); + message.setFiletype(type); + message.setUseMD5(options.isMd5()); + message.setVerbose(options.isVerbose()); + message.setNoOp(options.isNoOp()); + message.setFormatNamespace(options.getFormatNamespace()); + message.setOnBehalfOf(options.getOnBehalfOf()); + message.setChecksumError(options.getChecksumError()); message.setUserAgent(ClientConstants.SERVICE_NAME); - - processPost(message); + + processPost(message); - } + } - /** - * Perform a multi-post. Iterate over the list of -dest arguments in the command line - * options. For each -dest argument, attempt to post the file to the server. - * - * @throws SWORDClientException if there is an error processing the post for a requested - * destination. - * @throws MalformedURLException if there is an error with the URL for the post. - */ - private void multiPost() - throws SWORDClientException, MalformedURLException - { - // request the common information - String file = options.getFilename(); - if( file == null ) - { - file = readLine("Please enter the filename to deposit: "); - } - String type = options.getFiletype(); - if( type == null ) - { - type = readLine("Please enter the file type, e.g. application/zip: "); - } - - // process this information for each of the specified destinations - PostDestination destination; - String url = null; - - Iterator iterator = options.getMultiPost(); - while( iterator.hasNext() ) - { - destination = iterator.next(); - url = destination.getUrl(); - initialiseServer(url, destination.getUsername(), destination.getPassword()); - - String onBehalfOf = destination.getOnBehalfOf(); - if( onBehalfOf == null ) - { - onBehalfOf = ""; - } - else - { - onBehalfOf = " on behalf of: " + onBehalfOf; - } - - System.out.println("Sending file to: " + url + " for: " + destination.getUsername() + - onBehalfOf ); - PostMessage message = new PostMessage(); - message.setFilepath(file); - message.setDestination(url); - message.setFiletype(type); - message.setUseMD5(options.isMd5()); - message.setVerbose(options.isVerbose()); - message.setNoOp(options.isNoOp()); - message.setFormatNamespace(options.getFormatNamespace()); - message.setOnBehalfOf(destination.getOnBehalfOf()); - message.setChecksumError(options.getChecksumError()); + /** + * Perform a multi-post. Iterate over the list of -dest arguments in the command line + * options. For each -dest argument, attempt to post the file to the server. + * + * @throws SWORDClientException if there is an error processing the post for a requested + * destination. + * @throws MalformedURLException if there is an error with the URL for the post. + */ + private void multiPost() + throws SWORDClientException, MalformedURLException + { + // request the common information + String file = options.getFilename(); + if ( file == null ) + { + file = readLine("Please enter the filename to deposit: "); + } + String type = options.getFiletype(); + if ( type == null ) + { + type = readLine("Please enter the file type, e.g. application/zip: "); + } + + // process this information for each of the specified destinations + PostDestination destination; + String url = null; + + Iterator iterator = options.getMultiPost(); + while ( iterator.hasNext() ) + { + destination = iterator.next(); + url = destination.getUrl(); + initialiseServer(url, destination.getUsername(), destination.getPassword()); + + String onBehalfOf = destination.getOnBehalfOf(); + if ( onBehalfOf == null ) + { + onBehalfOf = ""; + } + else + { + onBehalfOf = " on behalf of: " + onBehalfOf; + } + + System.out.println("Sending file to: " + url + " for: " + destination.getUsername() + + onBehalfOf ); + PostMessage message = new PostMessage(); + message.setFilepath(file); + message.setDestination(url); + message.setFiletype(type); + message.setUseMD5(options.isMd5()); + message.setVerbose(options.isVerbose()); + message.setNoOp(options.isNoOp()); + message.setFormatNamespace(options.getFormatNamespace()); + message.setOnBehalfOf(destination.getOnBehalfOf()); + message.setChecksumError(options.getChecksumError()); message.setUserAgent(ClientConstants.SERVICE_NAME); - - processPost(message); - } - - } + + processPost(message); + } + + } - /** - * Process the post response. The message contains the list of arguments - * for the post. The method will then print out the details of the - * response. - * - * @param message The post options. - * - * @exception SWORDClientException if there is an error accessing the - * post response. - */ - protected void processPost(PostMessage message) - throws SWORDClientException - { - DepositResponse response = client.postFile(message); + /** + * Process the post response. The message contains the list of arguments + * for the post. The method will then print out the details of the + * response. + * + * @param message The post options. + * + * @throws SWORDClientException if there is an error accessing the + * post response. + */ + protected void processPost(PostMessage message) + throws SWORDClientException + { + DepositResponse response = client.postFile(message); - System.out.println("The status is: " + client.getStatus()); - - if( response != null) - { - log.debug("message is: " + response.marshall()); - - // iterate over the data and output it - SWORDEntry entry = response.getEntry(); - + System.out.println("The status is: " + client.getStatus()); + + if ( response != null) + { + log.debug("message is: " + response.marshall()); + + // iterate over the data and output it + SWORDEntry entry = response.getEntry(); + - System.out.println("Id: " + entry.getId()); - Title title = entry.getTitle(); - if( title != null ) - { - System.out.print("Title: " + title.getContent() + " type: " ); - if( title.getType() != null ) - { - System.out.println(title.getType().toString()); - } - else - { - System.out.println("Not specified."); - } - } + System.out.println("Id: " + entry.getId()); + Title title = entry.getTitle(); + if ( title != null ) + { + System.out.print("Title: " + title.getContent() + " type: " ); + if ( title.getType() != null ) + { + System.out.println(title.getType().toString()); + } + else + { + System.out.println("Not specified."); + } + } - // process the authors - Iterator authors = entry.getAuthors(); - while( authors.hasNext() ) - { - Author author = authors.next(); - System.out.println("Author - " + author.toString() ); - } - - Iterator categories = entry.getCategories(); - while( categories.hasNext() ) - { - System.out.println("Category: " + categories.next()); - } - - Iterator contributors = entry.getContributors(); - while( contributors.hasNext() ) - { - Contributor contributor = contributors.next(); - System.out.println("Contributor - " + contributor.toString()); - } - - Iterator links = entry.getLinks(); - while( links.hasNext() ) - { - Link link = links.next(); - System.out.println(link.toString()); - } + // process the authors + Iterator authors = entry.getAuthors(); + while ( authors.hasNext() ) + { + Author author = authors.next(); + System.out.println("Author - " + author.toString() ); + } + + Iterator categories = entry.getCategories(); + while ( categories.hasNext() ) + { + System.out.println("Category: " + categories.next()); + } + + Iterator contributors = entry.getContributors(); + while ( contributors.hasNext() ) + { + Contributor contributor = contributors.next(); + System.out.println("Contributor - " + contributor.toString()); + } + + Iterator links = entry.getLinks(); + while ( links.hasNext() ) + { + Link link = links.next(); + System.out.println(link.toString()); + } Generator generator = entry.getGenerator(); - if( generator != null ) + if ( generator != null ) { System.out.println("Generator - " + generator.toString()); } @@ -381,62 +381,61 @@ public class CmdClient implements ClientType } System.out.println( "Published: " + entry.getPublished()); - - Content content = entry.getContent(); - if( content != null ) - { - System.out.println(content.toString()); - } - else - { - System.out.println("There is no content element."); - } - - Rights right = entry.getRights(); - if( right != null ) - { - - System.out.println(right.toString()); - } - else - { - System.out.println("There is no right element."); - } - - Summary summary = entry.getSummary(); - if( summary != null ) - { - System.out.println(summary.toString()); - } - else - { - System.out.println("There is no summary element."); - } - - System.out.println("Update: " + entry.getUpdated() ); - System.out.println("Published: " + entry.getPublished()); - System.out.println("Verbose Description: " + entry.getVerboseDescription()); - System.out.println("Treatment: " + entry.getTreatment()); - System.out.println("Packaging: " + entry.getPackaging()); + Content content = entry.getContent(); + if ( content != null ) + { + System.out.println(content.toString()); + } + else + { + System.out.println("There is no content element."); + } + + Rights right = entry.getRights(); + if ( right != null ) + { + System.out.println(right.toString()); + } + else + { + System.out.println("There is no right element."); + } + + Summary summary = entry.getSummary(); + if ( summary != null ) + { + + System.out.println(summary.toString()); + } + else + { + System.out.println("There is no summary element."); + } + + System.out.println("Update: " + entry.getUpdated() ); + System.out.println("Published: " + entry.getPublished()); + System.out.println("Verbose Description: " + entry.getVerboseDescription()); + System.out.println("Treatment: " + entry.getTreatment()); + System.out.println("Packaging: " + entry.getPackaging()); - if( entry.isNoOpSet() ) - { - System.out.println("NoOp: " + entry.isNoOp()); - } - } - else - { - System.out.println("No valid Entry document was received from the server"); - } - } - - /** - * Initialise the server. Set the server that will be connected to and - * initialise any username and password. If the username and password are - * either null or contain empty strings, the user credentials will be cleared. - * - * @param location The location to connect to. This is a URL, of the format, + if ( entry.isNoOpSet() ) + { + System.out.println("NoOp: " + entry.isNoOp()); + } + } + else + { + System.out.println("No valid Entry document was received from the server"); + } + } + + /** + * Initialise the server. Set the server that will be connected to and + * initialise any username and password. If the username and password are + * either null or contain empty strings, the user credentials will be cleared. + * + * @param location The location to connect to. This is a URL, of the format, * http://a.host.com:port/. The host name and port number will * be extracted. If the port is not specified, a default port of * 80 will be used. @@ -446,71 +445,71 @@ public class CmdClient implements ClientType * credentials will be cleared. * * @throws MalformedURLException if there is an error processing the URL. - */ - private void initialiseServer(String location, String username, String password) - throws MalformedURLException - { - URL url = new URL(location); - int port = url.getPort(); - if( port == -1 ) - { - port = 80; - } + */ + private void initialiseServer(String location, String username, String password) + throws MalformedURLException + { + URL url = new URL(location); + int port = url.getPort(); + if ( port == -1 ) + { + port = 80; + } - client.setServer(url.getHost(), port); + client.setServer(url.getHost(), port); - if (username != null && username.length() > 0 && + if (username != null && username.length() > 0 && password != null && password.length() > 0 ) - { - log.info("Setting the username/password: " + username + " " - + password); - client.setCredentials(username, password); - } - else - { - client.clearCredentials(); - } - } + { + log.info("Setting the username/password: " + username + " " + + password); + client.setCredentials(username, password); + } + else + { + client.clearCredentials(); + } + } - /** - * Read a line of text from System.in. If there is an error reading - * from the input, the prompt will be redisplayed and the user asked - * to try again. - * - * @param prompt The prompt to display before the prompt. - * @return The string that is read from the line. - */ - private String readLine( String prompt ) - { - BufferedReader reader = new BufferedReader(new InputStreamReader( - System.in)); - String result = null; + /** + * Read a line of text from System.in. If there is an error reading + * from the input, the prompt will be redisplayed and the user asked + * to try again. + * + * @param prompt The prompt to display before the prompt. + * @return The string that is read from the line. + */ + private String readLine( String prompt ) + { + BufferedReader reader = new BufferedReader(new InputStreamReader( + System.in)); + String result = null; - boolean ok = false; - while (!ok) - { - try - { - System.out.print(prompt); - System.out.flush(); - result = reader.readLine(); - ok = true; - } catch (IOException ex) { - System.out.println("There was an error with your input. Please try again."); - } - } + boolean ok = false; + while (!ok) + { + try + { + System.out.print(prompt); + System.out.flush(); + result = reader.readLine(); + ok = true; + } catch (IOException ex) { + System.out.println("There was an error with your input. Please try again."); + } + } - return result; - } + return result; + } /** * Run the client and process the specified options. * * @param options The command line options. */ - public void run( ClientOptions options ) - { - this.options = options; - process( ); - } + public void run( ClientOptions options ) + { + this.options = options; + process( ); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/DebugOutputStream.java b/dspace-sword/src/main/java/org/purl/sword/client/DebugOutputStream.java index 9ddd4c7033..1a66df46f2 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/DebugOutputStream.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/DebugOutputStream.java @@ -17,32 +17,32 @@ import java.io.OutputStream; */ public class DebugOutputStream extends OutputStream { - /** - * Panel that will display the messages. - */ - private MessageOutputPanel panel; - - /** - * Create a new instance and specify the panel that will receive the output. - * - * @param panel The panel. - */ - public DebugOutputStream(MessageOutputPanel panel) - { - this.panel = panel; - } - - /** - * Override the write method from OutputStream. Capture the char and - * send it to the panel. - * - * @param arg0 The output character, expressed as an integer. - * - * @see java.io.OutputStream#write(int) - */ - public void write(int arg0) throws IOException - { - panel.addCharacter(Character.valueOf((char)arg0)); - } - + /** + * Panel that will display the messages. + */ + private MessageOutputPanel panel; + + /** + * Create a new instance and specify the panel that will receive the output. + * + * @param panel The panel. + */ + public DebugOutputStream(MessageOutputPanel panel) + { + this.panel = panel; + } + + /** + * Override the write method from OutputStream. Capture the char and + * send it to the panel. + * + * @param arg0 The output character, expressed as an integer. + * + * @see java.io.OutputStream#write(int) + */ + public void write(int arg0) throws IOException + { + panel.addCharacter(Character.valueOf((char)arg0)); + } + } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/MessageOutputPanel.java b/dspace-sword/src/main/java/org/purl/sword/client/MessageOutputPanel.java index d1bb9284b4..51145772dc 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/MessageOutputPanel.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/MessageOutputPanel.java @@ -65,79 +65,79 @@ public class MessageOutputPanel extends JPanel implements ActionListener { - /** - * The text area that displays the messages. - */ - private JTextArea messages = null; - - /** - * Create a new instance and initialise the panel. - */ - public MessageOutputPanel() - { - super(); - - setLayout(new GridBagLayout()); - - messages = new JTextArea(); - - JScrollPane detailsPane = new JScrollPane(messages, + /** + * The text area that displays the messages. + */ + private JTextArea messages = null; + + /** + * Create a new instance and initialise the panel. + */ + public MessageOutputPanel() + { + super(); + + setLayout(new GridBagLayout()); + + messages = new JTextArea(); + + JScrollPane detailsPane = new JScrollPane(messages, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - JButton clearButton = new JButton("Clear"); - clearButton.addActionListener(this); - - //add components and set constraints - //dpc = details pane constraint - GridBagConstraints dpc = new GridBagConstraints(); - dpc.gridx = 0; - dpc.gridy = 0; - dpc.fill = GridBagConstraints.BOTH; - dpc.weightx = 0.75; - dpc.weighty = 0.45; - dpc.gridwidth = 2; - dpc.insets = new Insets(5,5,5,5); - add(detailsPane,dpc); - - //cbc = clear button constraint - GridBagConstraints cbc = new GridBagConstraints(); - cbc.gridx = 1; - cbc.gridy = 1; - cbc.insets = new Insets(0,0,5,5); - cbc.anchor = GridBagConstraints.LINE_END; - add(clearButton,cbc); - - } - - /** - * Add a message to the text area. The message will be added with a carriage return. - * - * @param message The message. - */ - public void addMessage(String message) - { - messages.insert(message + "\n", messages.getDocument().getLength()); - } - - /** - * Add a single character to the text area. - * - * @param character The character. - */ - public void addCharacter(Character character) - { - messages.insert(character.toString(), messages.getDocument().getLength()); - } - - /** - * Clear the text from the display. - * - * @param arg0 The action event. - * - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent arg0) - { - messages.setText(""); - } + JButton clearButton = new JButton("Clear"); + clearButton.addActionListener(this); + + //add components and set constraints + //dpc = details pane constraint + GridBagConstraints dpc = new GridBagConstraints(); + dpc.gridx = 0; + dpc.gridy = 0; + dpc.fill = GridBagConstraints.BOTH; + dpc.weightx = 0.75; + dpc.weighty = 0.45; + dpc.gridwidth = 2; + dpc.insets = new Insets(5,5,5,5); + add(detailsPane,dpc); + + //cbc = clear button constraint + GridBagConstraints cbc = new GridBagConstraints(); + cbc.gridx = 1; + cbc.gridy = 1; + cbc.insets = new Insets(0,0,5,5); + cbc.anchor = GridBagConstraints.LINE_END; + add(clearButton,cbc); + + } + + /** + * Add a message to the text area. The message will be added with a carriage return. + * + * @param message The message. + */ + public void addMessage(String message) + { + messages.insert(message + "\n", messages.getDocument().getLength()); + } + + /** + * Add a single character to the text area. + * + * @param character The character. + */ + public void addCharacter(Character character) + { + messages.insert(character.toString(), messages.getDocument().getLength()); + } + + /** + * Clear the text from the display. + * + * @param arg0 The action event. + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) + { + messages.setText(""); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/PostDestination.java b/dspace-sword/src/main/java/org/purl/sword/client/PostDestination.java index b5f6c60b3c..ae25b818d1 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/PostDestination.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/PostDestination.java @@ -11,144 +11,144 @@ package org.purl.sword.client; * Details for a destination. This is used to represent a destination. If * expressed as a string, the destination looks like: *
    - * []:@
    + * <user>[<onBehalfOf>]:<password>@<url>
      * 
    * * @author Neil Taylor */ public class PostDestination { - /** - * URL for the post destination. - */ - private String url; - - /** - * The username. - */ - private String username; - - /** - * The password. - */ - private String password; - - /** - * The onBehalfOf ID. - */ - private String onBehalfOf; - - /** - * Create a new instance. - */ - public PostDestination() - { - // No-Op - } - - /** - * Create a new instance. - * - * @param url The url. - * @param username The username. - * @param password The password. - * @param onBehalfOf The onBehalfOf id. - */ - public PostDestination(String url, String username, String password, String onBehalfOf) - { - this.url = url; - this.username = username; - this.password = password; - this.onBehalfOf = onBehalfOf; - } - - /** - * @return the url - */ - public String getUrl() - { - return url; - } - - /** - * @param url the url to set - */ - public void setUrl(String url) - { - this.url = url; - } - - /** - * @return the username - */ - public String getUsername() - { - return username; - } - - /** - * @param username the username to set - */ - public void setUsername(String username) - { - this.username = username; - } - - /** - * @return the password - */ - public String getPassword() - { - return password; - } - - /** - * @param password the password to set - */ - public void setPassword(String password) - { - this.password = password; - } - - /** - * @return the onBehalfOf - */ - public String getOnBehalfOf() - { - return onBehalfOf; - } - - /** - * @param onBehalfOf the onBehalfOf to set - */ - public void setOnBehalfOf(String onBehalfOf) - { - this.onBehalfOf = onBehalfOf; - } - - /** - * Create a string representation of this object. - * - * @return The string. - */ - public String toString() - { - StringBuffer buffer = new StringBuffer(); - buffer.append(username); - if( onBehalfOf != null ) - { - buffer.append("["); - buffer.append(onBehalfOf); - buffer.append("]"); - } - - if( password != null ) - { - buffer.append(":******"); - } - buffer.append("@"); - buffer.append(url); - - return buffer.toString(); - } + /** + * URL for the post destination. + */ + private String url; + + /** + * The username. + */ + private String username; + + /** + * The password. + */ + private String password; + + /** + * The onBehalfOf ID. + */ + private String onBehalfOf; + + /** + * Create a new instance. + */ + public PostDestination() + { + // No-Op + } + + /** + * Create a new instance. + * + * @param url The url. + * @param username The username. + * @param password The password. + * @param onBehalfOf The onBehalfOf id. + */ + public PostDestination(String url, String username, String password, String onBehalfOf) + { + this.url = url; + this.username = username; + this.password = password; + this.onBehalfOf = onBehalfOf; + } + + /** + * @return the url + */ + public String getUrl() + { + return url; + } + + /** + * @param url the url to set + */ + public void setUrl(String url) + { + this.url = url; + } + + /** + * @return the username + */ + public String getUsername() + { + return username; + } + + /** + * @param username the username to set + */ + public void setUsername(String username) + { + this.username = username; + } + + /** + * @return the password + */ + public String getPassword() + { + return password; + } + + /** + * @param password the password to set + */ + public void setPassword(String password) + { + this.password = password; + } + + /** + * @return the onBehalfOf + */ + public String getOnBehalfOf() + { + return onBehalfOf; + } + + /** + * @param onBehalfOf the onBehalfOf to set + */ + public void setOnBehalfOf(String onBehalfOf) + { + this.onBehalfOf = onBehalfOf; + } + + /** + * Create a string representation of this object. + * + * @return The string. + */ + public String toString() + { + StringBuffer buffer = new StringBuffer(); + buffer.append(username); + if ( onBehalfOf != null ) + { + buffer.append("["); + buffer.append(onBehalfOf); + buffer.append("]"); + } + + if ( password != null ) + { + buffer.append(":******"); + } + buffer.append("@"); + buffer.append(url); + + return buffer.toString(); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/PostDialog.java b/dspace-sword/src/main/java/org/purl/sword/client/PostDialog.java index 6d5b5f92d2..f10a42c912 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/PostDialog.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/PostDialog.java @@ -70,581 +70,581 @@ import javax.swing.event.ChangeListener; public class PostDialog implements ActionListener, ChangeListener { - /** - * label for the browse command. - */ - protected static final String BROWSE = "browse"; - - /** - * label for the add command. - */ - protected static final String ADD = "add"; - - /** - * label for the edit command. - */ - protected static final String EDIT = "edit"; - - /** - * label for the delete command. - */ - protected static final String DELETE = "delete"; - - /** - * label for the clear command. - */ - protected static final String CLEAR = "clear"; - - /** - * Username combo box. - */ - private SWORDComboBox username; - - /** - * Post Location combo box. - */ - private SWORDComboBox postLocation; - - /** - * Password field. - */ - private JPasswordField password; - - /** - * The file combo box. - */ - private SWORDComboBox file; - - /** - * The filetype combo box. - */ - private SWORDComboBox fileType; - - /** - * The onBehalfOf combo box. - */ - private SWORDComboBox onBehalfOf; - - /** - * The md5 checkbox. - */ - private JCheckBox useMD5; - - /** - * The corruptMD5 checkbox. - */ - private JCheckBox corruptMD5; - - /** - * The corruptRequest checkbox. - */ - private JCheckBox corruptRequest; - - /** - * The useNoOp checkbox. - */ - private JCheckBox useNoOp; - - /** - * The verbose checkbox. - */ - private JCheckBox useVerbose; - - /** - * The format namespace combo box. - */ - private SWORDComboBox formatNamespace; - - /** - * The list of post destinations. - */ - private JList list; - - /** - * The parent frame for the dialog that is displayed. - */ - private JFrame parentFrame = null; - - /** - * Array that lists the labels for the buttons on the panel. - */ - private static Object[] options = {"Post File", "Cancel" }; - - /** - * The panel that holds the controls to show. - */ - private JPanel controls = null; - - /** - * - * @param parentFrame - */ - public PostDialog(JFrame parentFrame) - { - this.parentFrame = parentFrame; - controls = createControls(); - } - - /** - * Show the dialog with ok and cancel options. - * @return The return value from displaying JOptionPane. Either - * JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION. - */ - public int show( ) - { - int result = JOptionPane.showOptionDialog(parentFrame, - controls, - "Post Document", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.PLAIN_MESSAGE, - null, - options, - null); - - if( result == JOptionPane.OK_OPTION ) - { - // update the combo boxes with the values - username.updateList(); - file.updateList(); - fileType.updateList(); - onBehalfOf.updateList(); - formatNamespace.updateList(); - } - - return result; - } - - /** - * Create the controls for the main panel. - * - * @return The panel. - */ - protected final JPanel createControls( ) - { - file = new SWORDComboBox(); - JPanel filePanel = new JPanel(new BorderLayout()); - filePanel.add(file, BorderLayout.CENTER); - JButton browse = new JButton("Browse..."); - browse.setActionCommand(BROWSE); - browse.addActionListener(this); + /** + * label for the browse command. + */ + protected static final String BROWSE = "browse"; + + /** + * label for the add command. + */ + protected static final String ADD = "add"; + + /** + * label for the edit command. + */ + protected static final String EDIT = "edit"; + + /** + * label for the delete command. + */ + protected static final String DELETE = "delete"; + + /** + * label for the clear command. + */ + protected static final String CLEAR = "clear"; + + /** + * Username combo box. + */ + private SWORDComboBox username; + + /** + * Post Location combo box. + */ + private SWORDComboBox postLocation; + + /** + * Password field. + */ + private JPasswordField password; + + /** + * The file combo box. + */ + private SWORDComboBox file; + + /** + * The filetype combo box. + */ + private SWORDComboBox fileType; + + /** + * The onBehalfOf combo box. + */ + private SWORDComboBox onBehalfOf; + + /** + * The md5 checkbox. + */ + private JCheckBox useMD5; + + /** + * The corruptMD5 checkbox. + */ + private JCheckBox corruptMD5; + + /** + * The corruptRequest checkbox. + */ + private JCheckBox corruptRequest; + + /** + * The useNoOp checkbox. + */ + private JCheckBox useNoOp; + + /** + * The verbose checkbox. + */ + private JCheckBox useVerbose; + + /** + * The format namespace combo box. + */ + private SWORDComboBox formatNamespace; + + /** + * The list of post destinations. + */ + private JList list; + + /** + * The parent frame for the dialog that is displayed. + */ + private JFrame parentFrame = null; + + /** + * Array that lists the labels for the buttons on the panel. + */ + private static Object[] options = {"Post File", "Cancel" }; + + /** + * The panel that holds the controls to show. + */ + private JPanel controls = null; + + /** + * + * @param parentFrame the parent of this dialog. + */ + public PostDialog(JFrame parentFrame) + { + this.parentFrame = parentFrame; + controls = createControls(); + } + + /** + * Show the dialog with ok and cancel options. + * @return The return value from displaying JOptionPane. Either + * JOptionPane.OK_OPTION or JOptionPane.CANCEL_OPTION. + */ + public int show( ) + { + int result = JOptionPane.showOptionDialog(parentFrame, + controls, + "Post Document", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE, + null, + options, + null); - filePanel.add(browse, BorderLayout.SOUTH); - - fileType = new SWORDComboBox(); - String type = "application/zip"; - fileType.addItem(type); - fileType.setSelectedItem(type); - - // controls that will be used in the second dialog - postLocation = new SWORDComboBox(); - username = new SWORDComboBox(); - password = new JPasswordField(); - onBehalfOf = new SWORDComboBox(); - - - useMD5 = new JCheckBox(); - useMD5.addChangeListener(this); - corruptMD5 = new JCheckBox(); - corruptRequest = new JCheckBox(); - useNoOp = new JCheckBox(); - useVerbose = new JCheckBox(); - formatNamespace = new SWORDComboBox(); - - JLabel fileLabel = new JLabel("File:", JLabel.TRAILING); - JLabel fileTypeLabel = new JLabel("File Type:", JLabel.TRAILING); - JLabel useMD5Label = new JLabel("Use MD5:", JLabel.TRAILING); - JLabel corruptMD5Label = new JLabel("Corrupt MD5:", JLabel.TRAILING); - JLabel corruptRequestLabel = new JLabel("Corrupt Request:", JLabel.TRAILING); - //JLabel corruptMD5Label = new JLabel("Corrupt MD5:", JLabel.TRAILING); - JLabel useNoOpLabel = new JLabel("Use noOp:", JLabel.TRAILING); - JLabel useVerboseLabel = new JLabel("Use verbose:", JLabel.TRAILING); - JLabel formatNamespaceLabel = new JLabel("X-Packaging:", JLabel.TRAILING); - JLabel userAgentLabel = new JLabel("User Agent:", JLabel.TRAILING); - JLabel userAgentNameLabel = new JLabel(ClientConstants.SERVICE_NAME, JLabel.LEADING); - - SWORDFormPanel panel = new SWORDFormPanel(); - panel.addFirstRow(new JLabel("Please enter the details for the post operation")); - - JPanel destinations = createDestinationsPanel(); - - panel.addRow(new JLabel("Destinations:"), destinations); - panel.addRow(fileLabel, filePanel); - panel.addRow(fileTypeLabel, fileType); - panel.addRow(useMD5Label, useMD5); - panel.addRow(corruptMD5Label, corruptMD5); - panel.addRow(corruptRequestLabel, corruptRequest); - panel.addRow(useNoOpLabel, useNoOp); - panel.addRow(useVerboseLabel, useVerbose); - panel.addRow(formatNamespaceLabel, formatNamespace); - panel.addRow(userAgentLabel, userAgentNameLabel); - - return panel; - } - - /** - * Create the destinations panel. This contains a list and four buttons - * to operate on values in the list. - * - * @return The panel containing the controls. - */ - protected JPanel createDestinationsPanel() - { - DefaultListModel model = new DefaultListModel(); - list = new JList(model); - JScrollPane jsp = new JScrollPane(list); - - JPanel destinations = new JPanel(new BorderLayout()); - destinations.add(jsp, BorderLayout.CENTER); - JPanel destinationButtons = new JPanel(); - - JButton addButton = new JButton("Add"); - addButton.setActionCommand(ADD); - addButton.addActionListener(this); - - JButton editButton = new JButton("Edit"); - editButton.setActionCommand(EDIT); - editButton.addActionListener(this); - - JButton deleteButton = new JButton("Delete"); - deleteButton.setActionCommand(DELETE); - deleteButton.addActionListener(this); - - JButton clearButton = new JButton("Clear"); - clearButton.setActionCommand(CLEAR); - clearButton.addActionListener(this); - - destinationButtons.add(addButton); - destinationButtons.add(editButton); - destinationButtons.add(deleteButton); - destinationButtons.add(clearButton); - - destinations.add(destinationButtons, BorderLayout.SOUTH); - - return destinations; - } - - /** - * Handle the button click to select a file to upload. - */ - public void actionPerformed(ActionEvent evt) - { - String cmd = evt.getActionCommand(); - - if( BROWSE.equals(cmd) ) + if ( result == JOptionPane.OK_OPTION ) { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); - int returnVal = chooser.showOpenDialog(parentFrame); - if(returnVal == JFileChooser.APPROVE_OPTION) { - file.setSelectedItem(chooser.getSelectedFile().getAbsolutePath()); - } - } - else if( ADD.equals(cmd)) - { - PostDestination dest = showDestinationDialog(null); - if( dest != null ) - { - ((DefaultListModel)list.getModel()).addElement(dest); - } - } - else if( EDIT.equals(cmd)) - { - PostDestination dest = (PostDestination)list.getSelectedValue(); - if( dest != null ) - { - showDestinationDialog(dest); - list.repaint(); - } - } - else if( DELETE.equals(cmd)) - { - if( list.getSelectedIndex() != -1 ) - { - ((DefaultListModel)list.getModel()).removeElementAt(list.getSelectedIndex()); - } - } - else if( CLEAR.equals(cmd)) - { - ((DefaultListModel)list.getModel()).clear(); - } - } - - /** - * Show the destination dialog. This is used to enter the URL, - * username, password and onBehalfOf name for a destination. - * - * @param destination The post destination. If this is not null, the values - * in the object are used to set the current values - * in the dialog controls. - * @return The post destination value. - */ - public PostDestination showDestinationDialog( PostDestination destination ) - { - SWORDFormPanel panel = new SWORDFormPanel(); - panel.addFirstRow(new JLabel("Please enter the details for the post operation")); - - JLabel postLabel = new JLabel("Post Location:", JLabel.TRAILING); - JLabel userLabel = new JLabel("Username:", JLabel.TRAILING); - JLabel passwordLabel = new JLabel("Password:", JLabel.TRAILING); - JLabel onBehalfOfLabel = new JLabel("On Behalf Of:", JLabel.TRAILING); - - panel.addRow(postLabel, postLocation); - panel.addRow(userLabel, username); - panel.addRow(passwordLabel, password); - panel.addRow(onBehalfOfLabel, onBehalfOf); - - if( destination != null ) - { - postLocation.insertItem(destination.getUrl()); - username.insertItem(destination.getUsername()); - password.setText(destination.getPassword()); - onBehalfOf.insertItem(destination.getOnBehalfOf()); - } - else - { - String s = ""; - postLocation.insertItem(s); - //postLocation.setSelectedItem(s); - username.insertItem(s); - username.setSelectedItem(s); - password.setText(s); - onBehalfOf.insertItem(s); - onBehalfOf.setSelectedItem(s); - } - - int result = JOptionPane.showOptionDialog(null, - panel, - "Destination", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.PLAIN_MESSAGE, - null, - new String[] { "OK", "Cancel" }, - null); - - if( result == JOptionPane.OK_OPTION ) - { - postLocation.updateList(); + // update the combo boxes with the values username.updateList(); + file.updateList(); + fileType.updateList(); onBehalfOf.updateList(); - - if( destination == null ) - { - destination = new PostDestination(); - } - - destination.setUrl(postLocation.getText()); - destination.setUsername(username.getText()); - String pass = new String(password.getPassword()); - if( pass.length() > 0 ) - { - destination.setPassword(pass); - } - else - { - destination.setPassword(null); - } - - String obo = onBehalfOf.getText(); - if( obo.length() > 0 ) - { - destination.setOnBehalfOf(onBehalfOf.getText()); - } - else - { - destination.setOnBehalfOf(null); - } - + formatNamespace.updateList(); } - - return destination; - } - - /** - * Get the list of Post Destinations. - * @return The destinations. - */ - public PostDestination[] getDestinations() - { - DefaultListModel model = (DefaultListModel)list.getModel(); - PostDestination[] destinations = new PostDestination[model.size()]; - for( int i = 0; i < model.size(); i++) - { - destinations[i] = (PostDestination)model.get(i); - } - return destinations; - } - - /** - * Get the file details. - * @return The value. - */ - public String getFile( ) - { - return file.getText(); - } - - /** - * Get the filetype value. - * @return The value. - */ - public String getFileType() - { - return fileType.getText(); - } - - /** - * Get the onBehalfOf value. - * @return The value. - */ - public String getOnBehalfOf() - { - return onBehalfOf.getText(); - } - - /** - * Get the format namespace value. - * @return The value. - */ - public String getFormatNamespace() - { - return formatNamespace.getText(); - } - - /** - * Determine if the MD5 checkbox is selected. - * - * @return True if the MD5 checkbox is selected. - */ - public boolean useMd5() - { - return useMD5.isSelected(); - } - - /** - * Determine if the noOp checkbox is selected. - * - * @return True if the checkbox is selected. - */ - public boolean useNoOp() - { - return useNoOp.isSelected(); - } - - /** - * Determine if the verbose checkbox is selected. - * - * @return True if the checkbox is selected. - */ - public boolean useVerbose() - { - return useVerbose.isSelected(); - } - - /** - * Get the post location. - * @return The post location. - */ - public String getPostLocation() - { - return postLocation.getText(); - } - - /** - * Determine if the MD5 hash should be corrupted. - * @return True if the corrupt MD5 checkbox is selected. The MD5 checkbox - * must also be selected. - */ - public boolean corruptMD5() - { - return (corruptMD5.isEnabled() && corruptMD5.isSelected()); - } - - /** - * Determine if the POST request should be corrupted. - * @return True if the corrupt request checkbox is selected. - */ - public boolean corruptRequest() - { - return (corruptRequest.isSelected()); - } - - /** - * Detect a state change event for the checkbox. - * - * @param evt The event. - */ - public void stateChanged(ChangeEvent evt) - { - corruptMD5.setEnabled(useMD5.isSelected()); - } - - /** - * Add a list of user ids. - * - * @param users The user ids. - */ - public void addUserIds(String[] users) - { - username.insertItems(users); - } - - /** - * Add a list of deposit URLs. - * - * @param deposits The URLs. - */ - public void addDepositUrls(String[] deposits) - { - postLocation.insertItems(deposits); - } - - /** - * Add a list of onBehalfOf names. - * - * @param users The names. - */ - public void addOnBehalfOf(String[] users) - { - onBehalfOf.insertItems(users); - } - - /** - * Add the list of formatNamespace strings. - * - * @param namespaces list of strings. - */ - public void addFormatNamespaces(String[] namespaces) - { - formatNamespace.insertItems(namespaces); - } - - /** - * Add a list of file types. - * - * @param types The file types. - */ - public void addFileTypes(String[] types) - { - fileType.insertItems(types); - } - - /** - * Add a list of file names. - * @param files The list of files. - */ - public void addFiles(String[] files) - { - file.insertItems(files); - } - - /** - * Set the deposit location. - * - * @param location The location. - */ - public void setDepositLocation(String location) - { - postLocation.insertItem(location); - postLocation.setSelectedItem(location); - } + + return result; + } + + /** + * Create the controls for the main panel. + * + * @return The panel. + */ + protected final JPanel createControls( ) + { + file = new SWORDComboBox(); + JPanel filePanel = new JPanel(new BorderLayout()); + filePanel.add(file, BorderLayout.CENTER); + JButton browse = new JButton("Browse..."); + browse.setActionCommand(BROWSE); + browse.addActionListener(this); + + filePanel.add(browse, BorderLayout.SOUTH); + + fileType = new SWORDComboBox(); + String type = "application/zip"; + fileType.addItem(type); + fileType.setSelectedItem(type); + + // controls that will be used in the second dialog + postLocation = new SWORDComboBox(); + username = new SWORDComboBox(); + password = new JPasswordField(); + onBehalfOf = new SWORDComboBox(); + + + useMD5 = new JCheckBox(); + useMD5.addChangeListener(this); + corruptMD5 = new JCheckBox(); + corruptRequest = new JCheckBox(); + useNoOp = new JCheckBox(); + useVerbose = new JCheckBox(); + formatNamespace = new SWORDComboBox(); + + JLabel fileLabel = new JLabel("File:", JLabel.TRAILING); + JLabel fileTypeLabel = new JLabel("File Type:", JLabel.TRAILING); + JLabel useMD5Label = new JLabel("Use MD5:", JLabel.TRAILING); + JLabel corruptMD5Label = new JLabel("Corrupt MD5:", JLabel.TRAILING); + JLabel corruptRequestLabel = new JLabel("Corrupt Request:", JLabel.TRAILING); + //JLabel corruptMD5Label = new JLabel("Corrupt MD5:", JLabel.TRAILING); + JLabel useNoOpLabel = new JLabel("Use noOp:", JLabel.TRAILING); + JLabel useVerboseLabel = new JLabel("Use verbose:", JLabel.TRAILING); + JLabel formatNamespaceLabel = new JLabel("X-Packaging:", JLabel.TRAILING); + JLabel userAgentLabel = new JLabel("User Agent:", JLabel.TRAILING); + JLabel userAgentNameLabel = new JLabel(ClientConstants.SERVICE_NAME, JLabel.LEADING); + + SWORDFormPanel panel = new SWORDFormPanel(); + panel.addFirstRow(new JLabel("Please enter the details for the post operation")); + + JPanel destinations = createDestinationsPanel(); + + panel.addRow(new JLabel("Destinations:"), destinations); + panel.addRow(fileLabel, filePanel); + panel.addRow(fileTypeLabel, fileType); + panel.addRow(useMD5Label, useMD5); + panel.addRow(corruptMD5Label, corruptMD5); + panel.addRow(corruptRequestLabel, corruptRequest); + panel.addRow(useNoOpLabel, useNoOp); + panel.addRow(useVerboseLabel, useVerbose); + panel.addRow(formatNamespaceLabel, formatNamespace); + panel.addRow(userAgentLabel, userAgentNameLabel); + + return panel; + } + + /** + * Create the destinations panel. This contains a list and four buttons + * to operate on values in the list. + * + * @return The panel containing the controls. + */ + protected JPanel createDestinationsPanel() + { + DefaultListModel model = new DefaultListModel(); + list = new JList(model); + JScrollPane jsp = new JScrollPane(list); + + JPanel destinations = new JPanel(new BorderLayout()); + destinations.add(jsp, BorderLayout.CENTER); + JPanel destinationButtons = new JPanel(); + + JButton addButton = new JButton("Add"); + addButton.setActionCommand(ADD); + addButton.addActionListener(this); + + JButton editButton = new JButton("Edit"); + editButton.setActionCommand(EDIT); + editButton.addActionListener(this); + + JButton deleteButton = new JButton("Delete"); + deleteButton.setActionCommand(DELETE); + deleteButton.addActionListener(this); + + JButton clearButton = new JButton("Clear"); + clearButton.setActionCommand(CLEAR); + clearButton.addActionListener(this); + + destinationButtons.add(addButton); + destinationButtons.add(editButton); + destinationButtons.add(deleteButton); + destinationButtons.add(clearButton); + + destinations.add(destinationButtons, BorderLayout.SOUTH); + + return destinations; + } + + /** + * Handle the button click to select a file to upload. + */ + public void actionPerformed(ActionEvent evt) + { + String cmd = evt.getActionCommand(); + + if ( BROWSE.equals(cmd) ) + { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); + int returnVal = chooser.showOpenDialog(parentFrame); + if (returnVal == JFileChooser.APPROVE_OPTION) { + file.setSelectedItem(chooser.getSelectedFile().getAbsolutePath()); + } + } + else if ( ADD.equals(cmd)) + { + PostDestination dest = showDestinationDialog(null); + if ( dest != null ) + { + ((DefaultListModel)list.getModel()).addElement(dest); + } + } + else if ( EDIT.equals(cmd)) + { + PostDestination dest = (PostDestination)list.getSelectedValue(); + if ( dest != null ) + { + showDestinationDialog(dest); + list.repaint(); + } + } + else if ( DELETE.equals(cmd)) + { + if ( list.getSelectedIndex() != -1 ) + { + ((DefaultListModel)list.getModel()).removeElementAt(list.getSelectedIndex()); + } + } + else if ( CLEAR.equals(cmd)) + { + ((DefaultListModel)list.getModel()).clear(); + } + } + + /** + * Show the destination dialog. This is used to enter the URL, + * username, password and onBehalfOf name for a destination. + * + * @param destination The post destination. If this is not null, the values + * in the object are used to set the current values + * in the dialog controls. + * @return The post destination value. + */ + public PostDestination showDestinationDialog( PostDestination destination ) + { + SWORDFormPanel panel = new SWORDFormPanel(); + panel.addFirstRow(new JLabel("Please enter the details for the post operation")); + + JLabel postLabel = new JLabel("Post Location:", JLabel.TRAILING); + JLabel userLabel = new JLabel("Username:", JLabel.TRAILING); + JLabel passwordLabel = new JLabel("Password:", JLabel.TRAILING); + JLabel onBehalfOfLabel = new JLabel("On Behalf Of:", JLabel.TRAILING); + + panel.addRow(postLabel, postLocation); + panel.addRow(userLabel, username); + panel.addRow(passwordLabel, password); + panel.addRow(onBehalfOfLabel, onBehalfOf); + + if ( destination != null ) + { + postLocation.insertItem(destination.getUrl()); + username.insertItem(destination.getUsername()); + password.setText(destination.getPassword()); + onBehalfOf.insertItem(destination.getOnBehalfOf()); + } + else + { + String s = ""; + postLocation.insertItem(s); + //postLocation.setSelectedItem(s); + username.insertItem(s); + username.setSelectedItem(s); + password.setText(s); + onBehalfOf.insertItem(s); + onBehalfOf.setSelectedItem(s); + } + + int result = JOptionPane.showOptionDialog(null, + panel, + "Destination", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE, + null, + new String[] { "OK", "Cancel" }, + null); + + if ( result == JOptionPane.OK_OPTION ) + { + postLocation.updateList(); + username.updateList(); + onBehalfOf.updateList(); + + if ( destination == null ) + { + destination = new PostDestination(); + } + + destination.setUrl(postLocation.getText()); + destination.setUsername(username.getText()); + String pass = new String(password.getPassword()); + if ( pass.length() > 0 ) + { + destination.setPassword(pass); + } + else + { + destination.setPassword(null); + } + + String obo = onBehalfOf.getText(); + if ( obo.length() > 0 ) + { + destination.setOnBehalfOf(onBehalfOf.getText()); + } + else + { + destination.setOnBehalfOf(null); + } + + } + + return destination; + } + + /** + * Get the list of Post Destinations. + * @return The destinations. + */ + public PostDestination[] getDestinations() + { + DefaultListModel model = (DefaultListModel)list.getModel(); + PostDestination[] destinations = new PostDestination[model.size()]; + for ( int i = 0; i < model.size(); i++) + { + destinations[i] = (PostDestination)model.get(i); + } + return destinations; + } + + /** + * Get the file details. + * @return The value. + */ + public String getFile( ) + { + return file.getText(); + } + + /** + * Get the filetype value. + * @return The value. + */ + public String getFileType() + { + return fileType.getText(); + } + + /** + * Get the onBehalfOf value. + * @return The value. + */ + public String getOnBehalfOf() + { + return onBehalfOf.getText(); + } + + /** + * Get the format namespace value. + * @return The value. + */ + public String getFormatNamespace() + { + return formatNamespace.getText(); + } + + /** + * Determine if the MD5 checkbox is selected. + * + * @return True if the MD5 checkbox is selected. + */ + public boolean useMd5() + { + return useMD5.isSelected(); + } + + /** + * Determine if the noOp checkbox is selected. + * + * @return True if the checkbox is selected. + */ + public boolean useNoOp() + { + return useNoOp.isSelected(); + } + + /** + * Determine if the verbose checkbox is selected. + * + * @return True if the checkbox is selected. + */ + public boolean useVerbose() + { + return useVerbose.isSelected(); + } + + /** + * Get the post location. + * @return The post location. + */ + public String getPostLocation() + { + return postLocation.getText(); + } + + /** + * Determine if the MD5 hash should be corrupted. + * @return True if the corrupt MD5 checkbox is selected. The MD5 checkbox + * must also be selected. + */ + public boolean corruptMD5() + { + return (corruptMD5.isEnabled() && corruptMD5.isSelected()); + } + + /** + * Determine if the POST request should be corrupted. + * @return True if the corrupt request checkbox is selected. + */ + public boolean corruptRequest() + { + return (corruptRequest.isSelected()); + } + + /** + * Detect a state change event for the checkbox. + * + * @param evt The event. + */ + public void stateChanged(ChangeEvent evt) + { + corruptMD5.setEnabled(useMD5.isSelected()); + } + + /** + * Add a list of user ids. + * + * @param users The user ids. + */ + public void addUserIds(String[] users) + { + username.insertItems(users); + } + + /** + * Add a list of deposit URLs. + * + * @param deposits The URLs. + */ + public void addDepositUrls(String[] deposits) + { + postLocation.insertItems(deposits); + } + + /** + * Add a list of onBehalfOf names. + * + * @param users The names. + */ + public void addOnBehalfOf(String[] users) + { + onBehalfOf.insertItems(users); + } + + /** + * Add the list of formatNamespace strings. + * + * @param namespaces list of strings. + */ + public void addFormatNamespaces(String[] namespaces) + { + formatNamespace.insertItems(namespaces); + } + + /** + * Add a list of file types. + * + * @param types The file types. + */ + public void addFileTypes(String[] types) + { + fileType.insertItems(types); + } + + /** + * Add a list of file names. + * @param files The list of files. + */ + public void addFiles(String[] files) + { + file.insertItems(files); + } + + /** + * Set the deposit location. + * + * @param location The location. + */ + public void setDepositLocation(String location) + { + postLocation.insertItem(location); + postLocation.setSelectedItem(location); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/PostMessage.java b/dspace-sword/src/main/java/org/purl/sword/client/PostMessage.java index 777ca19c29..417cad0dd5 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/PostMessage.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/PostMessage.java @@ -54,312 +54,314 @@ import java.io.File; */ public class PostMessage { - /** - * The local filepath for the file to upload/deposit. - */ - private String filepath; + /** + * The local filepath for the file to upload/deposit. + */ + private String filepath; + + /** + * The URL of the destination server. + */ + private String destination; + + /** + * The filetype of the package that is to be uploaded. + */ + private String filetype; + + /** + * The string with the username if the deposit is on behalf of another user. + */ + private String onBehalfOf; + + /** + * True if an MD5 checksum should be sent with the deposit. + */ + private boolean useMD5; + + /** + * True if the deposit is a test and should not result in an actual deposit. + */ + private boolean noOp; + + /** + * True if the verbose operation is requested. + */ + private boolean verbose; + + /** + * The packaging format for the deposit. + */ + private String packaging; + + /** + * True if the deposit should simulate a checksum error. The client should check this + * field to determine if a correct MD5 checksum should be sent or whether the checksum should + * be modified so that it generates an error at the server. + */ + private boolean checksumError; + + /** + * True if the deposit should corrupt the POST header. The client should check this + * field to determine if a correct header should be sent or whether the header should + * be modified so that it generates an error at the server. + */ + private boolean corruptRequest; + + /** + * The Slug header value. + */ + private String slug; + + /** + * The user agent name + */ + private String userAgent; + + /** + * Get the filepath. + * + * @return The filepath. + */ + public String getFilepath() + { + return filepath; + } + + /** + * Get the filename. This is the last element of the filepath + * that has been set in this class. + * + * @return filename + */ + public String getFilename() + { + File file = new File(filepath); + return file.getName(); + } + + /** + * Set the filepath. + * + * @param filepath The filepath. + */ + public void setFilepath(String filepath) + { + this.filepath = filepath; + } + + /** + * Get the destination collection. + * + * @return The collection. + */ + public String getDestination() + { + return destination; + } + + /** + * Set the destination collection. + * + * @param destination The destination. + */ + public void setDestination(String destination) + { + this.destination = destination; + } + + /** + * Get the filetype. + * @return The filetype. + */ + public String getFiletype() + { + return filetype; + } + + /** + * Set the filetype. + * + * @param filetype The filetype. + */ + public void setFiletype(String filetype) + { + this.filetype = filetype; + } + + /** + * Get the onBehalfOf value. + * + * @return The value. + */ + public String getOnBehalfOf() + { + return onBehalfOf; + } + + /** + * Set the onBehalfOf value. + * + * @param onBehalfOf The value. + */ + public void setOnBehalfOf(String onBehalfOf) + { + this.onBehalfOf = onBehalfOf; + } + + /** + * Get the MD5 status. + * @return The value. + */ + public boolean isUseMD5() + { + return useMD5; + } + + /** + * Set the md5 state. + * + * @param useMD5 True if the message should use an MD5 checksum. + */ + public void setUseMD5(boolean useMD5) + { + this.useMD5 = useMD5; + } + + /** + * Get the no-op state. + * + * @return The value. + */ + public boolean isNoOp() + { + return noOp; + } + + /** + * Set the no-op state. + * + * @param noOp The no-op. + */ + public void setNoOp(boolean noOp) + { + this.noOp = noOp; + } + + /** + * Get the verbose value. + * + * @return The value. + */ + public boolean isVerbose() + { + return verbose; + } + + /** + * Set the verbose state. + * + * @param verbose True if the post message should send a + * verbose header. + */ + public void setVerbose(boolean verbose) + { + this.verbose = verbose; + } + + /** + * Get the packaging format. + * + * @return The value. + */ + public String getPackaging() + { + return packaging; + } + + /** + * Set the packaging format. + * + * @param packaging The packaging format. + */ + public void setFormatNamespace(String packaging) + { + this.packaging = packaging; + } + + /** + * Get the status of the checksum error. + * + * @return True if the client should simulate a checksum error. + */ + public boolean getChecksumError() + { + return checksumError; + } + + /** + * Set the state of the checksum error. + * + * @param checksumError True if the item should include a checksum error. + */ + public void setChecksumError(boolean checksumError) + { + this.checksumError = checksumError; + } + + /** + * Get the status of the corrupt request flag. + * + * @return True if the client should corrupt the POST header. + */ + public boolean getCorruptRequest() + { + return corruptRequest; + } + + /** + * Set the state of the corrupt request flag. + * + * @param corruptRequest True if the item should corrupt the POST header. + */ + public void setCorruptRequest(boolean corruptRequest) + { + this.corruptRequest = corruptRequest; + } + + /** + * Set the Slug value. + * + * @param slug The value. + */ + public void setSlug(String slug) + { + this.slug = slug; + } + + /** + * Get the Slug value. + * + * @return The Slug. + */ + public String getSlug() + { + return this.slug; + } - /** - * The URL of the destination server. - */ - private String destination; - - /** - * The filetype of the package that is to be uploaded. - */ - private String filetype; - - /** - * The string with the username if the deposit is on behalf of another user. - */ - private String onBehalfOf; - - /** - * True if an MD5 checksum should be sent with the deposit. - */ - private boolean useMD5; - - /** - * True if the deposit is a test and should not result in an actual deposit. - */ - private boolean noOp; - - /** - * True if the verbose operation is requested. - */ - private boolean verbose; - - /** - * The packaging format for the deposit. - */ - private String packaging; - - /** - * True if the deposit should simulate a checksum error. The client should check this - * field to determine if a correct MD5 checksum should be sent or whether the checksum should - * be modified so that it generates an error at the server. - */ - private boolean checksumError; - - /** - * True if the deposit should corrupt the POST header. The client should check this - * field to determine if a correct header should be sent or whether the header should - * be modified so that it generates an error at the server. - */ - private boolean corruptRequest; - - /** - * The Slug header value. - */ - private String slug; - - /** - * The user agent name - */ - private String userAgent; - - /** - * Get the filepath. - * - * @return The filepath. - */ - public String getFilepath() - { - return filepath; - } - - /** - * Get the filename. This is the last element of the filepath - * that has been set in this class. - */ - public String getFilename() - { - File file = new File(filepath); - return file.getName(); - } - - /** - * Set the filepath. - * - * @param filepath The filepath. - */ - public void setFilepath(String filepath) - { - this.filepath = filepath; - } - - /** - * Get the destination collection. - * - * @return The collection. - */ - public String getDestination() - { - return destination; - } - - /** - * Set the destination collection. - * - * @param destination The destination. - */ - public void setDestination(String destination) - { - this.destination = destination; - } - - /** - * Get the filetype. - * @return The filetype. - */ - public String getFiletype() - { - return filetype; - } - - /** - * Set the filetype. - * - * @param filetype The filetype. - */ - public void setFiletype(String filetype) - { - this.filetype = filetype; - } - - /** - * Get the onBehalfOf value. - * - * @return The value. - */ - public String getOnBehalfOf() - { - return onBehalfOf; - } - - /** - * Set the onBehalfOf value. - * - * @param onBehalfOf The value. - */ - public void setOnBehalfOf(String onBehalfOf) - { - this.onBehalfOf = onBehalfOf; - } - - /** - * Get the MD5 status. - * @return The value. - */ - public boolean isUseMD5() - { - return useMD5; - } - - /** - * Set the md5 state. - * - * @param useMD5 True if the message should use an MD5 checksum. - */ - public void setUseMD5(boolean useMD5) - { - this.useMD5 = useMD5; - } - - /** - * Get the no-op state. - * - * @return The value. - */ - public boolean isNoOp() - { - return noOp; - } - - /** - * Set the no-op state. - * - * @param noOp The no-op. - */ - public void setNoOp(boolean noOp) - { - this.noOp = noOp; - } - - /** - * Get the verbose value. - * - * @return The value. - */ - public boolean isVerbose() - { - return verbose; - } - - /** - * Set the verbose state. - * - * @param verbose True if the post message should send a - * verbose header. - */ - public void setVerbose(boolean verbose) - { - this.verbose = verbose; - } - - /** - * Get the packaging format. - * - * @return The value. - */ - public String getPackaging() - { - return packaging; - } - - /** - * Set the packaging format. - * - * @param packaging The packaging format. - */ - public void setFormatNamespace(String packaging) - { - this.packaging = packaging; - } - - /** - * Get the status of the checksum error. - * - * @return True if the client should simulate a checksum error. - */ - public boolean getChecksumError() - { - return checksumError; - } - - /** - * Set the state of the checksum error. - * - * @param checksumError True if the item should include a checksum error. - */ - public void setChecksumError(boolean checksumError) - { - this.checksumError = checksumError; - } - - /** - * Get the status of the corrupt request flag. - * - * @return True if the client should corrupt the POST header. - */ - public boolean getCorruptRequest() - { - return corruptRequest; - } - - /** - * Set the state of the corrupt request flag. - * - * @param corruptRequest True if the item should corrupt the POST header. - */ - public void setCorruptRequest(boolean corruptRequest) - { - this.corruptRequest = corruptRequest; - } - - /** - * Set the Slug value. - * - * @param slug The value. - */ - public void setSlug(String slug) - { - this.slug = slug; - } - - /** - * Get the Slug value. - * - * @return The Slug. - */ - public String getSlug() - { - return this.slug; - } - - /** - * @return the userAgent - */ - public String getUserAgent() { - return userAgent; - } - - /** - * Set the user agent - * - * @param userAgent the userAgent to set - */ - public void setUserAgent(String userAgent) { - this.userAgent = userAgent; - } + /** + * @return the userAgent + */ + public String getUserAgent() { + return userAgent; + } + + /** + * Set the user agent + * + * @param userAgent the userAgent to set + */ + public void setUserAgent(String userAgent) { + this.userAgent = userAgent; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/PropertiesDialog.java b/dspace-sword/src/main/java/org/purl/sword/client/PropertiesDialog.java index 1cd8b1ee74..03c5327533 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/PropertiesDialog.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/PropertiesDialog.java @@ -27,238 +27,238 @@ import javax.swing.table.TableCellEditor; */ public class PropertiesDialog { - /** - * The parent frame for the dialog that is displayed. - */ - private JFrame parentFrame = null; - - /** - * Array that lists the labels for the buttons on the panel. - */ - private static Object[] options = {"OK", "Cancel" }; - - /** - * The panel that holds the controls to show. - */ - private JPanel controls = null; - - /** - * The configuration properties - */ - private Properties properties = null; - - /** - * Table that is used to display the list of properties. - */ - private JTable propertiesTable; - - /** - * Create a new instance. - * - * @param parentFrame The parent frame for the dialog. - * @param props The properties lisst to display - */ - public PropertiesDialog(JFrame parentFrame, Properties props) - { - this.parentFrame = parentFrame; - properties = props; - controls = createControls(); - } - - /** - * Create the controls that are to be displayed in the system. - * - * @return A panel that contains the controls. - */ - protected final JPanel createControls( ) - { - JPanel panel = new JPanel(new BorderLayout()); - propertiesTable = new JTable(new PropertiesModel()); - ((DefaultCellEditor)propertiesTable.getDefaultEditor(String.class)).setClickCountToStart(1); - JScrollPane scrollpane = new JScrollPane(propertiesTable,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, - JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - panel.add(scrollpane, BorderLayout.CENTER); - return panel; - } - - - /** - * Show the dialog and return the status code. - * - * @return The status code returned from the dialog. - */ - public int show( ) - { - int result = JOptionPane.showOptionDialog(parentFrame, - controls, - "Edit Properties", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.PLAIN_MESSAGE, - null, - options, - null); - - // cancel any edit in the table. If there is a cell editing, the getEditingColumn will - // return a non-negative column number. This can be used to retreive the cell editor. - // The code then gets the default editor and calls the stopCellEditing. If custom - // editors are used, an additional check must be made to get the cell editor - // for a specific cell. - int column = propertiesTable.getEditingColumn(); - - if( column > -1 ) - { - TableCellEditor editor = propertiesTable.getDefaultEditor( propertiesTable.getColumnClass(column)); - if( editor != null ) - { - editor.stopCellEditing(); - } - } - - return result; - } - - - /** - * A table model that is used to show the properties. The model links directly - * to the underlying properties object. As changes are made in the table, the - * corresponding changes are made in the properties object. The user can only - * edit the value column in the table. - */ - public class PropertiesModel extends AbstractTableModel - { - /** - * Column names. - */ - private String columns[] = {"Property Name","Value"}; - - /** - * Create a new instance of the model. If no properties object exists, - * a default model is created. Note, this will allow the table to - * continue editing, although this value will not be passed back to - * the calling window. - */ - public PropertiesModel() - { - super(); - if(properties == null) - { - properties = new Properties(); - } - } - - /** - * Get the number of columns. - * - * @return The number of columns. - */ - public int getColumnCount() - { - return columns.length; - } - - /** - * Get the number of rows. - * - * @return The number of rows. - */ - public int getRowCount() - { - return properties.size(); - } - - /** - * Get the value that is at the specified cell. - * - * @param row The row for the cell. - * @param col The column for the cell. - * - * @return The data value from the properties. - */ - public Object getValueAt(int row, int col) - { - if(col == 0) - { - return getKeyValue(row); - } - else - { - String key = getKeyValue(row); - return properties.get(key); - } - } - - /** - * Retrieve the column name for the specified column. - * - * @param col The column number. - * - * @return The column name. - */ - public String getColumnName(int col){ - return columns[col]; - } - - /** - * Retrieve the column class. - * - * @param col The column number. - * - * @return The class for the object found at the column position. - */ - public Class getColumnClass(int col) - { + /** + * The parent frame for the dialog that is displayed. + */ + private JFrame parentFrame = null; + + /** + * Array that lists the labels for the buttons on the panel. + */ + private static Object[] options = {"OK", "Cancel" }; + + /** + * The panel that holds the controls to show. + */ + private JPanel controls = null; + + /** + * The configuration properties + */ + private Properties properties = null; + + /** + * Table that is used to display the list of properties. + */ + private JTable propertiesTable; + + /** + * Create a new instance. + * + * @param parentFrame The parent frame for the dialog. + * @param props The properties lisst to display + */ + public PropertiesDialog(JFrame parentFrame, Properties props) + { + this.parentFrame = parentFrame; + properties = props; + controls = createControls(); + } + + /** + * Create the controls that are to be displayed in the system. + * + * @return A panel that contains the controls. + */ + protected final JPanel createControls( ) + { + JPanel panel = new JPanel(new BorderLayout()); + propertiesTable = new JTable(new PropertiesModel()); + ((DefaultCellEditor)propertiesTable.getDefaultEditor(String.class)).setClickCountToStart(1); + JScrollPane scrollpane = new JScrollPane(propertiesTable,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + panel.add(scrollpane, BorderLayout.CENTER); + return panel; + } + + + /** + * Show the dialog and return the status code. + * + * @return The status code returned from the dialog. + */ + public int show( ) + { + int result = JOptionPane.showOptionDialog(parentFrame, + controls, + "Edit Properties", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE, + null, + options, + null); + + // cancel any edit in the table. If there is a cell editing, the getEditingColumn will + // return a non-negative column number. This can be used to retreive the cell editor. + // The code then gets the default editor and calls the stopCellEditing. If custom + // editors are used, an additional check must be made to get the cell editor + // for a specific cell. + int column = propertiesTable.getEditingColumn(); + + if ( column > -1 ) + { + TableCellEditor editor = propertiesTable.getDefaultEditor( propertiesTable.getColumnClass(column)); + if ( editor != null ) + { + editor.stopCellEditing(); + } + } + + return result; + } + + + /** + * A table model that is used to show the properties. The model links directly + * to the underlying properties object. As changes are made in the table, the + * corresponding changes are made in the properties object. The user can only + * edit the value column in the table. + */ + public class PropertiesModel extends AbstractTableModel + { + /** + * Column names. + */ + private String columns[] = {"Property Name","Value"}; + + /** + * Create a new instance of the model. If no properties object exists, + * a default model is created. Note, this will allow the table to + * continue editing, although this value will not be passed back to + * the calling window. + */ + public PropertiesModel() + { + super(); + if (properties == null) + { + properties = new Properties(); + } + } + + /** + * Get the number of columns. + * + * @return The number of columns. + */ + public int getColumnCount() + { + return columns.length; + } + + /** + * Get the number of rows. + * + * @return The number of rows. + */ + public int getRowCount() + { + return properties.size(); + } + + /** + * Get the value that is at the specified cell. + * + * @param row The row for the cell. + * @param col The column for the cell. + * + * @return The data value from the properties. + */ + public Object getValueAt(int row, int col) + { + if (col == 0) + { + return getKeyValue(row); + } + else + { + String key = getKeyValue(row); + return properties.get(key); + } + } + + /** + * Retrieve the column name for the specified column. + * + * @param col The column number. + * + * @return The column name. + */ + public String getColumnName(int col){ + return columns[col]; + } + + /** + * Retrieve the column class. + * + * @param col The column number. + * + * @return The class for the object found at the column position. + */ + public Class getColumnClass(int col) + { return getValueAt(0, col).getClass(); } - /** - * Determine if the cell can be edited. This model will only - * allow the second column to be edited. - * - * @param row The cell row. - * @param col The cell column. - * - * @return True if the cell can be edited. Otherwise, false. - */ - public boolean isCellEditable(int row, int col) - { - if(col == 1) - { - return true; - } - return false; - } + /** + * Determine if the cell can be edited. This model will only + * allow the second column to be edited. + * + * @param row The cell row. + * @param col The cell column. + * + * @return True if the cell can be edited. Otherwise, false. + */ + public boolean isCellEditable(int row, int col) + { + if (col == 1) + { + return true; + } + return false; + } - /** - * Set the value for the specified cell. - * - * @param value The value to set. - * @param row The row for the cell. - * @param col The column. - */ - public void setValueAt(Object value, int row, int col) - { - String key = getKeyValue(row); - properties.setProperty(key, ((String) value)); - fireTableCellUpdated(row, col); - } + /** + * Set the value for the specified cell. + * + * @param value The value to set. + * @param row The row for the cell. + * @param col The column. + */ + public void setValueAt(Object value, int row, int col) + { + String key = getKeyValue(row); + properties.setProperty(key, ((String) value)); + fireTableCellUpdated(row, col); + } - /** - * Get the Key value for the specified row. - * @param row The row. - * @return A string that shows the key value. - */ - public String getKeyValue(int row) - { - int count = 0; - Enumeration k = properties.keys(); - while (k.hasMoreElements()) { - String key = (String) k.nextElement(); - if(count == row){ - return key; - } - count++; - } - return null; - } - } + /** + * Get the Key value for the specified row. + * @param row The row. + * @return A string that shows the key value. + */ + public String getKeyValue(int row) + { + int count = 0; + Enumeration k = properties.keys(); + while (k.hasMoreElements()) { + String key = (String) k.nextElement(); + if (count == row){ + return key; + } + count++; + } + return null; + } + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/SWORDClientException.java b/dspace-sword/src/main/java/org/purl/sword/client/SWORDClientException.java index f783b51875..073678d2ab 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/SWORDClientException.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/SWORDClientException.java @@ -14,33 +14,33 @@ package org.purl.sword.client; */ public class SWORDClientException extends Exception { - /** - * Create a new exception, without a message. - */ - public SWORDClientException() - { - super(); - } - - /** - * Create a new exception with the specified message. - * - * @param message The message. - */ - public SWORDClientException( String message) - { - super(message); - } - - /** - * Create a new exception with the specified message and set - * the exception that generated this error. - * - * @param message The message. - * @param cause The original exception. - */ - public SWORDClientException( String message, Exception cause) - { - super(message, cause); - } -} \ No newline at end of file + /** + * Create a new exception, without a message. + */ + public SWORDClientException() + { + super(); + } + + /** + * Create a new exception with the specified message. + * + * @param message The message. + */ + public SWORDClientException( String message) + { + super(message); + } + + /** + * Create a new exception with the specified message and set + * the exception that generated this error. + * + * @param message The message. + * @param cause The original exception. + */ + public SWORDClientException( String message, Exception cause) + { + super(message, cause); + } +} diff --git a/dspace-sword/src/main/java/org/purl/sword/client/SWORDComboBox.java b/dspace-sword/src/main/java/org/purl/sword/client/SWORDComboBox.java index 5030f5b8f3..39117f17ba 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/SWORDComboBox.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/SWORDComboBox.java @@ -54,89 +54,87 @@ import javax.swing.JComboBox; */ public class SWORDComboBox extends JComboBox { - /** - * Create an instance of the SWORD Combo box. - */ - public SWORDComboBox() - { - super(); - setEditable(true); - } - - /** - * Update the list for the Combo box with the currently selected - * item. This will only add an item to the list if: i) the control - * is editable, ii) the selected item is not empty and iii) the - * item is not already in the list. - */ - public void updateList() - { - Object s = getSelectedItem(); - - if( ! isEditable() || s == null || (s != null && ((String)s).trim().length() == 0 ) ) - { - - // don't update with an empty item or if the combo box is not editable. - return; - } - - insertItem(s); - - } - - /** - * Insert an item into the combo box. This will only be added - * if the item is not already present in the combo box. - * - * @param newItem The item to insert. - */ - public void insertItem(Object newItem) - { - int count = getItemCount(); - - boolean found = false; - - for( int i = 0; i < count && ! found; i++ ) - { - Object item = getItemAt(i); - if( item != null && item.equals(newItem) ) - { - found = true; - } - } - - if( ! found ) - { - addItem(newItem); - } - } - - /** - * Insert multiple items into the combo box. - * - * @param items The array of items. - */ - public void insertItems(String[] items) - { - for( String item : items ) - { - insertItem(item); - } - } - - /** - * Get the text of the currently selected item in the combo box. - * @return The text. null is returned if no item - * is selected. - */ - public String getText() - { - Object o = getSelectedItem(); - if( o != null ) - { - return o.toString().trim(); - } - - return null; - } + /** + * Create an instance of the SWORD Combo box. + */ + public SWORDComboBox() + { + super(); + setEditable(true); + } + + /** + * Update the list for the Combo box with the currently selected + * item. This will only add an item to the list if: i) the control + * is editable, ii) the selected item is not empty and iii) the + * item is not already in the list. + */ + public void updateList() + { + Object s = getSelectedItem(); + + if ( ! isEditable() || s == null || (s != null && ((String)s).trim().length() == 0 ) ) + { + // don't update with an empty item or if the combo box is not editable. + return; + } + + insertItem(s); + } + + /** + * Insert an item into the combo box. This will only be added + * if the item is not already present in the combo box. + * + * @param newItem The item to insert. + */ + public void insertItem(Object newItem) + { + int count = getItemCount(); + + boolean found = false; + + for ( int i = 0; i < count && ! found; i++ ) + { + Object item = getItemAt(i); + if ( item != null && item.equals(newItem) ) + { + found = true; + } + } + + if ( ! found ) + { + addItem(newItem); + } + } + + /** + * Insert multiple items into the combo box. + * + * @param items The array of items. + */ + public void insertItems(String[] items) + { + for ( String item : items ) + { + insertItem(item); + } + } + + /** + * Get the text of the currently selected item in the combo box. + * @return The text. null is returned if no item + * is selected. + */ + public String getText() + { + Object o = getSelectedItem(); + if ( o != null ) + { + return o.toString().trim(); + } + + return null; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/SWORDFormPanel.java b/dspace-sword/src/main/java/org/purl/sword/client/SWORDFormPanel.java index d27864ee26..bfda746e93 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/SWORDFormPanel.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/SWORDFormPanel.java @@ -23,131 +23,131 @@ import javax.swing.JPanel; */ public class SWORDFormPanel extends JPanel { - /** - * Constraints used to control the layout on the panel. - */ - private GridBagConstraints labelConstraints; - - /** - * Constraints used to control the layout of the input controls on the panel. - */ - private GridBagConstraints controlConstraints; - - /** - * Index to the next row. - */ - private int rowIndex = 0; - - /** - * Insets for the top row of the label column. - */ - private Insets labelTop = new Insets(10, 10, 0, 0); - - /** - * Insets for the top row of the control column. - */ - private Insets controlTop = new Insets(10, 4, 0, 10); - - /** - * Insets for a general row in the label column. - */ - private Insets labelGeneral = new Insets(3, 10, 0, 0); - - /** - * Insets for a general row in the control column. - */ - private Insets controlGeneral = new Insets(3, 4, 0, 10); - - /** - * Create a new instance of the class. - */ - public SWORDFormPanel() - { - super(); - setLayout(new GridBagLayout()); - - labelConstraints = new GridBagConstraints(); - labelConstraints.fill = GridBagConstraints.NONE; - labelConstraints.anchor = GridBagConstraints.LINE_END; - labelConstraints.weightx = 0.1; - - controlConstraints = new GridBagConstraints(); - controlConstraints.fill = GridBagConstraints.HORIZONTAL; - controlConstraints.weightx = 0.9; - } - - /** - * Add the specified component as the first row. It will occupy two - * columns. - * - * @param one The control to add. - */ - public void addFirstRow(Component one) - { - addRow(one, null, labelTop, controlTop); - } - - /** - * Add the specified components as the first row in the form. - * @param one The label component. - * @param two The control component. - */ - public void addFirstRow(Component one, Component two) - { - addRow(one, two, labelTop, controlTop); - } - - /** - * Add a component to the general row. This will be added in the label column. - * @param one The component. - */ - public void addRow(Component one) - { - addRow(one, null); - } - - /** - * Add a component to the general row. - * @param one The component to add to the label column. - * @param two The component to add to the control column. - */ - public void addRow(Component one, Component two) - { - addRow(one, two, labelGeneral, controlGeneral); - } - - /** - * Add a row to the table. - * - * @param one The component to display in the label column. - * @param two The component to display in the control column. - * @param labels The insets for the label column. - * @param controls The insets for the controls column. - */ - protected void addRow(Component one, Component two, Insets labels, Insets controls ) - { - labelConstraints.insets = labels; - labelConstraints.gridx = 0; - labelConstraints.gridy = rowIndex; - if( two == null ) - { - labelConstraints.gridwidth = 2; - } - else - { - labelConstraints.gridwidth = 1; - } - - add(one, labelConstraints); - - if( two != null ) - { - controlConstraints.insets = controls; - controlConstraints.gridx = 1; - controlConstraints.gridy = rowIndex; - add(two, controlConstraints); - } - - rowIndex++; - } + /** + * Constraints used to control the layout on the panel. + */ + private GridBagConstraints labelConstraints; + + /** + * Constraints used to control the layout of the input controls on the panel. + */ + private GridBagConstraints controlConstraints; + + /** + * Index to the next row. + */ + private int rowIndex = 0; + + /** + * Insets for the top row of the label column. + */ + private Insets labelTop = new Insets(10, 10, 0, 0); + + /** + * Insets for the top row of the control column. + */ + private Insets controlTop = new Insets(10, 4, 0, 10); + + /** + * Insets for a general row in the label column. + */ + private Insets labelGeneral = new Insets(3, 10, 0, 0); + + /** + * Insets for a general row in the control column. + */ + private Insets controlGeneral = new Insets(3, 4, 0, 10); + + /** + * Create a new instance of the class. + */ + public SWORDFormPanel() + { + super(); + setLayout(new GridBagLayout()); + + labelConstraints = new GridBagConstraints(); + labelConstraints.fill = GridBagConstraints.NONE; + labelConstraints.anchor = GridBagConstraints.LINE_END; + labelConstraints.weightx = 0.1; + + controlConstraints = new GridBagConstraints(); + controlConstraints.fill = GridBagConstraints.HORIZONTAL; + controlConstraints.weightx = 0.9; + } + + /** + * Add the specified component as the first row. It will occupy two + * columns. + * + * @param one The control to add. + */ + public void addFirstRow(Component one) + { + addRow(one, null, labelTop, controlTop); + } + + /** + * Add the specified components as the first row in the form. + * @param one The label component. + * @param two The control component. + */ + public void addFirstRow(Component one, Component two) + { + addRow(one, two, labelTop, controlTop); + } + + /** + * Add a component to the general row. This will be added in the label column. + * @param one The component. + */ + public void addRow(Component one) + { + addRow(one, null); + } + + /** + * Add a component to the general row. + * @param one The component to add to the label column. + * @param two The component to add to the control column. + */ + public void addRow(Component one, Component two) + { + addRow(one, two, labelGeneral, controlGeneral); + } + + /** + * Add a row to the table. + * + * @param one The component to display in the label column. + * @param two The component to display in the control column. + * @param labels The insets for the label column. + * @param controls The insets for the controls column. + */ + protected void addRow(Component one, Component two, Insets labels, Insets controls ) + { + labelConstraints.insets = labels; + labelConstraints.gridx = 0; + labelConstraints.gridy = rowIndex; + if ( two == null ) + { + labelConstraints.gridwidth = 2; + } + else + { + labelConstraints.gridwidth = 1; + } + + add(one, labelConstraints); + + if ( two != null ) + { + controlConstraints.insets = controls; + controlConstraints.gridx = 1; + controlConstraints.gridy = rowIndex; + add(two, controlConstraints); + } + + rowIndex++; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/client/ServiceDialog.java b/dspace-sword/src/main/java/org/purl/sword/client/ServiceDialog.java index e107d58477..b8592224b9 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/ServiceDialog.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/ServiceDialog.java @@ -57,183 +57,183 @@ import javax.swing.JPasswordField; */ public class ServiceDialog { - /** - * The username. - */ - private SWORDComboBox username; - - /** - * The password. - */ - private JPasswordField password; - - /** - * Holds the URL for the collection. - */ - private SWORDComboBox location; - - /** - * The combo box that shows the list of onBehalfOf items. - */ - private SWORDComboBox onBehalfOf; + /** + * The username. + */ + private SWORDComboBox username; - /** - * Parent frame for the dialog. - */ - private JFrame parentFrame = null; - - /** - * The panel that holds the controls. - */ - private JPanel controls = null; - - /** - * List of buttons. - */ - private static Object[] options = {"Get Service Document", "Cancel" }; + /** + * The password. + */ + private JPasswordField password; + + /** + * Holds the URL for the collection. + */ + private SWORDComboBox location; + + /** + * The combo box that shows the list of onBehalfOf items. + */ + private SWORDComboBox onBehalfOf; + + /** + * Parent frame for the dialog. + */ + private JFrame parentFrame = null; + + /** + * The panel that holds the controls. + */ + private JPanel controls = null; + + /** + * List of buttons. + */ + private static Object[] options = {"Get Service Document", "Cancel" }; + + /** + * Create a new instance. + * + * @param parentFrame The parent frame. The dialog will be shown over the + * centre of this frame. + */ + public ServiceDialog(JFrame parentFrame) + { + this.parentFrame = parentFrame; + controls = createControls(); + } + + /** + * Show the dialog. + * + * @return The close option. This is one of the dialog options from + * JOptionPane. + */ + public int show( ) + { + int result = JOptionPane.showOptionDialog(parentFrame, + controls, + "Get Service Document", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE, + null, + options, + options[1]); + + if ( result == JOptionPane.OK_OPTION ) + { + // update the combo boxes with the values + username.updateList(); + location.updateList(); + onBehalfOf.updateList(); + } + + return result; + } + + /** + * Create the controls that are displayed in the dialog. + * + * @return The panel that contains the controls. + */ + protected final JPanel createControls( ) + { + username = new SWORDComboBox(); + username.setEditable(true); + password = new JPasswordField(); + location = new SWORDComboBox(); + location.setEditable(true); + onBehalfOf = new SWORDComboBox(); + onBehalfOf.setEditable(true); + + JLabel userLabel = new JLabel("Username:", JLabel.TRAILING); + JLabel passwordLabel = new JLabel("Password:", JLabel.TRAILING); + JLabel locationLabel = new JLabel("Location:", JLabel.TRAILING); + JLabel onBehalfOfLabel = new JLabel("On Behalf Of:", JLabel.TRAILING); + + SWORDFormPanel panel = new SWORDFormPanel(); + panel.addFirstRow(userLabel, username); + panel.addRow(passwordLabel, password); + panel.addRow(locationLabel, location); + panel.addRow(onBehalfOfLabel, onBehalfOf); + + return panel; + } + + /** + * Get the username from the controls on the dialog. + * + * @return The username. + */ + public String getUsername() + { + return username.getText(); + } + + /** + * Get the password from the dialog. + * + * @return The password. + */ + public String getPassword() + { + return new String(password.getPassword()); + } + + /** + * The location from the dialog. + * + * @return The location. + */ + public String getLocation() + { + return location.getText(); + } + + /** + * The onBehalfOf value from the dialog. + * + * @return The onBehalfOf value. + */ + public String getOnBehalfOf() + { + String text = onBehalfOf.getText().trim(); + if ( text.length() == 0 ) + { + return null; + } + return text; + } + + /** + * Add the list of user ids to the dialog. + * + * @param users The list of user ids. + */ + public void addUserIds(String[] users) + { + username.insertItems(users); + } + + /** + * Add the list of service URLs. + * + * @param services The service URLs. + */ + public void addServiceUrls(String[] services) + { + location.insertItems(services); + } + + /** + * Add a list of onBehalfOf names. + * + * @param users The list of onBehalfOf items. + */ + public void addOnBehalfOf(String[] users) + { + onBehalfOf.insertItems(users); + } - /** - * Create a new instance. - * - * @param parentFrame The parent frame. The dialog will be shown over the - * centre of this frame. - */ - public ServiceDialog(JFrame parentFrame) - { - this.parentFrame = parentFrame; - controls = createControls(); - } - - /** - * Show the dialog. - * - * @return The close option. This is one of the dialog options from - * JOptionPane. - */ - public int show( ) - { - int result = JOptionPane.showOptionDialog(parentFrame, - controls, - "Get Service Document", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.PLAIN_MESSAGE, - null, - options, - options[1]); - - if( result == JOptionPane.OK_OPTION ) - { - // update the combo boxes with the values - username.updateList(); - location.updateList(); - onBehalfOf.updateList(); - } - - return result; - } - - /** - * Create the controls that are displayed in the dialog. - * - * @return The panel that contains the controls. - */ - protected final JPanel createControls( ) - { - username = new SWORDComboBox(); - username.setEditable(true); - password = new JPasswordField(); - location = new SWORDComboBox(); - location.setEditable(true); - onBehalfOf = new SWORDComboBox(); - onBehalfOf.setEditable(true); - - JLabel userLabel = new JLabel("Username:", JLabel.TRAILING); - JLabel passwordLabel = new JLabel("Password:", JLabel.TRAILING); - JLabel locationLabel = new JLabel("Location:", JLabel.TRAILING); - JLabel onBehalfOfLabel = new JLabel("On Behalf Of:", JLabel.TRAILING); - - SWORDFormPanel panel = new SWORDFormPanel(); - panel.addFirstRow(userLabel, username); - panel.addRow(passwordLabel, password); - panel.addRow(locationLabel, location); - panel.addRow(onBehalfOfLabel, onBehalfOf); - - return panel; - } - - /** - * Get the username from the controls on the dialog. - * - * @return The username. - */ - public String getUsername() - { - return username.getText(); - } - - /** - * Get the password from the dialog. - * - * @return The password. - */ - public String getPassword() - { - return new String(password.getPassword()); - } - - /** - * The location from the dialog. - * - * @return The location. - */ - public String getLocation() - { - return location.getText(); - } - - /** - * The onBehalfOf value from the dialog. - * - * @return The onBehalfOf value. - */ - public String getOnBehalfOf() - { - String text = onBehalfOf.getText().trim(); - if( text.length() == 0 ) - { - return null; - } - return text; - } - - /** - * Add the list of user ids to the dialog. - * - * @param users The list of user ids. - */ - public void addUserIds(String[] users) - { - username.insertItems(users); - } - - /** - * Add the list of service URLs. - * - * @param services The service URLs. - */ - public void addServiceUrls(String[] services) - { - location.insertItems(services); - } - - /** - * Add a list of onBehalfOf names. - * - * @param users The list of onBehalfOf items. - */ - public void addOnBehalfOf(String[] users) - { - onBehalfOf.insertItems(users); - } - -} \ No newline at end of file +} diff --git a/dspace-sword/src/main/java/org/purl/sword/client/ServicePanel.java b/dspace-sword/src/main/java/org/purl/sword/client/ServicePanel.java index db53c68745..8ac00c7a80 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/ServicePanel.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/ServicePanel.java @@ -86,849 +86,850 @@ import org.purl.sword.base.SwordAcceptPackaging; public class ServicePanel extends JPanel implements TreeSelectionListener { - /** - * The top level item in the tree that lists services. - */ - DefaultMutableTreeNode top; - - /** - * The tree model used to display the items. - */ - DefaultTreeModel treeModel = null; - - /** - * Tree that holds the list of services. - */ - private JTree services; - - /** - * The panel that shows an HTML table with any details for the selected - * node in the services tree. - */ - private JEditorPane details; - - /** - * A registered listener. This listener will be notified when there is a - * different node selected in the service tree. - */ - private ServiceSelectedListener listener; - - /** - * Create a new instance of the panel. - */ - public ServicePanel() - { - super(); - setLayout(new BorderLayout()); - - top = new DefaultMutableTreeNode("Services & Posted Files"); - treeModel = new DefaultTreeModel(top); - - services = new JTree(treeModel); - services.setCellRenderer(new ServicePostTreeRenderer()); - - JScrollPane servicesPane = new JScrollPane(services, + /** + * The top level item in the tree that lists services. + */ + DefaultMutableTreeNode top; + + /** + * The tree model used to display the items. + */ + DefaultTreeModel treeModel = null; + + /** + * Tree that holds the list of services. + */ + private JTree services; + + /** + * The panel that shows an HTML table with any details for the selected + * node in the services tree. + */ + private JEditorPane details; + + /** + * A registered listener. This listener will be notified when there is a + * different node selected in the service tree. + */ + private ServiceSelectedListener listener; + + /** + * Create a new instance of the panel. + */ + public ServicePanel() + { + super(); + setLayout(new BorderLayout()); + + top = new DefaultMutableTreeNode("Services & Posted Files"); + treeModel = new DefaultTreeModel(top); + + services = new JTree(treeModel); + services.setCellRenderer(new ServicePostTreeRenderer()); + + JScrollPane servicesPane = new JScrollPane(services, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - - details = new JEditorPane("text/html", "

    Details

    This panel will show the details for the currently selected item in the tree.

    "); - - JScrollPane detailsPane = new JScrollPane(details, + + details = new JEditorPane("text/html", + "

    Details

    This panel will show the details for the currently selected item in the tree.

    "); + + JScrollPane detailsPane = new JScrollPane(details, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - - JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, + + JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, servicesPane, detailsPane); - splitPane.setOneTouchExpandable(true); - splitPane.setResizeWeight(0.5); - splitPane.setDividerLocation(200); - - services.addTreeSelectionListener(this); - ToolTipManager.sharedInstance().registerComponent(services); - - add(splitPane, BorderLayout.CENTER); - } - - /** - * Renderer that displays the icons for the tree nodes. - * - * @author Neil Taylor - */ - static class ServicePostTreeRenderer extends DefaultTreeCellRenderer - { - Icon workspaceIcon; - Icon serviceIcon; - Icon collectionIcon; - Icon fileIcon; - - /** - * Initialise the renderer. Load the icons. - */ - public ServicePostTreeRenderer() - { - ClassLoader loader = this.getClass().getClassLoader(); - workspaceIcon = new ImageIcon(loader.getResource("images/WorkspaceNodeImage.gif")); - serviceIcon = new ImageIcon(loader.getResource("images/ServiceNodeImage.gif")); - collectionIcon = new ImageIcon(loader.getResource("images/CollectionNodeImage.gif")); - fileIcon = new ImageIcon(loader.getResource("images/ServiceNodeImage.gif")); - } - - /** - * Return the cell renderer. This will be the default tree cell renderer - * with a different icon depending upon the type of data in the node. - * - * @param tree The JTree control. - * @param value The value to display. - * @param sel True if the node is selected. - * @param expanded True if the node is expanded. - * @param leaf True if the node is a leaf. - * @param row The row. - * @param hasFocus True if the node has focus. - */ - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean sel, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - - JComponent comp = (JComponent)super.getTreeCellRendererComponent( - tree, value, sel, - expanded, leaf, row, - hasFocus); - - DefaultMutableTreeNode node = - (DefaultMutableTreeNode)value; - - Object o = node.getUserObject(); - if( o instanceof TreeNodeWrapper ) - { - TreeNodeWrapper wrapper = (TreeNodeWrapper)o; - comp.setToolTipText(wrapper.toString()); - Object data = wrapper.getData(); - if( data instanceof Service ) - { - setIcon(serviceIcon); - } - else if( data instanceof Workspace ) - { - setIcon(workspaceIcon); - } - else if( data instanceof Collection ) - { - setIcon(collectionIcon); - } - else if( data instanceof SWORDEntry ) - { - setIcon(fileIcon); - } - } - else - { - comp.setToolTipText(null); - } - return comp; + splitPane.setOneTouchExpandable(true); + splitPane.setResizeWeight(0.5); + splitPane.setDividerLocation(200); + + services.addTreeSelectionListener(this); + ToolTipManager.sharedInstance().registerComponent(services); + + add(splitPane, BorderLayout.CENTER); + } + + /** + * Renderer that displays the icons for the tree nodes. + * + * @author Neil Taylor + */ + static class ServicePostTreeRenderer extends DefaultTreeCellRenderer + { + Icon workspaceIcon; + Icon serviceIcon; + Icon collectionIcon; + Icon fileIcon; + + /** + * Initialise the renderer. Load the icons. + */ + public ServicePostTreeRenderer() + { + ClassLoader loader = this.getClass().getClassLoader(); + workspaceIcon = new ImageIcon(loader.getResource("images/WorkspaceNodeImage.gif")); + serviceIcon = new ImageIcon(loader.getResource("images/ServiceNodeImage.gif")); + collectionIcon = new ImageIcon(loader.getResource("images/CollectionNodeImage.gif")); + fileIcon = new ImageIcon(loader.getResource("images/ServiceNodeImage.gif")); } - - - } - - /** - * Set the service selected listener. This listener will be notified when - * there is a selection change in the tree. - * - * @param listener The listener. - */ - public void setServiceSelectedListener(ServiceSelectedListener listener) - { - this.listener = listener; + + /** + * Return the cell renderer. This will be the default tree cell renderer + * with a different icon depending upon the type of data in the node. + * + * @param tree The JTree control. + * @param value The value to display. + * @param sel True if the node is selected. + * @param expanded True if the node is expanded. + * @param leaf True if the node is a leaf. + * @param row The row. + * @param hasFocus True if the node has focus. + */ + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean sel, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + + JComponent comp = (JComponent)super.getTreeCellRendererComponent( + tree, value, sel, + expanded, leaf, row, + hasFocus); + + DefaultMutableTreeNode node = + (DefaultMutableTreeNode)value; + + Object o = node.getUserObject(); + if ( o instanceof TreeNodeWrapper ) + { + TreeNodeWrapper wrapper = (TreeNodeWrapper)o; + comp.setToolTipText(wrapper.toString()); + Object data = wrapper.getData(); + if ( data instanceof Service ) + { + setIcon(serviceIcon); + } + else if ( data instanceof Workspace ) + { + setIcon(workspaceIcon); + } + else if ( data instanceof Collection ) + { + setIcon(collectionIcon); + } + else if ( data instanceof SWORDEntry ) + { + setIcon(fileIcon); + } + } + else + { + comp.setToolTipText(null); + } + return comp; + } + + } - - /** - * Process the specified service document. Add the details as a new child of the - * root of the tree. - * - * @param url The url used to access the service document. - * @param doc The service document. - */ - public void processServiceDocument(String url, - ServiceDocument doc) - { - TreeNodeWrapper wrapper = null; - - Service service = doc.getService(); - wrapper = new TreeNodeWrapper(url, service); - DefaultMutableTreeNode serviceNode = new DefaultMutableTreeNode(wrapper); - treeModel.insertNodeInto(serviceNode, top, top.getChildCount()); - services.scrollPathToVisible(new TreePath(serviceNode.getPath())); - - // process the workspaces - DefaultMutableTreeNode workspaceNode = null; - - Iterator workspaces = service.getWorkspaces(); - for (; workspaces.hasNext();) - { - Workspace workspace = workspaces.next(); - wrapper = new TreeNodeWrapper(workspace.getTitle(), workspace); - workspaceNode = new DefaultMutableTreeNode(wrapper); - treeModel.insertNodeInto(workspaceNode, serviceNode, serviceNode.getChildCount()); - services.scrollPathToVisible(new TreePath(workspaceNode.getPath())); - - DefaultMutableTreeNode collectionNode = null; - Iterator collections = workspace.collectionIterator(); - for (; collections.hasNext();) - { - Collection collection = collections.next(); - wrapper = new TreeNodeWrapper(collection.getTitle(), collection); - collectionNode = new DefaultMutableTreeNode(wrapper); - treeModel.insertNodeInto(collectionNode, workspaceNode, workspaceNode.getChildCount()); - services.scrollPathToVisible(new TreePath(collectionNode.getPath())); - } - } // for - } - - /** - * Holds the data for a tree node. It specifies the name that will be displayed - * in the node, and stores associated data. - * - * @author Neil Taylor - */ - static class TreeNodeWrapper - { - /** - * The node name. - */ - private String name; - - /** - * The user data. - */ - private Object userObject; - - /** - * Create a new instance. - * - * @param name The name of the node. - * @param data The data in the node. - */ - public TreeNodeWrapper(String name, Object data) - { - this.name = name; - this.userObject = data; - } - - /** - * Retrieve the data that is stored in this node. - * - * @return The data. - */ - public Object getData() - { - return userObject; - } - - /** - * Get a string description for this node. - */ - public String toString() - { - if( name == null || name.trim().equals("") ) - { - return "Unspecified"; - } - - return name; - } - } - - /** - * Respond to a changed tree selection event. Update the details panel to - * show an appropriate message for the newly selected node. Also, - * alert the selection listener for this panel. The listener will receive - * a path, if a collection has been selected. Otherwise, the listener - * will receive null. - */ - public void valueChanged(TreeSelectionEvent evt) - { - // Get all nodes whose selection status has changed - TreePath[] paths = evt.getPaths(); - - for (int i=0; i workspaces = service.getWorkspaces(); + for (; workspaces.hasNext();) + { + Workspace workspace = workspaces.next(); + wrapper = new TreeNodeWrapper(workspace.getTitle(), workspace); + workspaceNode = new DefaultMutableTreeNode(wrapper); + treeModel.insertNodeInto(workspaceNode, serviceNode, serviceNode.getChildCount()); + services.scrollPathToVisible(new TreePath(workspaceNode.getPath())); + + DefaultMutableTreeNode collectionNode = null; + Iterator collections = workspace.collectionIterator(); + for ( ; collections.hasNext(); ) { - try - { - TreeNodeWrapper wrapper = (TreeNodeWrapper)o; - Object data = wrapper.getData(); - if( data instanceof Service ) - { - showService((Service)data); - alertListener(null); - } - else if( data instanceof Workspace ) - { - showWorkspace((Workspace)data); - if( listener != null ) - { - alertListener(null); - } - } - else if( data instanceof Collection ) - { - Collection c = (Collection)data; - showCollection(c); - alertListener(c.getLocation()); - } - else if( data instanceof SWORDEntry ) - { - showEntry((SWORDEntry)data); - alertListener(null); - } - else - { - details.setText("unknown"); - alertListener(null); - } - } - catch( Exception e ) - { - details.setText("An error occurred. The message was: " + e.getMessage() + ""); - alertListener(null); - e.printStackTrace(); - } + Collection collection = collections.next(); + wrapper = new TreeNodeWrapper(collection.getTitle(), collection); + collectionNode = new DefaultMutableTreeNode(wrapper); + treeModel.insertNodeInto(collectionNode, workspaceNode, workspaceNode.getChildCount()); + services.scrollPathToVisible(new TreePath(collectionNode.getPath())); + } + } // for + } + + /** + * Holds the data for a tree node. It specifies the name that will be displayed + * in the node, and stores associated data. + * + * @author Neil Taylor + */ + static class TreeNodeWrapper + { + /** + * The node name. + */ + private String name; + + /** + * The user data. + */ + private Object userObject; + + /** + * Create a new instance. + * + * @param name The name of the node. + * @param data The data in the node. + */ + public TreeNodeWrapper(String name, Object data) + { + this.name = name; + this.userObject = data; + } + + /** + * Retrieve the data that is stored in this node. + * + * @return The data. + */ + public Object getData() + { + return userObject; + } + + /** + * Get a string description for this node. + */ + public String toString() + { + if ( name == null || name.trim().equals("") ) + { + return "Unspecified"; + } + + return name; + } + } + + /** + * Respond to a changed tree selection event. Update the details panel to + * show an appropriate message for the newly selected node. Also, + * alert the selection listener for this panel. The listener will receive + * a path, if a collection has been selected. Otherwise, the listener + * will receive null. + */ + public void valueChanged(TreeSelectionEvent evt) + { + // Get all nodes whose selection status has changed + TreePath[] paths = evt.getPaths(); + + for (int i=0; iunknown"); + alertListener(null); + } + } + catch ( Exception e ) + { + details.setText("An error occurred. The message was: " + e.getMessage() + ""); + alertListener(null); + e.printStackTrace(); + } + } + else + { + details.setText("please select one of the other nodes"); + alertListener(null); + } + } + + } + } + + /** + * Notify the listener that there has been a change to the currently selected + * item in the tree. + * + * @param value The value to send to the listener. + */ + private void alertListener(String value) + { + if ( listener != null ) + { + listener.selected(value); + } + } + + /** + * Add a new HTML table row to the specified StringBuffer. The label is displayed in + * the left column and the value is displayed in the right column. + * + * @param buffer The destination string buffer. + * @param label The label to add. + * @param value The corresponding value to add. + */ + private void addTableRow(StringBuffer buffer, String label, Object value) + { + buffer.append(""); + buffer.append(label); + buffer.append(""); + buffer.append(displayableValue(value)); + buffer.append(""); + } + + /** + * Show the specified service data in the details panel. + * + * @param service The service node to display. + */ + private void showService(Service service) + { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + + buffer.append(""); + buffer.append(""); + addTableRow(buffer, "SWORD Version", service.getVersion()); + addTableRow(buffer, "NoOp Support ", service.isNoOp()); + addTableRow(buffer, "Verbose Support ", service.isVerbose()); + + String maxSize = ""; + + // Commented out the following code as the client code is out of step with the + // Sword 'base' library and wont compile. - Robin Taylor. + //if ( service.maxUploadIsDefined() ) + //{ + // maxSize = "" + service.getMaxUploadSize() + "kB"; + //} + //else + //{ + maxSize = "undefined"; + //} + + addTableRow(buffer, "Max File Upload Size ", maxSize); + + buffer.append("
    Service Summary
    "); + + buffer.append(""); + buffer.append(""); + details.setText(buffer.toString()); + } + + /** + * Display the workspace data in the details panel. + * + * @param workspace The workspace. + */ + private void showWorkspace(Workspace workspace) + { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + + buffer.append(""); + buffer.append(""); + addTableRow(buffer, "Workspace Title", workspace.getTitle()); + buffer.append("
    Workspace Summary
    "); + + buffer.append(""); + buffer.append(""); + details.setText(buffer.toString()); + } + + /** + * Return the parameter unmodified if set, or the not defined text if null + * @param s + * @return s or ClientConstants.NOT_DEFINED_TEXT + */ + private Object displayableValue(Object s) + { + if (null == s) + { + return ClientConstants.NOT_DEFINED_TEXT; + } else { + return s; + } + } + + /** + * Add a string within paragraph tags. + * + * @param buffer The buffer to add the message to. + * @param message The message to add. + */ + private void addPara(StringBuffer buffer, String message) + { + buffer.append("

    " + message + "

    "); + } + + /** + * Show the specified collection data in the details panel. + * + * @param collection The collection data. + */ + private void showCollection(Collection collection) + { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + + if ( collection == null ) + { + addPara(buffer, "Invalid Collection object. Unable to display details."); + } + else + { + buffer.append(""); + buffer.append(""); + addTableRow(buffer, "Collection location", collection.getLocation()); + addTableRow(buffer, "Collection title", collection.getTitle()); + addTableRow(buffer, "Abstract", collection.getAbstract()); + addTableRow(buffer, "Collection Policy", collection.getCollectionPolicy()); + addTableRow(buffer, "Treatment", collection.getTreatment()); + addTableRow(buffer, "Mediation", collection.getMediation()); + addTableRow(buffer, "Nested Service Document", collection.getService()); + + String[] accepts = collection.getAccepts(); + StringBuilder acceptList = new StringBuilder(); + if ( accepts != null && accepts.length == 0 ) + { + acceptList.append("None specified"); } else { - details.setText("please select one of the other nodes"); - alertListener(null); + for (String s : accepts) + { + acceptList.append(s).append("
    "); + } } - } - - } - } - - /** - * Notify the listener that there has been a change to the currently selected - * item in the tree. - * - * @param value The value to send to the listener. - */ - private void alertListener(String value) - { - if( listener != null ) - { - listener.selected(value); - } - } - - /** - * Add a new HTML table row to the specified StringBuffer. The label is displayed in - * the left column and the value is displayed in the right column. - * - * @param buffer The destination string buffer. - * @param label The label to add. - * @param value The corresponding value to add. - */ - private void addTableRow(StringBuffer buffer, String label, Object value) - { - buffer.append(""); - } - - /** - * Show the specified service data in the details panel. - * - * @param service The service node to display. - */ - private void showService(Service service) - { - StringBuffer buffer = new StringBuffer(); - buffer.append(""); - buffer.append(""); - - buffer.append("
    Collection Summary
    "); - buffer.append(label); - buffer.append(""); - buffer.append(displayableValue(value)); - buffer.append("
    "); - buffer.append(""); - addTableRow(buffer, "SWORD Version", service.getVersion()); - addTableRow(buffer, "NoOp Support ", service.isNoOp()); - addTableRow(buffer, "Verbose Support ", service.isVerbose()); - - String maxSize = ""; - - // Commented out the following code as the client code is out of step with the - // Sword 'base' library and wont compile. - Robin Taylor. - //if( service.maxUploadIsDefined() ) - //{ - // maxSize = "" + service.getMaxUploadSize() + "kB"; - //} - //else - //{ - maxSize = "undefined"; - //} - - addTableRow(buffer, "Max File Upload Size ", maxSize); - - buffer.append("
    Service Summary
    "); - - buffer.append(""); - buffer.append(""); - details.setText(buffer.toString()); - } - - /** - * Display the workspace data in the details panel. - * - * @param workspace The workspace. - */ - private void showWorkspace(Workspace workspace) - { - StringBuffer buffer = new StringBuffer(); - buffer.append(""); - buffer.append(""); - - buffer.append(""); - buffer.append(""); - addTableRow(buffer, "Workspace Title", workspace.getTitle()); - buffer.append("
    Workspace Summary
    "); - - buffer.append(""); - buffer.append(""); - details.setText(buffer.toString()); - } - - /** - * Return the parameter unmodified if set, or the not defined text if null - * @param s - * @return s or ClientConstants.NOT_DEFINED_TEXT - */ - private Object displayableValue(Object s) - { - if (null == s) + addTableRow(buffer, "Accepts", acceptList.toString()); + + List acceptsPackaging = collection.getAcceptPackaging(); + + StringBuilder acceptPackagingList = new StringBuilder(); + for (Iterator i = acceptsPackaging.iterator(); i.hasNext();) { + SwordAcceptPackaging accept = (SwordAcceptPackaging) i.next(); + acceptPackagingList.append(accept.getContent()).append(" (").append(accept.getQualityValue()).append(")"); + + // add a , separator if there are any more items in the list + if ( i.hasNext() ) { + acceptPackagingList.append(", "); + } + } + + addTableRow(buffer, "Accepts Packaging", acceptPackagingList.toString()); + + buffer.append(""); + } + + buffer.append(""); + buffer.append(""); + details.setText(buffer.toString()); + } + + /** + * Display the contents of a Post entry in the display panel. + * + * @param entry The entry to display. + */ + private void showEntry(SWORDEntry entry) + { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + + if ( entry == null ) { - return ClientConstants.NOT_DEFINED_TEXT; - }else{ - return s; + addPara(buffer, "Invalid Entry object. Unable to display details."); } - } - - /** - * Add a string within paragraph tags. - * - * @param buffer The buffer to add the message to. - * @param message The message to add. - */ - private void addPara(StringBuffer buffer, String message) - { - buffer.append("

    " + message + "

    "); - } - - /** - * Show the specified collection data in the details panel. - * - * @param collection The collection data. - */ - private void showCollection(Collection collection) - { - StringBuffer buffer = new StringBuffer(); - buffer.append(""); - buffer.append(""); - - if( collection == null ) - { - addPara(buffer, "Invalid Collection object. Unable to display details."); - } - else - { - buffer.append(""); - buffer.append(""); - addTableRow(buffer, "Collection location", collection.getLocation()); - addTableRow(buffer, "Collection title", collection.getTitle()); - addTableRow(buffer, "Abstract", collection.getAbstract()); - addTableRow(buffer, "Collection Policy", collection.getCollectionPolicy()); - addTableRow(buffer, "Treatment", collection.getTreatment()); - addTableRow(buffer, "Mediation", collection.getMediation()); - addTableRow(buffer, "Nested Service Document", collection.getService()); - - String[] accepts = collection.getAccepts(); - StringBuilder acceptList = new StringBuilder(); - if( accepts != null && accepts.length == 0 ) - { - acceptList.append("None specified"); - } - else - { - for (String s : accepts) + else + { + buffer.append("
    Collection Summary
    "); + buffer.append(""); + + // process atom:title + String titleString = getTextConstructDetails(entry.getSummary()); + addTableRow(buffer, "Title", titleString); + + // process id + addTableRow(buffer, "ID", entry.getId()); + + // process updated + addTableRow(buffer, "Date Updated", entry.getUpdated()); + + String authorString = getAuthorDetails(entry.getAuthors()); + addTableRow(buffer, "Authors", authorString); + + // process summary + String summaryString = getTextConstructDetails(entry.getSummary()); + addTableRow(buffer, "Summary", summaryString); + + // process content + Content content = entry.getContent(); + String contentString = ""; + if ( content == null ) + { + contentString = "Not defined."; + } + else + { + contentString += "Source: '" + content.getSource() + "', Type: '" + + content.getType() + "'"; + } + addTableRow(buffer, "Content", contentString); + + // process links + Iterator links = entry.getLinks(); + StringBuffer linkBuffer = new StringBuffer(); + for ( ; links.hasNext(); ) + { + Link link = links.next(); + linkBuffer.append("href: '"); + linkBuffer.append(link.getHref()); + linkBuffer.append("', href lang: '"); + linkBuffer.append(link.getHreflang()); + linkBuffer.append("', rel: '"); + linkBuffer.append(link.getRel()); + linkBuffer.append("')
    "); + } + if ( linkBuffer.length() == 0 ) + { + linkBuffer.append("Not defined"); + } + addTableRow(buffer, "Links", linkBuffer.toString()); + + // process contributors + String contributorString = getContributorDetails(entry.getContributors()); + addTableRow(buffer, "Contributors", contributorString); + + // process source + String sourceString=""; + Generator generator = entry.getGenerator(); + if ( generator != null ) + { + sourceString += "Content: '" + generator.getContent() + "'
    '"; + sourceString += "Version: '" + generator.getVersion() + "'
    '"; + sourceString += "Uri: '" + generator.getUri() + "'"; + } + else + { + sourceString += "No generator defined."; + } + + addTableRow(buffer, "Generator", sourceString); + + // process treatment + addTableRow(buffer, "Treatment", entry.getTreatment()); + + // process verboseDescription + addTableRow(buffer, "Verbose Description", entry.getVerboseDescription()); + + // process noOp + addTableRow(buffer, "NoOp", entry.isNoOp()); + + // process formatNamespace + addTableRow(buffer, "Packaging", entry.getPackaging()); + + // process userAgent + addTableRow(buffer, "User Agent", entry.getUserAgent()); + + + buffer.append("
    Entry Summary
    "); + } + + buffer.append(""); + buffer.append(""); + details.setText(buffer.toString()); + } + + /** + * Retrieve the details for a TextConstruct object. + * + * @param data The text construct object to display. + * + * @return Either 'Not defined' if the data is null, or + * details of the text content element. + */ + private String getTextConstructDetails(TextConstruct data) + { + String summaryStr = ""; + if ( data == null ) + { + summaryStr = "Not defined"; + } + else + { + summaryStr = "Content: '" + data.getContent() + "', Type: "; + if ( data.getType() != null ) { - acceptList.append(s).append("
    "); + summaryStr += "'" + data.getType().toString() + "'"; } - } - addTableRow(buffer, "Accepts", acceptList.toString()); - - List acceptsPackaging = collection.getAcceptPackaging(); - - StringBuilder acceptPackagingList = new StringBuilder(); - for (Iterator i = acceptsPackaging.iterator(); i.hasNext();) { - SwordAcceptPackaging accept = (SwordAcceptPackaging) i.next(); - acceptPackagingList.append(accept.getContent()).append(" (").append(accept.getQualityValue()).append(")"); - - // add a , separator if there are any more items in the list - if( i.hasNext() ) { - acceptPackagingList.append(", "); - } - } - - addTableRow(buffer, "Accepts Packaging", acceptPackagingList.toString()); - - buffer.append(""); - } - - buffer.append(""); - buffer.append(""); - details.setText(buffer.toString()); - } - - /** - * Display the contents of a Post entry in the display panel. - * - * @param entry The entry to display. - */ - private void showEntry(SWORDEntry entry) - { - StringBuffer buffer = new StringBuffer(); - buffer.append(""); - buffer.append(""); - - if( entry == null ) - { - addPara(buffer, "Invalid Entry object. Unable to display details."); - } - else - { - buffer.append(""); - buffer.append(""); - - // process atom:title - String titleString = getTextConstructDetails(entry.getSummary()); - addTableRow(buffer, "Title", titleString); - - // process id - addTableRow(buffer, "ID", entry.getId()); - - // process updated - addTableRow(buffer, "Date Updated", entry.getUpdated()); - - String authorString = getAuthorDetails(entry.getAuthors()); - addTableRow(buffer, "Authors", authorString); - - // process summary - String summaryString = getTextConstructDetails(entry.getSummary()); - addTableRow(buffer, "Summary", summaryString); - - // process content - Content content = entry.getContent(); - String contentString = ""; - if( content == null ) - { - contentString = "Not defined."; - } - else - { - contentString += "Source: '" + content.getSource() + "', Type: '" + - content.getType() + "'"; - } - addTableRow(buffer, "Content", contentString); - - // process links - Iterator links = entry.getLinks(); - StringBuffer linkBuffer = new StringBuffer(); - for( ; links.hasNext(); ) - { - Link link = links.next(); - linkBuffer.append("href: '"); - linkBuffer.append(link.getHref()); - linkBuffer.append("', href lang: '"); - linkBuffer.append(link.getHreflang()); - linkBuffer.append("', rel: '"); - linkBuffer.append(link.getRel()); - linkBuffer.append("')
    "); - } - if( linkBuffer.length() == 0 ) - { - linkBuffer.append("Not defined"); - } - addTableRow(buffer, "Links", linkBuffer.toString()); - - // process contributors - String contributorString = getContributorDetails(entry.getContributors()); - addTableRow(buffer, "Contributors", contributorString); - - // process source - String sourceString=""; - Generator generator = entry.getGenerator(); - if( generator != null ) - { - sourceString += "Content: '" + generator.getContent() + "'
    '"; - sourceString += "Version: '" + generator.getVersion() + "'
    '"; - sourceString += "Uri: '" + generator.getUri() + "'"; - } - else - { - sourceString += "No generator defined."; - } - - addTableRow(buffer, "Generator", sourceString); - - // process treatment - addTableRow(buffer, "Treatment", entry.getTreatment()); - - // process verboseDescription - addTableRow(buffer, "Verbose Description", entry.getVerboseDescription()); - - // process noOp - addTableRow(buffer, "NoOp", entry.isNoOp()); - - // process formatNamespace - addTableRow(buffer, "Packaging", entry.getPackaging()); - - // process userAgent - addTableRow(buffer, "User Agent", entry.getUserAgent()); - - - buffer.append("
    Entry Summary
    "); - } - - buffer.append(""); - buffer.append(""); - details.setText(buffer.toString()); - } - - /** - * Retrieve the details for a TextConstruct object. - * - * @param data The text construct object to display. - * - * @return Either 'Not defined' if the data is null, or - * details of the text content element. - */ - private String getTextConstructDetails(TextConstruct data) - { - String summaryStr = ""; - if( data == null ) - { - summaryStr = "Not defined"; - } - else - { - summaryStr = "Content: '" + data.getContent() + "', Type: "; - if( data.getType() != null ) - { - summaryStr += "'" + data.getType().toString() + "'"; - } - else - { - summaryStr += "undefined."; - } - } - - return summaryStr; - } - - /** - * Get the author details and insert them into a string. - * - * @param authors the list of authors to process. - * - * @return A string containing the list of authors. - */ - private String getAuthorDetails(Iterator authors) - { - // process author - StringBuffer authorBuffer = new StringBuffer(); - for( ; authors.hasNext(); ) - { - Author a = authors.next(); - authorBuffer.append(getAuthorDetails(a)); - } - - if( authorBuffer.length() == 0 ) - { - authorBuffer.append("Not defined"); - } - - return authorBuffer.toString(); - } - - /** - * Get the contributor details and insert them into a string. - * - * @param contributors The contributors. - * - * @return The string that lists the details of the contributors. - */ - private String getContributorDetails(Iterator contributors) - { - // process author - StringBuffer authorBuffer = new StringBuffer(); - for( ; contributors.hasNext(); ) - { - Contributor c = contributors.next(); - authorBuffer.append(getAuthorDetails(c)); - } - - if( authorBuffer.length() == 0 ) - { - authorBuffer.append("Not defined"); - } - - return authorBuffer.toString(); - } - - /** - * Build a string that describes the specified author. - * - * @param author The author. - * - * @return The string description. - */ - private String getAuthorDetails(Author author) - { - // process author - StringBuffer authorBuffer = new StringBuffer(); - authorBuffer.append(author.getName()); - authorBuffer.append(" (email: '"); - authorBuffer.append(author.getEmail()); - authorBuffer.append("', uri: '"); - authorBuffer.append(author.getUri()); - authorBuffer.append("')
    "); - - return authorBuffer.toString(); - } - - /** - * Process the deposit response and insert the details into the tree. If the url - * matches one of the collections in the tree, the deposit is added as a child - * node. Otherwise, the node is added as a child of the root. - * - * @param url The url of the collection that the file was posted to. - * - * @param response The details of the deposit. - */ - public void processDepositResponse(String url, - DepositResponse response) - { - SWORDEntry entry = response.getEntry(); - Object title = entry.getTitle(); - if( title == null ) - { - title = "Undefined"; - } - else - { - title = entry.getTitle().getContent(); - } - - TreeNodeWrapper wrapper = new TreeNodeWrapper(title.toString(), entry); - DefaultMutableTreeNode entryNode = new DefaultMutableTreeNode(wrapper); - - DefaultMutableTreeNode newParentNode = top; - List nodes = getCollectionNodes(); - for( DefaultMutableTreeNode node : nodes ) - { - Object o = node.getUserObject(); - if( o instanceof TreeNodeWrapper ) - { - TreeNodeWrapper collectionWrapper = (TreeNodeWrapper)o; - Object data = collectionWrapper.getData(); - if( data instanceof Collection ) + else { - Collection col = (Collection)data; - String location = col.getLocation(); - if( location != null && location.equals(url)) - { - newParentNode = node; - break; - } + summaryStr += "undefined."; } - } - } - - treeModel.insertNodeInto(entryNode, newParentNode, newParentNode.getChildCount()); - services.scrollPathToVisible(new TreePath(entryNode.getPath())); - } - - /** - * Get a list of all current collections displayed in the tree. - * - * @return An array of the URLs for the collections. - */ - public String[] getCollectionLocations() - { - List nodes = getCollectionNodes(); - String[] locations = new String[nodes.size()]; - - DefaultMutableTreeNode node; - for( int i = 0; i < nodes.size(); i++ ) - { - node = nodes.get(i); - Object o = node.getUserObject(); - if( o instanceof TreeNodeWrapper ) - { - TreeNodeWrapper collectionWrapper = (TreeNodeWrapper)o; - Object data = collectionWrapper.getData(); - if( data instanceof Collection ) + } + + return summaryStr; + } + + /** + * Get the author details and insert them into a string. + * + * @param authors the list of authors to process. + * + * @return A string containing the list of authors. + */ + private String getAuthorDetails(Iterator authors) + { + // process author + StringBuffer authorBuffer = new StringBuffer(); + for ( ; authors.hasNext(); ) + { + Author a = authors.next(); + authorBuffer.append(getAuthorDetails(a)); + } + + if ( authorBuffer.length() == 0 ) + { + authorBuffer.append("Not defined"); + } + + return authorBuffer.toString(); + } + + /** + * Get the contributor details and insert them into a string. + * + * @param contributors The contributors. + * + * @return The string that lists the details of the contributors. + */ + private String getContributorDetails(Iterator contributors) + { + // process author + StringBuffer authorBuffer = new StringBuffer(); + for ( ; contributors.hasNext(); ) + { + Contributor c = contributors.next(); + authorBuffer.append(getAuthorDetails(c)); + } + + if ( authorBuffer.length() == 0 ) + { + authorBuffer.append("Not defined"); + } + + return authorBuffer.toString(); + } + + /** + * Build a string that describes the specified author. + * + * @param author The author. + * + * @return The string description. + */ + private String getAuthorDetails(Author author) + { + // process author + StringBuffer authorBuffer = new StringBuffer(); + authorBuffer.append(author.getName()); + authorBuffer.append(" (email: '"); + authorBuffer.append(author.getEmail()); + authorBuffer.append("', uri: '"); + authorBuffer.append(author.getUri()); + authorBuffer.append("')
    "); + + return authorBuffer.toString(); + } + + /** + * Process the deposit response and insert the details into the tree. If the url + * matches one of the collections in the tree, the deposit is added as a child + * node. Otherwise, the node is added as a child of the root. + * + * @param url The url of the collection that the file was posted to. + * + * @param response The details of the deposit. + */ + public void processDepositResponse(String url, + DepositResponse response) + { + SWORDEntry entry = response.getEntry(); + Object title = entry.getTitle(); + if ( title == null ) + { + title = "Undefined"; + } + else + { + title = entry.getTitle().getContent(); + } + + TreeNodeWrapper wrapper = new TreeNodeWrapper(title.toString(), entry); + DefaultMutableTreeNode entryNode = new DefaultMutableTreeNode(wrapper); + + DefaultMutableTreeNode newParentNode = top; + List nodes = getCollectionNodes(); + for ( DefaultMutableTreeNode node : nodes ) + { + Object o = node.getUserObject(); + if ( o instanceof TreeNodeWrapper ) { - Collection col = (Collection)data; - String location = col.getLocation(); - if( location != null ) - { - locations[i] = location; - } - } - } - } - return locations; - } - - /** - * Get a list of nodes that contain collections. - * - * @return A vector of the collection nodes. - */ - private List getCollectionNodes() - { - List nodes = new ArrayList(); - - DefaultMutableTreeNode node; - Enumeration treeNodes = top.depthFirstEnumeration(); - - while( treeNodes.hasMoreElements() ) - { - node = (DefaultMutableTreeNode)treeNodes.nextElement(); - Object o = node.getUserObject(); - if( o instanceof TreeNodeWrapper ) - { - TreeNodeWrapper wrapper = (TreeNodeWrapper)o; - Object data = wrapper.getData(); - if( data instanceof Collection ) + TreeNodeWrapper collectionWrapper = (TreeNodeWrapper)o; + Object data = collectionWrapper.getData(); + if ( data instanceof Collection ) + { + Collection col = (Collection)data; + String location = col.getLocation(); + if ( location != null && location.equals(url)) + { + newParentNode = node; + break; + } + } + } + } + + treeModel.insertNodeInto(entryNode, newParentNode, newParentNode.getChildCount()); + services.scrollPathToVisible(new TreePath(entryNode.getPath())); + } + + /** + * Get a list of all current collections displayed in the tree. + * + * @return An array of the URLs for the collections. + */ + public String[] getCollectionLocations() + { + List nodes = getCollectionNodes(); + String[] locations = new String[nodes.size()]; + + DefaultMutableTreeNode node; + for ( int i = 0; i < nodes.size(); i++ ) + { + node = nodes.get(i); + Object o = node.getUserObject(); + if ( o instanceof TreeNodeWrapper ) { - nodes.add(node); + TreeNodeWrapper collectionWrapper = (TreeNodeWrapper)o; + Object data = collectionWrapper.getData(); + if ( data instanceof Collection ) + { + Collection col = (Collection)data; + String location = col.getLocation(); + if ( location != null ) + { + locations[i] = location; + } + } + } + } + return locations; + } + + /** + * Get a list of nodes that contain collections. + * + * @return A vector of the collection nodes. + */ + private List getCollectionNodes() + { + List nodes = new ArrayList(); + + DefaultMutableTreeNode node; + Enumeration treeNodes = top.depthFirstEnumeration(); + + while ( treeNodes.hasMoreElements() ) + { + node = (DefaultMutableTreeNode)treeNodes.nextElement(); + Object o = node.getUserObject(); + if ( o instanceof TreeNodeWrapper ) + { + TreeNodeWrapper wrapper = (TreeNodeWrapper)o; + Object data = wrapper.getData(); + if ( data instanceof Collection ) + { + nodes.add(node); + } } - } - } - - return nodes; - } -} \ No newline at end of file + } + + return nodes; + } +} diff --git a/dspace-sword/src/main/java/org/purl/sword/client/ServletClient.java b/dspace-sword/src/main/java/org/purl/sword/client/ServletClient.java index 28661bfc07..a721950699 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/ServletClient.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/ServletClient.java @@ -68,162 +68,168 @@ import org.purl.sword.base.ServiceDocument; */ public class ServletClient extends HttpServlet { - /** - * The user agent name of this library - */ - public static final String userAgent = "SWORDAPP Java Client: SWORD version 1.3 compatible (http://sourceforge.net/projects/sword-app/)"; - - /** - * Temporary directory. - */ - private String tempDirectory; + /** + * The user agent name of this library + */ + public static final String userAgent = "SWORDAPP Java Client: SWORD version 1.3 compatible (http://sourceforge.net/projects/sword-app/)"; + + /** + * Temporary directory. + */ + private String tempDirectory; - /** - * List of urls for the destination services to access. - */ - private String[] urls; + /** + * List of urls for the destination services to access. + */ + private String[] urls; - /** - * Used to determine if a proxy value should be set. - */ - private boolean useProxy = false; + /** + * Used to determine if a proxy value should be set. + */ + private boolean useProxy = false; - /** - * The proxy host name. - */ - private String pHost; + /** + * The proxy host name. + */ + private String pHost; - /** - * The proxy port name. - */ - private int pPort; + /** + * The proxy port name. + */ + private int pPort; - /** Counter used during Deposit information. */ - private static int counter = 0; + /** Counter used during Deposit information. */ + private static int counter = 0; - /** - * Initialise the servlet. - */ - public void init() { - tempDirectory = getServletContext().getInitParameter( - "upload-temp-directory"); - if ((tempDirectory == null) || (tempDirectory.equals(""))) { - tempDirectory = System.getProperty("java.io.tmpdir"); - } - String lots = getServletContext().getInitParameter("client-urls"); - urls = lots.split(","); - - pHost = getServletContext().getInitParameter("proxy-host"); - String pPortstr = getServletContext().getInitParameter("proxy-port"); - if (((pHost != null) && (!pHost.equals(""))) - && ((pPortstr != null) && (!pPortstr.equals("")))) { - try { - pPort = Integer.parseInt(pPortstr); - useProxy = true; - } catch (Exception e) { - // Port number not numeric - } - } - } + /** + * Initialise the servlet. + */ + public void init() { + tempDirectory = getServletContext().getInitParameter( + "upload-temp-directory"); + if ((tempDirectory == null) || (tempDirectory.equals(""))) { + tempDirectory = System.getProperty("java.io.tmpdir"); + } + String lots = getServletContext().getInitParameter("client-urls"); + urls = lots.split(","); + + pHost = getServletContext().getInitParameter("proxy-host"); + String pPortstr = getServletContext().getInitParameter("proxy-port"); + if (((pHost != null) && (!pHost.equals(""))) + && ((pPortstr != null) && (!pPortstr.equals("")))) { + try { + pPort = Integer.parseInt(pPortstr); + useProxy = true; + } catch (Exception e) { + // Port number not numeric + } + } + } - /** - * Handle a get request. Simply show the default form (form.jsp) - * - * @param request The request details - * @param response The response to write to. - * - * @throws ServletException - * @throws IOException - */ - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - // Get request, so show the default page - request.setAttribute("urls", urls); - request.getRequestDispatcher("form.jsp").forward(request, response); - } + /** + * Handle a get request. Simply show the default form (form.jsp) + * + * @param request The request details + * @param response The response to write to. + * + * @throws ServletException + * 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. + */ + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + // Get request, so show the default page + request.setAttribute("urls", urls); + request.getRequestDispatcher("form.jsp").forward(request, response); + } - /** - * Process the post. Determine if the request is for a post or service - * document. Then, dispatch the request to the appropriate handler. - * - * @param request The request details. - * @param response The response to write to. - * - * @throws ServletException - * @throws IOException - */ + /** + * Process the post. Determine if the request is for a post or service + * document. Then, dispatch the request to the appropriate handler. + * + * @param request The request details. + * @param response The response to write to. + * + * @throws ServletException + * 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. + */ - protected void doPost(HttpServletRequest request, + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getParameter("servicedocument") != null) { - this.doServiceDocument(request, response); - } else if (request.getParameter("deposit") != null) { - request.setAttribute("url", request.getParameter("url")); - request.setAttribute("u", request.getParameter("u")); - request.setAttribute("p", request.getParameter("p")); - request.setAttribute("obo", request.getParameter("obo")); - request.setAttribute("abstract", request.getParameter("abstract")); - request.setAttribute("policy", request.getParameter("policy")); - request.setAttribute("treatment", request.getParameter("treatment")); - request.setAttribute("mediation", request.getParameter("mediation")); - request.setAttribute("accepts", request.getParameter("accepts")); - request.setAttribute("acceptsp", request.getParameter("acceptsp")); - request.setAttribute("maxuploadsize", request.getParameter("maxuploadsize")); - request.getRequestDispatcher("depositform.jsp").forward(request, response); - } else if (ServletFileUpload.isMultipartContent(request)) { - this.doDeposit(request, response); - } else { - request.setAttribute("urls", urls); - request.getRequestDispatcher("form.jsp").forward(request, response); - } - } + if (request.getParameter("servicedocument") != null) { + this.doServiceDocument(request, response); + } else if (request.getParameter("deposit") != null) { + request.setAttribute("url", request.getParameter("url")); + request.setAttribute("u", request.getParameter("u")); + request.setAttribute("p", request.getParameter("p")); + request.setAttribute("obo", request.getParameter("obo")); + request.setAttribute("abstract", request.getParameter("abstract")); + request.setAttribute("policy", request.getParameter("policy")); + request.setAttribute("treatment", request.getParameter("treatment")); + request.setAttribute("mediation", request.getParameter("mediation")); + request.setAttribute("accepts", request.getParameter("accepts")); + request.setAttribute("acceptsp", request.getParameter("acceptsp")); + request.setAttribute("maxuploadsize", request.getParameter("maxuploadsize")); + request.getRequestDispatcher("depositform.jsp").forward(request, response); + } else if (ServletFileUpload.isMultipartContent(request)) { + this.doDeposit(request, response); + } else { + request.setAttribute("urls", urls); + request.getRequestDispatcher("form.jsp").forward(request, response); + } + } - /** - * Process the request for a service document. - * - * @param request The request details. - * @param response The response to write to. - * - * @throws ServletException - * @throws IOException - */ + /** + * Process the request for a service document. + * + * @param request The request details. + * @param response The response to write to. + * + * @throws ServletException + * 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. + */ - private void doServiceDocument(HttpServletRequest request, + private void doServiceDocument(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - // Get the service document - Client client = new Client(); - // Which URL do we want? - URL url = new URL(request.getParameter("url")); - String theUrl = request.getParameter("url"); - - if ((request.getParameter("ownurl") != null) - && (!request.getParameter("ownurl").equals(""))) { - url = new URL(request.getParameter("ownurl")); - theUrl = request.getParameter("ownurl"); - } + // Get the service document + Client client = new Client(); + // Which URL do we want? + URL url = new URL(request.getParameter("url")); + String theUrl = request.getParameter("url"); + + if ((request.getParameter("ownurl") != null) + && (!request.getParameter("ownurl").equals(""))) { + url = new URL(request.getParameter("ownurl")); + theUrl = request.getParameter("ownurl"); + } - int port = url.getPort(); - if (port == -1) { - port = 80; - } + int port = url.getPort(); + if (port == -1) { + port = 80; + } - // Set up the server - client.setServer(url.getHost(), port); - client.setCredentials(request.getParameter("u"), request.getParameter("p")); - if (useProxy) { - client.setProxy(pHost, pPort); - } + // Set up the server + client.setServer(url.getHost(), port); + client.setCredentials(request.getParameter("u"), request.getParameter("p")); + if (useProxy) { + client.setProxy(pHost, pPort); + } - try { - ServiceDocument sd = client.getServiceDocument(theUrl, - request.getParameter("obo")); + try { + ServiceDocument sd = client.getServiceDocument(theUrl, + request.getParameter("obo")); - // Set the status - Status status = client.getStatus(); - request.setAttribute("status", status.toString()); - if (status.getCode() == 200) { - // Set the debug response - String xml = sd.marshall(); + // Set the status + Status status = client.getStatus(); + request.setAttribute("status", status.toString()); + if (status.getCode() == 200) { + // Set the debug response + String xml = sd.marshall(); String validateXml = xml; validateXml = validateXml.replaceAll("&", "&"); @@ -233,155 +239,157 @@ public class ServletClient extends HttpServlet { validateXml = validateXml.replaceAll("'", "'"); request.setAttribute("xmlValidate", validateXml); // for passing to validation - xml = xml.replaceAll("<", "<"); - xml = xml.replaceAll(">", ">"); - request.setAttribute("xml", xml); - - // Set the ServiceDocument and associated values - request.setAttribute("sd", sd); - request.setAttribute("sdURL", theUrl); - request.setAttribute("u", request.getParameter("u")); - request.setAttribute("p", request.getParameter("p")); - request.setAttribute("sdOBO", request.getParameter("obo")); - request.getRequestDispatcher("servicedocument.jsp").forward( - request, response); - return; - } else { - request.setAttribute("error", status.getCode() + " " - + status.getMessage()); - request.setAttribute("urls", urls); - request.getRequestDispatcher("form.jsp").forward(request, - response); - return; - } - } catch (SWORDClientException e) { - e.printStackTrace(); - request.setAttribute("error", e.toString()); - request.setAttribute("urls", urls); - request.getRequestDispatcher("form.jsp").forward(request, response); - } - } + xml = xml.replaceAll("<", "<"); + xml = xml.replaceAll(">", ">"); + request.setAttribute("xml", xml); + + // Set the ServiceDocument and associated values + request.setAttribute("sd", sd); + request.setAttribute("sdURL", theUrl); + request.setAttribute("u", request.getParameter("u")); + request.setAttribute("p", request.getParameter("p")); + request.setAttribute("sdOBO", request.getParameter("obo")); + request.getRequestDispatcher("servicedocument.jsp").forward( + request, response); + return; + } else { + request.setAttribute("error", status.getCode() + " " + + status.getMessage()); + request.setAttribute("urls", urls); + request.getRequestDispatcher("form.jsp").forward(request, + response); + return; + } + } catch (SWORDClientException e) { + e.printStackTrace(); + request.setAttribute("error", e.toString()); + request.setAttribute("urls", urls); + request.getRequestDispatcher("form.jsp").forward(request, response); + } + } - /** - * Process a deposit. - * - * @param request The request details. - * @param response The response to output to. - * - * @throws ServletException - * @throws IOException - */ - private void doDeposit(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - // Do the deposit - Client client = new Client(); - try { - PostMessage message = new PostMessage(); + /** + * Process a deposit. + * + * @param request The request details. + * @param response The response to output to. + * + * @throws ServletException + * 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. + */ + private void doDeposit(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + // Do the deposit + Client client = new Client(); + try { + PostMessage message = new PostMessage(); message.setUserAgent(ClientConstants.SERVICE_NAME); - - // Get the file - FileItemFactory factory = new DiskFileItemFactory(); - - // Create a new file upload handler - ServletFileUpload upload = new ServletFileUpload(factory); - - // Parse the request - List items = upload.parseRequest(request); - Iterator iter = items.iterator(); - String u = null; - String p = null; - String contentDisposition = null; - String filetype = null; - boolean useMD5 = false; - boolean errorMD5 = false; - boolean verbose = false; - boolean noOp = false; - boolean login = false; - while (iter.hasNext()) { - FileItem item = iter.next(); - if (item.isFormField()) { - String name = item.getFieldName(); - String value = item.getString(); - if (name.equals("url")) { - message.setDestination(value); - URL url = new URL(value); - int port = url.getPort(); - if (port == -1) { - port = 80; - } - client.setServer(url.getHost(), port); - } else if (name.equals("usemd5")) { - useMD5 = true; - } else if (name.equals("errormd5")) { - errorMD5 = true; - } else if (name.equals("verbose")) { - verbose = true; - } else if (name.equals("noop")) { - noOp = true; - } else if (name.equals("obo")) { - message.setOnBehalfOf(value); - } else if (name.equals("slug")) { - if ((value != null) && (!value.trim().equals(""))) { - message.setSlug(value); - } - } else if (name.equals("cd")) { - contentDisposition = value; - } else if (name.equals("filetype")) { - filetype = value; - } else if (name.equals("formatnamespace")) { - if ((value != null) && (!value.trim().equals(""))) { - message.setFormatNamespace(value); - } - } else if (name.equals("u")) { - u = value; - login = true; - request.setAttribute("u", value); - } else if (name.equals("p")) { - p = value; - login = true; - } - request.setAttribute(name, value); - } else { - String fname = tempDirectory + File.separator + - "ServletClient-" + counter++; - if ((contentDisposition != null) && (!contentDisposition.equals(""))) { - fname = tempDirectory + File.separator + contentDisposition; - } + + // Get the file + FileItemFactory factory = new DiskFileItemFactory(); + + // Create a new file upload handler + ServletFileUpload upload = new ServletFileUpload(factory); + + // Parse the request + List items = upload.parseRequest(request); + Iterator iter = items.iterator(); + String u = null; + String p = null; + String contentDisposition = null; + String filetype = null; + boolean useMD5 = false; + boolean errorMD5 = false; + boolean verbose = false; + boolean noOp = false; + boolean login = false; + while (iter.hasNext()) { + FileItem item = iter.next(); + if (item.isFormField()) { + String name = item.getFieldName(); + String value = item.getString(); + if (name.equals("url")) { + message.setDestination(value); + URL url = new URL(value); + int port = url.getPort(); + if (port == -1) { + port = 80; + } + client.setServer(url.getHost(), port); + } else if (name.equals("usemd5")) { + useMD5 = true; + } else if (name.equals("errormd5")) { + errorMD5 = true; + } else if (name.equals("verbose")) { + verbose = true; + } else if (name.equals("noop")) { + noOp = true; + } else if (name.equals("obo")) { + message.setOnBehalfOf(value); + } else if (name.equals("slug")) { + if ((value != null) && (!value.trim().equals(""))) { + message.setSlug(value); + } + } else if (name.equals("cd")) { + contentDisposition = value; + } else if (name.equals("filetype")) { + filetype = value; + } else if (name.equals("formatnamespace")) { + if ((value != null) && (!value.trim().equals(""))) { + message.setFormatNamespace(value); + } + } else if (name.equals("u")) { + u = value; + login = true; + request.setAttribute("u", value); + } else if (name.equals("p")) { + p = value; + login = true; + } + request.setAttribute(name, value); + } else { + String fname = tempDirectory + File.separator + + "ServletClient-" + counter++; + if ((contentDisposition != null) && (!contentDisposition.equals(""))) { + fname = tempDirectory + File.separator + contentDisposition; + } - File uploadedFile = new File(fname); - item.write(uploadedFile); - message.setFilepath(fname); + File uploadedFile = new File(fname); + item.write(uploadedFile); + message.setFilepath(fname); - if ((filetype == null) || (filetype.trim().equals(""))) { - message.setFiletype(item.getContentType()); - } else { - message.setFiletype(filetype); - } - } - } + if ((filetype == null) || (filetype.trim().equals(""))) { + message.setFiletype(item.getContentType()); + } else { + message.setFiletype(filetype); + } + } + } - if (login) { - client.setCredentials(u, p); - } + if (login) { + client.setCredentials(u, p); + } - if (useProxy) { - client.setProxy(pHost, pPort); - } + if (useProxy) { + client.setProxy(pHost, pPort); + } message.setUseMD5(useMD5); - message.setChecksumError(errorMD5); - message.setVerbose(verbose); - message.setNoOp(noOp); + message.setChecksumError(errorMD5); + message.setVerbose(verbose); + message.setNoOp(noOp); - // Post the file - DepositResponse resp = client.postFile(message); + // Post the file + DepositResponse resp = client.postFile(message); - // Set the status - Status status = client.getStatus(); - request.setAttribute("status", status.toString()); - if ((status.getCode() == 201) || (status.getCode() == 202)) { - // Set the debug response - String xml = resp.marshall(); + // Set the status + Status status = client.getStatus(); + request.setAttribute("status", status.toString()); + if ((status.getCode() == 201) || (status.getCode() == 202)) { + // Set the debug response + String xml = resp.marshall(); String validateXml = xml; validateXml = validateXml.replaceAll("&", "&"); @@ -391,56 +399,56 @@ public class ServletClient extends HttpServlet { validateXml = validateXml.replaceAll("'", "'"); request.setAttribute("xmlValidate", validateXml); // for passing to validation - xml = xml.replaceAll("<", "<"); - xml = xml.replaceAll(">", ">"); - request.setAttribute("xml", xml); - SWORDEntry se = resp.getEntry(); - request.setAttribute("id", se.getId()); - request.setAttribute("authors", se.getAuthors()); - request.setAttribute("contributors", se.getContributors()); - request.setAttribute("title", se.getTitle().getContent()); - request.setAttribute("updated", se.getUpdated()); - request.setAttribute("categories", se.getCategories()); - request.setAttribute("treatment", se.getTreatment()); - request.setAttribute("summary", se.getSummary().getContent()); - request.setAttribute("generator", se.getGenerator().getContent()); - request.setAttribute("userAgent", se.getUserAgent()); - request.setAttribute("packaging", se.getPackaging()); - request.setAttribute("links", se.getLinks()); - request.setAttribute("location", resp.getLocation()); - - // Set the ServiceDocument and associated values - request.getRequestDispatcher("deposit.jsp").forward(request, response); - return; - } else { - String error = status.getCode() + " " + status.getMessage() + " - "; - try { - error += resp.getEntry().getSummary().getContent(); - } catch (Exception e) { - // Do nothing - we have default error message + xml = xml.replaceAll("<", "<"); + xml = xml.replaceAll(">", ">"); + request.setAttribute("xml", xml); + SWORDEntry se = resp.getEntry(); + request.setAttribute("id", se.getId()); + request.setAttribute("authors", se.getAuthors()); + request.setAttribute("contributors", se.getContributors()); + request.setAttribute("title", se.getTitle().getContent()); + request.setAttribute("updated", se.getUpdated()); + request.setAttribute("categories", se.getCategories()); + request.setAttribute("treatment", se.getTreatment()); + request.setAttribute("summary", se.getSummary().getContent()); + request.setAttribute("generator", se.getGenerator().getContent()); + request.setAttribute("userAgent", se.getUserAgent()); + request.setAttribute("packaging", se.getPackaging()); + request.setAttribute("links", se.getLinks()); + request.setAttribute("location", resp.getLocation()); + + // Set the ServiceDocument and associated values + request.getRequestDispatcher("deposit.jsp").forward(request, response); + return; + } else { + String error = status.getCode() + " " + status.getMessage() + " - "; + try { + error += resp.getEntry().getSummary().getContent(); + } catch (Exception e) { + // Do nothing - we have default error message e.printStackTrace(); - } - request.setAttribute("error", error); - - // Try and get an error document in xml - String xml = resp.marshall(); - xml = xml.replaceAll("<", "<"); - xml = xml.replaceAll(">", ">"); - request.setAttribute("xml", xml); - - request.getRequestDispatcher("depositform.jsp").forward(request, response); - return; - } - } catch (RuntimeException e) { + } + request.setAttribute("error", error); + + // Try and get an error document in xml + String xml = resp.marshall(); + xml = xml.replaceAll("<", "<"); + xml = xml.replaceAll(">", ">"); + request.setAttribute("xml", xml); + + request.getRequestDispatcher("depositform.jsp").forward(request, response); + return; + } + } catch (RuntimeException e) { e.printStackTrace(); request.setAttribute("error", "value: " + e.toString()); request.setAttribute("urls", urls); request.getRequestDispatcher("depositform.jsp").forward(request, response); } catch (Exception e) { - e.printStackTrace(); - request.setAttribute("error", "value: " + e.toString()); - request.setAttribute("urls", urls); - request.getRequestDispatcher("depositform.jsp").forward(request, response); - } - } -} \ No newline at end of file + e.printStackTrace(); + request.setAttribute("error", "value: " + e.toString()); + request.setAttribute("urls", urls); + request.getRequestDispatcher("depositform.jsp").forward(request, response); + } + } +} diff --git a/dspace-sword/src/main/java/org/purl/sword/client/Status.java b/dspace-sword/src/main/java/org/purl/sword/client/Status.java index 6edb6f3a40..84ba359cc1 100644 --- a/dspace-sword/src/main/java/org/purl/sword/client/Status.java +++ b/dspace-sword/src/main/java/org/purl/sword/client/Status.java @@ -14,53 +14,53 @@ package org.purl.sword.client; */ public class Status { - /** - * The status code. - */ - private int code; - - /** - * The status message. - */ - private String message; - - /** - * Create a new status message. - * - * @param code The code. - * @param message The message. - */ - public Status( int code, String message) - { - this.code = code; - this.message = message; - } - - /** - * Retrieve the code. - * - * @return The code. - */ - public int getCode( ) - { - return code; - } - - /** - * Get the message. - * - * @return The message. - */ - public String getMessage() - { - return message; - } - - /** - * Get a string representation of the status. - */ - public String toString() - { - return "Code: " + code + ", Message: '" + message + "'"; - } -} \ No newline at end of file + /** + * The status code. + */ + private int code; + + /** + * The status message. + */ + private String message; + + /** + * Create a new status message. + * + * @param code The code. + * @param message The message. + */ + public Status( int code, String message) + { + this.code = code; + this.message = message; + } + + /** + * Retrieve the code. + * + * @return The code. + */ + public int getCode( ) + { + return code; + } + + /** + * Get the message. + * + * @return The message. + */ + public String getMessage() + { + return message; + } + + /** + * Get a string representation of the status. + */ + public String toString() + { + return "Code: " + code + ", Message: '" + message + "'"; + } +} diff --git a/dspace-sword/src/main/java/org/purl/sword/server/AtomDocumentServlet.java b/dspace-sword/src/main/java/org/purl/sword/server/AtomDocumentServlet.java index 6aef67f107..c7a6b8fbc7 100644 --- a/dspace-sword/src/main/java/org/purl/sword/server/AtomDocumentServlet.java +++ b/dspace-sword/src/main/java/org/purl/sword/server/AtomDocumentServlet.java @@ -22,72 +22,85 @@ import org.purl.sword.base.SWORDException; /** * EntryDocumentServlet - * + * * @author Glen Robson * @author Stuart Lewis */ public class AtomDocumentServlet extends DepositServlet { public AtomDocumentServlet() - throws ServletException + throws ServletException { super(); } /** - * Process the get request. - */ + * Process the get request. + */ @Override - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - try { - // Create the atom document request object - AtomDocumentRequest adr = new AtomDocumentRequest(); - - // Are there any authentication details? - String usernamePassword = getUsernamePassword(request); - if ((usernamePassword != null) && (!usernamePassword.equals(""))) { - int p = usernamePassword.indexOf(':'); - if (p != -1) { - adr.setUsername(usernamePassword.substring(0, p)); - adr.setPassword(usernamePassword.substring(p + 1)); - } - } else if (authenticateWithBasic()) { - String s = "Basic realm=\"SWORD\""; - response.setHeader("WWW-Authenticate", s); - response.setStatus(401); - return; - } - - // Set the IP address - adr.setIPAddress(request.getRemoteAddr()); + protected void doGet(HttpServletRequest request, + HttpServletResponse response) + throws ServletException, IOException + { + try + { + // Create the atom document request object + AtomDocumentRequest adr = new AtomDocumentRequest(); - // Set the deposit location - adr.setLocation(getUrl(request)); - - // Generate the response - AtomDocumentResponse dr = myRepository.doAtomDocument(adr); - - // Print out the Deposit Response - response.setStatus(dr.getHttpResponse()); - response.setContentType("application/atom+xml; charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.write(dr.marshall()); - out.flush(); - } catch (SWORDAuthenticationException sae) { - // Ask for credentials again - String s = "Basic realm=\"SWORD\""; - response.setHeader("WWW-Authenticate", s); - response.setStatus(401); - } catch (SWORDException se) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } catch (SWORDErrorException see) { - // Get the details and send the right SWORD error document - super.makeErrorDocument(see.getErrorURI(), - see.getStatus(), - see.getDescription(), - request, - response); - } - } + // Are there any authentication details? + String usernamePassword = getUsernamePassword(request); + if ((usernamePassword != null) && (!usernamePassword.equals(""))) + { + int p = usernamePassword.indexOf(':'); + if (p != -1) + { + adr.setUsername(usernamePassword.substring(0, p)); + adr.setPassword(usernamePassword.substring(p + 1)); + } + } + else if (authenticateWithBasic()) + { + String s = "Basic realm=\"SWORD\""; + response.setHeader("WWW-Authenticate", s); + response.setStatus(401); + return; + } + + // Set the IP address + adr.setIPAddress(request.getRemoteAddr()); + + // Set the deposit location + adr.setLocation(getUrl(request)); + + // Generate the response + AtomDocumentResponse dr = myRepository.doAtomDocument(adr); + + // Print out the Deposit Response + response.setStatus(dr.getHttpResponse()); + response.setContentType("application/atom+xml; charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.write(dr.marshall()); + out.flush(); + } + catch (SWORDAuthenticationException sae) + { + // Ask for credentials again + String s = "Basic realm=\"SWORD\""; + response.setHeader("WWW-Authenticate", s); + response.setStatus(401); + } + catch (SWORDException se) + { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + catch (SWORDErrorException see) + { + // Get the details and send the right SWORD error document + super.makeErrorDocument(see.getErrorURI(), + see.getStatus(), + see.getDescription(), + request, + response); + } + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/server/DepositServlet.java b/dspace-sword/src/main/java/org/purl/sword/server/DepositServlet.java index 77b0f085bc..db0248d204 100644 --- a/dspace-sword/src/main/java/org/purl/sword/server/DepositServlet.java +++ b/dspace-sword/src/main/java/org/purl/sword/server/DepositServlet.java @@ -46,38 +46,38 @@ import org.purl.sword.base.SWORDErrorException; */ public class DepositServlet extends HttpServlet { - /** Sword repository */ - protected transient SWORDServer myRepository; + /** Sword repository */ + protected transient SWORDServer myRepository; - /** Authentication type */ - private String authN; - - /** Maximum file upload size in kB **/ - private int maxUploadSize; + /** Authentication type */ + private String authN; + + /** Maximum file upload size in kB **/ + private int maxUploadSize; - /** Temp directory */ - private String tempDirectory; + /** Temp directory */ + private String tempDirectory; - /** Counter */ - private static final AtomicInteger counter = new AtomicInteger(0); + /** Counter */ + private static final AtomicInteger counter = new AtomicInteger(0); - /** Logger */ - private static final Logger log = Logger.getLogger(DepositServlet.class); + /** Logger */ + private static final Logger log = Logger.getLogger(DepositServlet.class); /** - * Initialise the servlet. - * - * @throws ServletException if there is trouble with the upload directory. - */ + * Initialise the servlet. + * + * @throws ServletException if there is trouble with the upload directory. + */ @Override - public void init() throws ServletException { + public void init() throws ServletException { // Instantiate the correct SWORD Server class - String className = getServletContext().getInitParameter("sword-server-class"); - if (className == null) { - log.fatal("Unable to read value of 'sword-server-class' from Servlet context"); + String className = getServletContext().getInitParameter("sword-server-class"); + if (className == null) { + log.fatal("Unable to read value of 'sword-server-class' from Servlet context"); throw new ServletException("Unable to read value of 'sword-server-class' from Servlet context"); - } + } try { myRepository = (SWORDServer) Class.forName(className) @@ -92,367 +92,370 @@ public class DepositServlet extends HttpServlet { } authN = getServletContext().getInitParameter("authentication-method"); - if ((authN == null) || (authN.equals(""))) { - authN = "None"; - } - log.info("Authentication type set to: " + authN); + if ((authN == null) || (authN.equals(""))) { + authN = "None"; + } + log.info("Authentication type set to: " + authN); - String maxUploadSizeStr = getServletContext().getInitParameter("maxUploadSize"); - if ((maxUploadSizeStr == null) || - (maxUploadSizeStr.equals("")) || - (maxUploadSizeStr.equals("-1"))) { - maxUploadSize = -1; - log.warn("No maxUploadSize set, so setting max file upload size to unlimited."); - } else { - try { - maxUploadSize = Integer.parseInt(maxUploadSizeStr); - log.info("Setting max file upload size to " + maxUploadSize); - } catch (NumberFormatException nfe) { - maxUploadSize = -1; - log.warn("maxUploadSize not a number, so setting max file upload size to unlimited."); - } - } + String maxUploadSizeStr = getServletContext().getInitParameter("maxUploadSize"); + if ((maxUploadSizeStr == null) || + (maxUploadSizeStr.equals("")) || + (maxUploadSizeStr.equals("-1"))) { + maxUploadSize = -1; + log.warn("No maxUploadSize set, so setting max file upload size to unlimited."); + } else { + try { + maxUploadSize = Integer.parseInt(maxUploadSizeStr); + log.info("Setting max file upload size to " + maxUploadSize); + } catch (NumberFormatException nfe) { + maxUploadSize = -1; + log.warn("maxUploadSize not a number, so setting max file upload size to unlimited."); + } + } - tempDirectory = getServletContext().getInitParameter( - "upload-temp-directory"); - if ((tempDirectory == null) || (tempDirectory.equals(""))) { - tempDirectory = System.getProperty("java.io.tmpdir"); - } + tempDirectory = getServletContext().getInitParameter( + "upload-temp-directory"); + if ((tempDirectory == null) || (tempDirectory.equals(""))) { + tempDirectory = System.getProperty("java.io.tmpdir"); + } if (!tempDirectory.endsWith(System.getProperty("file.separator"))) { tempDirectory += System.getProperty("file.separator"); } - File tempDir = new File(tempDirectory); - log.info("Upload temporary directory set to: " + tempDir); - if (!tempDir.exists() && !tempDir.mkdirs()) { + File tempDir = new File(tempDirectory); + log.info("Upload temporary directory set to: " + tempDir); + if (!tempDir.exists() && !tempDir.mkdirs()) { throw new ServletException( "Upload directory did not exist and I can't create it. " + tempDir); } - if (!tempDir.isDirectory()) { - log.fatal("Upload temporary directory is not a directory: " - + tempDir); - throw new ServletException( - "Upload temporary directory is not a directory: " + tempDir); - } - if (!tempDir.canWrite()) { - log.fatal("Upload temporary directory cannot be written to: " - + tempDir); - throw new ServletException( - "Upload temporary directory cannot be written to: " - + tempDir); - } - } + if (!tempDir.isDirectory()) { + log.fatal("Upload temporary directory is not a directory: " + + tempDir); + throw new ServletException( + "Upload temporary directory is not a directory: " + tempDir); + } + if (!tempDir.canWrite()) { + log.fatal("Upload temporary directory cannot be written to: " + + tempDir); + throw new ServletException( + "Upload temporary directory cannot be written to: " + + tempDir); + } + } - /** - * Process the Get request. This will return an unimplemented response. + /** + * Process the Get request. This will return an unimplemented response. * @param request the request. * @param response the response. * @throws javax.servlet.ServletException passed through. * @throws java.io.IOException passed through. - */ + */ @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - // Send a '501 Not Implemented' - response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); - } + // Send a '501 Not Implemented' + response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); + } - /** - * Process a post request. + /** + * Process a post request. * @param request the request. * @param response the response. * @throws javax.servlet.ServletException passed through. * @throws java.io.IOException passed through. - */ + */ @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - // Create the Deposit request - Deposit d = new Deposit(); - Date date = new Date(); - log.debug("Starting deposit processing at " + date.toString() + " by " - + request.getRemoteAddr()); + // Create the Deposit request + Deposit d = new Deposit(); + Date date = new Date(); + log.debug("Starting deposit processing at " + date.toString() + " by " + + request.getRemoteAddr()); - // Are there any authentication details? - String usernamePassword = getUsernamePassword(request); - if ((usernamePassword != null) && (!usernamePassword.equals(""))) { - int p = usernamePassword.indexOf(':'); - if (p != -1) { - d.setUsername(usernamePassword.substring(0, p)); - d.setPassword(usernamePassword.substring(p + 1)); - } - } else if (authenticateWithBasic()) { - String s = "Basic realm=\"SWORD\""; - response.setHeader("WWW-Authenticate", s); - response.setStatus(401); - return; - } - - // Set up some variables - String filename = null; - - // Do the processing - try { - // Write the file to the temp directory - filename = tempDirectory + "SWORD-" - + request.getRemoteAddr() + "-" + counter.addAndGet(1); + // Are there any authentication details? + String usernamePassword = getUsernamePassword(request); + if ((usernamePassword != null) && (!usernamePassword.equals(""))) { + int p = usernamePassword.indexOf(':'); + if (p != -1) { + d.setUsername(usernamePassword.substring(0, p)); + d.setPassword(usernamePassword.substring(p + 1)); + } + } else if (authenticateWithBasic()) { + String s = "Basic realm=\"SWORD\""; + response.setHeader("WWW-Authenticate", s); + response.setStatus(401); + return; + } + + // Set up some variables + String filename = null; + + // Do the processing + try { + // Write the file to the temp directory + filename = tempDirectory + "SWORD-" + + request.getRemoteAddr() + "-" + counter.addAndGet(1); log.debug("Package temporarily stored as: " + filename); - InputStream inputstream = request.getInputStream(); - OutputStream outputstream = new FileOutputStream(new File(filename)); - try - { - byte[] buf = new byte[1024]; - int len; - while ((len = inputstream.read(buf)) > 0) - { - outputstream.write(buf, 0, len); - } - } - finally - { - inputstream.close(); - outputstream.close(); - } + InputStream inputstream = request.getInputStream(); + OutputStream outputstream = new FileOutputStream(new File(filename)); + try + { + byte[] buf = new byte[1024]; + int len; + while ((len = inputstream.read(buf)) > 0) + { + outputstream.write(buf, 0, len); + } + } + finally + { + inputstream.close(); + outputstream.close(); + } - // Check the size is OK - File file = new File(filename); - long fLength = file.length() / 1024; - if ((maxUploadSize != -1) && (fLength > maxUploadSize)) { - this.makeErrorDocument(ErrorCodes.MAX_UPLOAD_SIZE_EXCEEDED, - HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, - "The uploaded file exceeded the maximum file size this server will accept (the file is " + - fLength + "kB but the server will only accept files as large as " + - maxUploadSize + "kB)", - request, - response); - return; - } - - // Check the MD5 hash - String receivedMD5 = ChecksumUtils.generateMD5(filename); - log.debug("Received filechecksum: " + receivedMD5); - d.setMd5(receivedMD5); - String md5 = request.getHeader("Content-MD5"); - log.debug("Received file checksum header: " + md5); - if ((md5 != null) && (!md5.equals(receivedMD5))) { - // Return an error document - this.makeErrorDocument(ErrorCodes.ERROR_CHECKSUM_MISMATCH, - HttpServletResponse.SC_PRECONDITION_FAILED, - "The received MD5 checksum for the deposited file did not match the checksum sent by the deposit client", - request, - response); - log.debug("Bad MD5 for file. Aborting with appropriate error message"); - return; - } else { - // Set the file to be deposited - d.setFile(file); + // Check the size is OK + File file = new File(filename); + long fLength = file.length() / 1024; + if ((maxUploadSize != -1) && (fLength > maxUploadSize)) { + this.makeErrorDocument(ErrorCodes.MAX_UPLOAD_SIZE_EXCEEDED, + HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, + "The uploaded file exceeded the maximum file size this server will accept (the file is " + + fLength + "kB but the server will only accept files as large as " + + maxUploadSize + "kB)", + request, + response); + return; + } + + // Check the MD5 hash + String receivedMD5 = ChecksumUtils.generateMD5(filename); + log.debug("Received filechecksum: " + receivedMD5); + d.setMd5(receivedMD5); + String md5 = request.getHeader("Content-MD5"); + log.debug("Received file checksum header: " + md5); + if ((md5 != null) && (!md5.equals(receivedMD5))) { + // Return an error document + this.makeErrorDocument(ErrorCodes.ERROR_CHECKSUM_MISMATCH, + HttpServletResponse.SC_PRECONDITION_FAILED, + "The received MD5 checksum for the deposited file did not match the checksum sent by the deposit client", + request, + response); + log.debug("Bad MD5 for file. Aborting with appropriate error message"); + return; + } else { + // Set the file to be deposited + d.setFile(file); - // Set the X-On-Behalf-Of header + // Set the X-On-Behalf-Of header String onBehalfOf = request.getHeader(HttpHeaders.X_ON_BEHALF_OF); - if ((onBehalfOf != null) && (onBehalfOf.equals("reject"))) { + if ((onBehalfOf != null) && (onBehalfOf.equals("reject"))) { // user name is "reject", so throw a not know error to allow the client to be tested throw new SWORDErrorException(ErrorCodes.TARGET_OWNER_UKNOWN,"unknown user \"reject\""); } else { d.setOnBehalfOf(onBehalfOf); } - // Set the X-Packaging header - d.setPackaging(request.getHeader(HttpHeaders.X_PACKAGING)); + // Set the X-Packaging header + d.setPackaging(request.getHeader(HttpHeaders.X_PACKAGING)); - // Set the X-No-Op header - String noop = request.getHeader(HttpHeaders.X_NO_OP); + // Set the X-No-Op header + String noop = request.getHeader(HttpHeaders.X_NO_OP); log.error("X_NO_OP value is " + noop); - if ((noop != null) && (noop.equals("true"))) { - d.setNoOp(true); - } else if ((noop != null) && (noop.equals("false"))) { - d.setNoOp(false); - }else if (noop == null) { + if ((noop != null) && (noop.equals("true"))) { + d.setNoOp(true); + } else if ((noop != null) && (noop.equals("false"))) { d.setNoOp(false); - } else { + } else if (noop == null) { + d.setNoOp(false); + } else { throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST,"Bad no-op"); } - // Set the X-Verbose header - String verbose = request.getHeader(HttpHeaders.X_VERBOSE); - if ((verbose != null) && (verbose.equals("true"))) { - d.setVerbose(true); - } else if ((verbose != null) && (verbose.equals("false"))) { - d.setVerbose(false); - }else if (verbose == null) { + // Set the X-Verbose header + String verbose = request.getHeader(HttpHeaders.X_VERBOSE); + if ((verbose != null) && (verbose.equals("true"))) { + d.setVerbose(true); + } else if ((verbose != null) && (verbose.equals("false"))) { d.setVerbose(false); - } else { + } else if (verbose == null) { + d.setVerbose(false); + } else { throw new SWORDErrorException(ErrorCodes.ERROR_BAD_REQUEST,"Bad verbose"); } - // Set the slug - String slug = request.getHeader(HttpHeaders.SLUG); - if (slug != null) { - d.setSlug(slug); - } + // Set the slug + String slug = request.getHeader(HttpHeaders.SLUG); + if (slug != null) { + d.setSlug(slug); + } - // Set the content disposition - d.setContentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION)); + // Set the content disposition + d.setContentDisposition(request.getHeader(HttpHeaders.CONTENT_DISPOSITION)); - // Set the IP address - d.setIPAddress(request.getRemoteAddr()); + // Set the IP address + d.setIPAddress(request.getRemoteAddr()); - // Set the deposit location - d.setLocation(getUrl(request)); + // Set the deposit location + d.setLocation(getUrl(request)); - // Set the content type - d.setContentType(request.getContentType()); + // Set the content type + d.setContentType(request.getContentType()); - // Set the content length - String cl = request.getHeader(HttpHeaders.CONTENT_LENGTH); - if ((cl != null) && (!cl.equals(""))) { - d.setContentLength(Integer.parseInt(cl)); - } + // Set the content length + String cl = request.getHeader(HttpHeaders.CONTENT_LENGTH); + if ((cl != null) && (!cl.equals(""))) { + d.setContentLength(Integer.parseInt(cl)); + } - // Get the DepositResponse - DepositResponse dr = myRepository.doDeposit(d); - - // Echo back the user agent - if (request.getHeader(HttpHeaders.USER_AGENT) != null) { - dr.getEntry().setUserAgent(request.getHeader(HttpHeaders.USER_AGENT)); - } - - // Echo back the packaging format - if (request.getHeader(HttpHeaders.X_PACKAGING) != null) { - dr.getEntry().setPackaging(request.getHeader(HttpHeaders.X_PACKAGING)); - } - - // Print out the Deposit Response - response.setStatus(dr.getHttpResponse()); - if ((dr.getLocation() != null) && (!dr.getLocation().equals(""))) - { - response.setHeader("Location", dr.getLocation()); - } - response.setContentType("application/atom+xml; charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.write(dr.marshall()); - out.flush(); - } - } catch (SWORDAuthenticationException sae) { - // Ask for credentials again - if (authN.equals("Basic")) { - String s = "Basic realm=\"SWORD\""; - response.setHeader("WWW-Authenticate", s); - response.setStatus(401); - } - } catch (SWORDErrorException see) { - // Get the details and send the right SWORD error document - log.error(see.toString()); - this.makeErrorDocument(see.getErrorURI(), - see.getStatus(), - see.getDescription(), - request, - response); - return; - } catch (SWORDException se) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - log.error(se.toString()); - } catch (NoSuchAlgorithmException nsae) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - log.error(nsae.toString()); - } - - finally { - // Try deleting the temp file - if (filename != null) { - File f = new File(filename); - if (f != null && !f.delete()) + // Get the DepositResponse + DepositResponse dr = myRepository.doDeposit(d); + + // Echo back the user agent + if (request.getHeader(HttpHeaders.USER_AGENT) != null) { + dr.getEntry().setUserAgent(request.getHeader(HttpHeaders.USER_AGENT)); + } + + // Echo back the packaging format + if (request.getHeader(HttpHeaders.X_PACKAGING) != null) { + dr.getEntry().setPackaging(request.getHeader(HttpHeaders.X_PACKAGING)); + } + + // Print out the Deposit Response + response.setStatus(dr.getHttpResponse()); + if ((dr.getLocation() != null) && (!dr.getLocation().equals(""))) + { + response.setHeader("Location", dr.getLocation()); + } + response.setContentType("application/atom+xml; charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.write(dr.marshall()); + out.flush(); + } + } catch (SWORDAuthenticationException sae) { + // Ask for credentials again + if (authN.equals("Basic")) { + String s = "Basic realm=\"SWORD\""; + response.setHeader("WWW-Authenticate", s); + response.setStatus(401); + } + } catch (SWORDErrorException see) { + // Get the details and send the right SWORD error document + log.error(see.toString()); + this.makeErrorDocument(see.getErrorURI(), + see.getStatus(), + see.getDescription(), + request, + response); + return; + } catch (SWORDException se) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + log.error(se.toString()); + } catch (NoSuchAlgorithmException nsae) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + log.error(nsae.toString()); + } + + finally { + // Try deleting the temp file + if (filename != null) { + File f = new File(filename); + if (f != null && !f.delete()) { log.error("Unable to delete file: " + filename); } - } - } - } - - /** - * Utility method to construct a SWORDErrorDocumentTest - * - * @param errorURI The error URI to pass - * @param status The HTTP status to return - * @param summary The textual description to give the user - * @param request The HttpServletRequest object - * @param response The HttpServletResponse to send the error document to - * @throws IOException - */ - protected void makeErrorDocument(String errorURI, int status, String summary, - HttpServletRequest request, HttpServletResponse response) throws IOException - { - SWORDErrorDocument sed = new SWORDErrorDocument(errorURI); - Title title = new Title(); - title.setContent("ERROR"); - sed.setTitle(title); - Calendar calendar = Calendar.getInstance(); - String utcformat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - SimpleDateFormat zulu = new SimpleDateFormat(utcformat); - String serializeddate = zulu.format(calendar.getTime()); - sed.setUpdated(serializeddate); - Summary sum = new Summary(); - sum.setContent(summary); - sed.setSummary(sum); - if (request.getHeader(HttpHeaders.USER_AGENT) != null) { - sed.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT)); - } - response.setStatus(status); - response.setContentType("application/atom+xml; charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.write(sed.marshall().toXML()); - out.flush(); - } + } + } + } + + /** + * Utility method to construct a SWORDErrorDocumentTest + * + * @param errorURI The error URI to pass + * @param status The HTTP status to return + * @param summary The textual description to give the user + * @param request The HttpServletRequest object + * @param response The HttpServletResponse to send the error document to + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. + */ + protected void makeErrorDocument(String errorURI, int status, String summary, + HttpServletRequest request, HttpServletResponse response) + throws IOException + { + SWORDErrorDocument sed = new SWORDErrorDocument(errorURI); + Title title = new Title(); + title.setContent("ERROR"); + sed.setTitle(title); + Calendar calendar = Calendar.getInstance(); + String utcformat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + SimpleDateFormat zulu = new SimpleDateFormat(utcformat); + String serializeddate = zulu.format(calendar.getTime()); + sed.setUpdated(serializeddate); + Summary sum = new Summary(); + sum.setContent(summary); + sed.setSummary(sum); + if (request.getHeader(HttpHeaders.USER_AGENT) != null) { + sed.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT)); + } + response.setStatus(status); + response.setContentType("application/atom+xml; charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.write(sed.marshall().toXML()); + out.flush(); + } - /** - * Utility method to return the username and password (separated by a colon - * ':') - * - * @param request - * @return The username and password combination - */ - protected String getUsernamePassword(HttpServletRequest request) { - try { - String authHeader = request.getHeader("Authorization"); - if (authHeader != null) { - StringTokenizer st = new StringTokenizer(authHeader); - if (st.hasMoreTokens()) { - String basic = st.nextToken(); - if (basic.equalsIgnoreCase("Basic")) { - String credentials = st.nextToken(); - String userPass = new String(Base64 - .decodeBase64(credentials.getBytes())); - return userPass; - } - } - } - } catch (Exception e) { - log.debug(e.toString()); - } - return null; - } + /** + * Utility method to return the username and password (separated by a colon + * ':') + * + * @param request + * Servlet's HTTP request object. + * @return The username and password combination + */ + protected String getUsernamePassword(HttpServletRequest request) { + try { + String authHeader = request.getHeader("Authorization"); + if (authHeader != null) { + StringTokenizer st = new StringTokenizer(authHeader); + if (st.hasMoreTokens()) { + String basic = st.nextToken(); + if (basic.equalsIgnoreCase("Basic")) { + String credentials = st.nextToken(); + String userPass = new String(Base64 + .decodeBase64(credentials.getBytes())); + return userPass; + } + } + } + } catch (Exception e) { + log.debug(e.toString()); + } + return null; + } - /** - * Utility method to decide if we are using HTTP Basic authentication - * - * @return if HTTP Basic authentication is in use or not - */ - protected boolean authenticateWithBasic() { - return (authN.equalsIgnoreCase("Basic")); - } + /** + * Utility method to decide if we are using HTTP Basic authentication + * + * @return if HTTP Basic authentication is in use or not + */ + protected boolean authenticateWithBasic() { + return (authN.equalsIgnoreCase("Basic")); + } - /** - * Utility method to construct the URL called for this Servlet - * - * @param req The request object - * @return The URL - */ - protected static String getUrl(HttpServletRequest req) { - String reqUrl = req.getRequestURL().toString(); - String queryString = req.getQueryString(); - if (queryString != null) { - reqUrl += "?" + queryString; - } - return reqUrl; - } + /** + * Utility method to construct the URL called for this Servlet + * + * @param req The request object + * @return The URL + */ + protected static String getUrl(HttpServletRequest req) { + String reqUrl = req.getRequestURL().toString(); + String queryString = req.getQueryString(); + if (queryString != null) { + reqUrl += "?" + queryString; + } + return reqUrl; + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/server/DummyServer.java b/dspace-sword/src/main/java/org/purl/sword/server/DummyServer.java index 49300af011..5ee17e3c9d 100644 --- a/dspace-sword/src/main/java/org/purl/sword/server/DummyServer.java +++ b/dspace-sword/src/main/java/org/purl/sword/server/DummyServer.java @@ -56,184 +56,184 @@ import org.apache.log4j.Logger; */ public class DummyServer implements SWORDServer { - /** A counter to count submissions, so the response to a deposit can increment */ - private static int counter = 0; + /** A counter to count submissions, so the response to a deposit can increment */ + private static int counter = 0; /** Logger */ - private static Logger log = Logger.getLogger(ServiceDocumentServlet.class); + private static Logger log = Logger.getLogger(ServiceDocumentServlet.class); - /** - * Provides a dumb but plausible service document - it contains - * an anonymous workspace and collection, and one personalised - * for the onBehalfOf user. - * - * @param sdr The request - * @throws SWORDAuthenticationException If the credentials are bad - * @throws SWORDErrorException If something goes wrong, such as - */ - public ServiceDocument doServiceDocument(ServiceDocumentRequest sdr) + /** + * Provides a dumb but plausible service document - it contains + * an anonymous workspace and collection, and one personalised + * for the onBehalfOf user. + * + * @param sdr The request + * @throws SWORDAuthenticationException If the credentials are bad + * @throws SWORDErrorException If something goes wrong, such as + */ + public ServiceDocument doServiceDocument(ServiceDocumentRequest sdr) throws SWORDAuthenticationException, SWORDErrorException, SWORDException { - // Authenticate the user - String username = sdr.getUsername(); - String password = sdr.getPassword(); - if ((username != null) && (password != null) && - (((username.equals("")) && (password.equals(""))) || - (!username.equalsIgnoreCase(password))) ) { - // User not authenticated - throw new SWORDAuthenticationException("Bad credentials"); - } - - // Allow users to force the throwing of a SWORD error exception by setting - // the OBO user to 'error' - if ((sdr.getOnBehalfOf() != null) && (sdr.getOnBehalfOf().equals("error"))) { - // Throw the error exception - throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, "Mediated deposits not allowed"); - } - - // Create and return a dummy ServiceDocument - ServiceDocument document = new ServiceDocument(); - Service service = new Service("1.3", true, true); - document.setService(service); - log.debug("sdr.getLocation() is: " + sdr.getLocation()); - String location = sdr.getLocation().substring(0, sdr.getLocation().length() - 16); - log.debug("location is: " + location); + // Authenticate the user + String username = sdr.getUsername(); + String password = sdr.getPassword(); + if ((username != null) && (password != null) && + (((username.equals("")) && (password.equals(""))) || + (!username.equalsIgnoreCase(password))) ) { + // User not authenticated + throw new SWORDAuthenticationException("Bad credentials"); + } - if (sdr.getLocation().contains("?nested=")) { - Workspace workspace = new Workspace(); - workspace.setTitle("Nested service document workspace"); - Collection collection = new Collection(); - collection.setTitle("Nested collection: " + sdr.getLocation().substring(sdr.getLocation().indexOf('?') + 1)); - collection.setLocation(location + "/deposit/nested"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); - collection.addAccepts("application/zip"); - collection.addAccepts("application/xml"); - collection.setAbstract("A nested collection that users can deposit into"); - collection.setTreatment("This is a dummy server"); - collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); - workspace.addCollection(collection); - service.addWorkspace(workspace); - } else { - Workspace workspace = new Workspace(); - workspace.setTitle("Anonymous submitters workspace"); - Collection collection = new Collection(); - collection.setTitle("Anonymous submitters collection"); - collection.setLocation(location + "/deposit/anon"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); - collection.addAccepts("application/zip"); - collection.addAccepts("application/xml"); - collection.setAbstract("A collection that anonymous users can deposit into"); - collection.setTreatment("This is a dummy server"); - collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); - collection.setService(location + "/client/servicedocument?nested=anon"); - workspace.addCollection(collection); - collection = new Collection(); - collection.setTitle("Anonymous submitters other collection"); - collection.setLocation(location + "/deposit/anonymous"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); - collection.addAccepts("application/zip"); - collection.addAccepts("application/xml"); - collection.setAbstract("Another collection that anonymous users can deposit into"); - collection.setTreatment("This is a dummy server"); - collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); - workspace.addCollection(collection); - service.addWorkspace(workspace); - - if (sdr.getUsername() != null) { - workspace = new Workspace(); - workspace.setTitle("Authenticated workspace for " + username); - collection = new Collection(); - collection.setTitle("Authenticated collection for " + username); - collection.setLocation(location + "/deposit/" + username); - collection.addAccepts("application/zip"); - collection.addAccepts("application/xml"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.8f); - collection.setAbstract("A collection that " + username + " can deposit into"); - collection.setTreatment("This is a dummy server"); - collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); - collection.setService(location + "/client/servicedocument?nested=authenticated"); - workspace.addCollection(collection); - collection = new Collection(); - collection.setTitle("Second authenticated collection for " + username); - collection.setLocation(location + "/deposit/" + username + "-2"); - collection.addAccepts("application/zip"); - collection.addAccepts("application/xml"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.123f); - collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); - collection.setAbstract("A collection that " + username + " can deposit into"); - collection.setTreatment("This is a dummy server"); - collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); - workspace.addCollection(collection); - } - service.addWorkspace(workspace); - } - - String onBehalfOf = sdr.getOnBehalfOf(); - if ((onBehalfOf != null) && (!onBehalfOf.equals(""))) { - Workspace workspace = new Workspace(); - workspace.setTitle("Personal workspace for " + onBehalfOf); - Collection collection = new Collection(); - collection.setTitle("Personal collection for " + onBehalfOf); - collection.setLocation(location + "/deposit?user=" + onBehalfOf); - collection.addAccepts("application/zip"); - collection.addAccepts("application/xml"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); - collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.8f); - collection.setAbstract("An abstract goes in here"); - collection.setCollectionPolicy("A collection policy"); - collection.setMediation(true); - collection.setTreatment("treatment in here too"); - workspace.addCollection(collection); - service.addWorkspace(workspace); - } - - return document; - } + // Allow users to force the throwing of a SWORD error exception by setting + // the OBO user to 'error' + if ((sdr.getOnBehalfOf() != null) && (sdr.getOnBehalfOf().equals("error"))) { + // Throw the error exception + throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, "Mediated deposits not allowed"); + } + + // Create and return a dummy ServiceDocument + ServiceDocument document = new ServiceDocument(); + Service service = new Service("1.3", true, true); + document.setService(service); + log.debug("sdr.getLocation() is: " + sdr.getLocation()); + String location = sdr.getLocation().substring(0, sdr.getLocation().length() - 16); + log.debug("location is: " + location); + + if (sdr.getLocation().contains("?nested=")) { + Workspace workspace = new Workspace(); + workspace.setTitle("Nested service document workspace"); + Collection collection = new Collection(); + collection.setTitle("Nested collection: " + sdr.getLocation().substring(sdr.getLocation().indexOf('?') + 1)); + collection.setLocation(location + "/deposit/nested"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); + collection.addAccepts("application/zip"); + collection.addAccepts("application/xml"); + collection.setAbstract("A nested collection that users can deposit into"); + collection.setTreatment("This is a dummy server"); + collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); + workspace.addCollection(collection); + service.addWorkspace(workspace); + } else { + Workspace workspace = new Workspace(); + workspace.setTitle("Anonymous submitters workspace"); + Collection collection = new Collection(); + collection.setTitle("Anonymous submitters collection"); + collection.setLocation(location + "/deposit/anon"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); + collection.addAccepts("application/zip"); + collection.addAccepts("application/xml"); + collection.setAbstract("A collection that anonymous users can deposit into"); + collection.setTreatment("This is a dummy server"); + collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); + collection.setService(location + "/client/servicedocument?nested=anon"); + workspace.addCollection(collection); + collection = new Collection(); + collection.setTitle("Anonymous submitters other collection"); + collection.setLocation(location + "/deposit/anonymous"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit"); + collection.addAccepts("application/zip"); + collection.addAccepts("application/xml"); + collection.setAbstract("Another collection that anonymous users can deposit into"); + collection.setTreatment("This is a dummy server"); + collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); + workspace.addCollection(collection); + service.addWorkspace(workspace); + + if (sdr.getUsername() != null) { + workspace = new Workspace(); + workspace.setTitle("Authenticated workspace for " + username); + collection = new Collection(); + collection.setTitle("Authenticated collection for " + username); + collection.setLocation(location + "/deposit/" + username); + collection.addAccepts("application/zip"); + collection.addAccepts("application/xml"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.8f); + collection.setAbstract("A collection that " + username + " can deposit into"); + collection.setTreatment("This is a dummy server"); + collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); + collection.setService(location + "/client/servicedocument?nested=authenticated"); + workspace.addCollection(collection); + collection = new Collection(); + collection.setTitle("Second authenticated collection for " + username); + collection.setLocation(location + "/deposit/" + username + "-2"); + collection.addAccepts("application/zip"); + collection.addAccepts("application/xml"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.123f); + collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); + collection.setAbstract("A collection that " + username + " can deposit into"); + collection.setTreatment("This is a dummy server"); + collection.setCollectionPolicy("No guarantee of service, or that deposits will be retained for any length of time."); + workspace.addCollection(collection); + } + service.addWorkspace(workspace); + } + + String onBehalfOf = sdr.getOnBehalfOf(); + if ((onBehalfOf != null) && (!onBehalfOf.equals(""))) { + Workspace workspace = new Workspace(); + workspace.setTitle("Personal workspace for " + onBehalfOf); + Collection collection = new Collection(); + collection.setTitle("Personal collection for " + onBehalfOf); + collection.setLocation(location + "/deposit?user=" + onBehalfOf); + collection.addAccepts("application/zip"); + collection.addAccepts("application/xml"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/METSDSpaceSIP"); + collection.addAcceptPackaging("http://purl.org/net/sword-types/bagit", 0.8f); + collection.setAbstract("An abstract goes in here"); + collection.setCollectionPolicy("A collection policy"); + collection.setMediation(true); + collection.setTreatment("treatment in here too"); + workspace.addCollection(collection); + service.addWorkspace(workspace); + } + + return document; + } - public DepositResponse doDeposit(Deposit deposit) - throws SWORDAuthenticationException, SWORDErrorException, SWORDException { - // Authenticate the user - String username = deposit.getUsername(); - String password = deposit.getPassword(); - if ((username != null) && (password != null) && - (((username.equals("")) && (password.equals(""))) || - (!username.equalsIgnoreCase(password))) ) { - // User not authenticated - throw new SWORDAuthenticationException("Bad credentials"); - } - - // Check this is a collection that takes obo deposits, else thrown an error - if (((deposit.getOnBehalfOf() != null) && (!deposit.getOnBehalfOf().equals(""))) && - (!deposit.getLocation().contains("deposit?user="))) { - throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, - "Mediated deposit not allowed to this collection"); - } - - // Get the filenames - StringBuffer filenames = new StringBuffer("Deposit file contained: "); - if (deposit.getFilename() != null) { - filenames.append("(filename = " + deposit.getFilename() + ") "); - } - if (deposit.getSlug() != null) { - filenames.append("(slug = " + deposit.getSlug() + ") "); - } + public DepositResponse doDeposit(Deposit deposit) + throws SWORDAuthenticationException, SWORDErrorException, SWORDException { + // Authenticate the user + String username = deposit.getUsername(); + String password = deposit.getPassword(); + if ((username != null) && (password != null) && + (((username.equals("")) && (password.equals(""))) || + (!username.equalsIgnoreCase(password))) ) { + // User not authenticated + throw new SWORDAuthenticationException("Bad credentials"); + } + + // Check this is a collection that takes obo deposits, else thrown an error + if (((deposit.getOnBehalfOf() != null) && (!deposit.getOnBehalfOf().equals(""))) && + (!deposit.getLocation().contains("deposit?user="))) { + throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, + "Mediated deposit not allowed to this collection"); + } + + // Get the filenames + StringBuffer filenames = new StringBuffer("Deposit file contained: "); + if (deposit.getFilename() != null) { + filenames.append("(filename = " + deposit.getFilename() + ") "); + } + if (deposit.getSlug() != null) { + filenames.append("(slug = " + deposit.getSlug() + ") "); + } ZipInputStream zip = null; - try { + try { File depositFile = deposit.getFile(); - zip = new ZipInputStream(new FileInputStream(depositFile)); + zip = new ZipInputStream(new FileInputStream(depositFile)); ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { filenames.append(" ").append(ze.toString()); } - } catch (IOException ioe) { - throw new SWORDException("Failed to open deposited zip file", ioe, ErrorCodes.ERROR_CONTENT); - } finally { + } catch (IOException ioe) { + throw new SWORDException("Failed to open deposited zip file", ioe, ErrorCodes.ERROR_CONTENT); + } finally { if (zip != null) { try @@ -246,103 +246,103 @@ public class DummyServer implements SWORDServer { } } } - - // Handle the deposit - if (!deposit.isNoOp()) { - counter++; - } - DepositResponse dr = new DepositResponse(Deposit.CREATED); - SWORDEntry se = new SWORDEntry(); - - Title t = new Title(); - t.setContent("DummyServer Deposit: #" + counter); - se.setTitle(t); - - se.addCategory("Category"); - - if (deposit.getSlug() != null) { - se.setId(deposit.getSlug() + " - ID: " + counter); - } else { - se.setId("ID: " + counter); - } - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - TimeZone utc = TimeZone.getTimeZone("UTC"); - sdf.setTimeZone (utc); - String milliFormat = sdf.format(new Date()); - se.setUpdated(milliFormat); - - Summary s = new Summary(); - s.setContent(filenames.toString()); - se.setSummary(s); - Author a = new Author(); - if (username != null) { - a.setName(username); - } else { - a.setName("unknown"); - } - se.addAuthors(a); - - Link em = new Link(); - em.setRel("edit-media"); - em.setHref("http://www.myrepository.ac.uk/sdl/workflow/my deposit"); - se.addLink(em); - - Link e = new Link(); - e.setRel("edit"); - e.setHref("http://www.myrepository.ac.uk/sdl/workflow/my deposit.atom"); - se.addLink(e); - - if (deposit.getOnBehalfOf() != null) { - Contributor c = new Contributor(); - c.setName(deposit.getOnBehalfOf()); - c.setEmail(deposit.getOnBehalfOf() + "@myrepository.ac.uk"); - se.addContributor(c); - } - - Generator generator = new Generator(); - generator.setContent("Stuart's Dummy SWORD Server"); - generator.setUri("http://dummy-sword-server.example.com/"); - generator.setVersion("1.3"); - se.setGenerator(generator); - - Content content = new Content(); - try { - content.setType("application/zip"); - } catch (InvalidMediaTypeException ex) { - ex.printStackTrace(); - } - content.setSource("http://www.myrepository.ac.uk/sdl/uploads/upload-" + counter + ".zip"); - se.setContent(content); - - se.setTreatment("Short back and sides"); - - if (deposit.isVerbose()) { - se.setVerboseDescription("I've done a lot of hard work to get this far!"); - } - - se.setNoOp(deposit.isNoOp()); - - dr.setEntry(se); - - dr.setLocation("http://www.myrepository.ac.uk/atom/" + counter); - - return dr; - } - - public AtomDocumentResponse doAtomDocument(AtomDocumentRequest adr) + + // Handle the deposit + if (!deposit.isNoOp()) { + counter++; + } + DepositResponse dr = new DepositResponse(Deposit.CREATED); + SWORDEntry se = new SWORDEntry(); + + Title t = new Title(); + t.setContent("DummyServer Deposit: #" + counter); + se.setTitle(t); + + se.addCategory("Category"); + + if (deposit.getSlug() != null) { + se.setId(deposit.getSlug() + " - ID: " + counter); + } else { + se.setId("ID: " + counter); + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + TimeZone utc = TimeZone.getTimeZone("UTC"); + sdf.setTimeZone (utc); + String milliFormat = sdf.format(new Date()); + se.setUpdated(milliFormat); + + Summary s = new Summary(); + s.setContent(filenames.toString()); + se.setSummary(s); + Author a = new Author(); + if (username != null) { + a.setName(username); + } else { + a.setName("unknown"); + } + se.addAuthors(a); + + Link em = new Link(); + em.setRel("edit-media"); + em.setHref("http://www.myrepository.ac.uk/sdl/workflow/my deposit"); + se.addLink(em); + + Link e = new Link(); + e.setRel("edit"); + e.setHref("http://www.myrepository.ac.uk/sdl/workflow/my deposit.atom"); + se.addLink(e); + + if (deposit.getOnBehalfOf() != null) { + Contributor c = new Contributor(); + c.setName(deposit.getOnBehalfOf()); + c.setEmail(deposit.getOnBehalfOf() + "@myrepository.ac.uk"); + se.addContributor(c); + } + + Generator generator = new Generator(); + generator.setContent("Stuart's Dummy SWORD Server"); + generator.setUri("http://dummy-sword-server.example.com/"); + generator.setVersion("1.3"); + se.setGenerator(generator); + + Content content = new Content(); + try { + content.setType("application/zip"); + } catch (InvalidMediaTypeException ex) { + ex.printStackTrace(); + } + content.setSource("http://www.myrepository.ac.uk/sdl/uploads/upload-" + counter + ".zip"); + se.setContent(content); + + se.setTreatment("Short back and sides"); + + if (deposit.isVerbose()) { + se.setVerboseDescription("I've done a lot of hard work to get this far!"); + } + + se.setNoOp(deposit.isNoOp()); + + dr.setEntry(se); + + dr.setLocation("http://www.myrepository.ac.uk/atom/" + counter); + + return dr; + } + + public AtomDocumentResponse doAtomDocument(AtomDocumentRequest adr) throws SWORDAuthenticationException, SWORDErrorException, SWORDException { - // Authenticate the user - String username = adr.getUsername(); - String password = adr.getPassword(); - if ((username != null) && (password != null) && - (((username.equals("")) && (password.equals(""))) || - (!username.equalsIgnoreCase(password))) ) { - // User not authenticated - throw new SWORDAuthenticationException("Bad credentials"); - } - - return new AtomDocumentResponse(HttpServletResponse.SC_OK); - } + // Authenticate the user + String username = adr.getUsername(); + String password = adr.getPassword(); + if ((username != null) && (password != null) && + (((username.equals("")) && (password.equals(""))) || + (!username.equalsIgnoreCase(password))) ) { + // User not authenticated + throw new SWORDAuthenticationException("Bad credentials"); + } + + return new AtomDocumentResponse(HttpServletResponse.SC_OK); + } } diff --git a/dspace-sword/src/main/java/org/purl/sword/server/SWORDServer.java b/dspace-sword/src/main/java/org/purl/sword/server/SWORDServer.java index beff3a16a6..33010de936 100644 --- a/dspace-sword/src/main/java/org/purl/sword/server/SWORDServer.java +++ b/dspace-sword/src/main/java/org/purl/sword/server/SWORDServer.java @@ -32,10 +32,10 @@ public interface SWORDServer { * * @param sdr The Service Document Request object * - * @exception SWORDAuthenticationException Thrown if the authentication fails - * @exception SWORDErrorException Thrown if there was an error with the input not matching + * @throws SWORDAuthenticationException Thrown if the authentication fails + * @throws SWORDErrorException Thrown if there was an error with the input not matching * the capabilities of the server - * @exception SWORDException Thrown in an un-handalable Exception occurs. + * @throws SWORDException Thrown in an un-handalable Exception occurs. * This will be dealt with by sending a HTTP 500 Server Exception * * @return The ServiceDocument representing the service document @@ -48,10 +48,10 @@ public interface SWORDServer { * * @param deposit The Deposit object * - * @exception SWORDAuthenticationException Thrown if the authentication fails - * @exception SWORDErrorException Thrown if there was an error with the input not matching + * @throws SWORDAuthenticationException Thrown if the authentication fails + * @throws SWORDErrorException Thrown if there was an error with the input not matching * the capabilities of the server - * @exception SWORDException Thrown if an un-handalable Exception occurs. + * @throws SWORDException Thrown if an un-handalable Exception occurs. * This will be dealt with by sending a HTTP 500 Server Exception * * @return The response to the deposit @@ -64,10 +64,10 @@ public interface SWORDServer { * * @param adr The Atom Document Request object * - * @exception SWORDAuthenticationException Thrown if the authentication fails - * @exception SWORDErrorException Thrown if there was an error with the input not matching + * @throws SWORDAuthenticationException Thrown if the authentication fails + * @throws SWORDErrorException Thrown if there was an error with the input not matching * the capabilities of the server - * @exception SWORDException Thrown if an un-handalable Exception occurs. + * @throws SWORDException Thrown if an un-handalable Exception occurs. * This will be dealt with by sending a HTTP 500 Server Exception * * @return The response to the atom document request diff --git a/dspace-sword/src/main/java/org/purl/sword/server/ServiceDocumentServlet.java b/dspace-sword/src/main/java/org/purl/sword/server/ServiceDocumentServlet.java index 3dfd6890fc..79bafbb718 100644 --- a/dspace-sword/src/main/java/org/purl/sword/server/ServiceDocumentServlet.java +++ b/dspace-sword/src/main/java/org/purl/sword/server/ServiceDocumentServlet.java @@ -27,204 +27,233 @@ import org.purl.sword.base.ServiceDocumentRequest; /** * ServiceDocumentServlet - * + * * @author Stuart Lewis */ public class ServiceDocumentServlet extends HttpServlet { - /** The repository */ - private transient SWORDServer myRepository; + /** The repository */ + private transient SWORDServer myRepository; - /** Authentication type. */ - private String authN; + /** Authentication type. */ + private String authN; - /** Maximum file upload size in kB **/ - private int maxUploadSize; + /** Maximum file upload size in kB **/ + private int maxUploadSize; - /** Logger */ - private static final Logger log = Logger.getLogger(ServiceDocumentServlet.class); + /** Logger */ + private static final Logger log = Logger.getLogger(ServiceDocumentServlet.class); /** - * Initialise the servlet. - * - * @throws ServletException if the server class cannot be instantiated. - */ + * Initialise the servlet. + * + * @throws ServletException if the server class cannot be instantiated. + */ @Override - public void init() throws ServletException { + public void init() throws ServletException { // Instantiate the correct SWORD Server class - String className = getServletContext().getInitParameter("sword-server-class"); - if (className == null) { - log.fatal("Unable to read value of 'sword-server-class' from Servlet context"); + String className = getServletContext().getInitParameter("sword-server-class"); + if (className == null) { + log.fatal("Unable to read value of 'sword-server-class' from Servlet context"); throw new ServletException("Unable to read value of 'sword-server-class' from Servlet context"); - } else { - try { - myRepository = (SWORDServer) Class.forName(className) - .newInstance(); - log.info("Using " + className + " as the SWORDServer"); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { - log.fatal("Unable to instantiate class from 'server-class': " - + className); - throw new ServletException( - "Unable to instantiate class from 'server-class': " - + className, e); - } - } + } + else + { + try + { + myRepository = (SWORDServer) Class.forName(className) + .newInstance(); + log.info("Using " + className + " as the SWORDServer"); + } + catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) + { + log.fatal("Unable to instantiate class from 'server-class': " + + className); + throw new ServletException( + "Unable to instantiate class from 'server-class': " + + className, e); + } + } - // Set the authentication method - authN = getServletContext().getInitParameter("authentication-method"); - if ((authN == null) || ("".equals(authN))) { - authN = "None"; - } - log.info("Authentication type set to: " + authN); - - String maxUploadSizeStr = getServletContext().getInitParameter("maxUploadSize"); - if ((maxUploadSizeStr == null) || - (maxUploadSizeStr.equals("")) || - (maxUploadSizeStr.equals("-1"))) { - maxUploadSize = -1; - log.warn("No maxUploadSize set, so setting max file upload size to unlimited."); - } else { - try { - maxUploadSize = Integer.parseInt(maxUploadSizeStr); - log.info("Setting max file upload size to " + maxUploadSize); - } catch (NumberFormatException nfe) { - maxUploadSize = -1; - log.warn("maxUploadSize not a number, so setting max file upload size to unlimited."); - } - } - } + // Set the authentication method + authN = getServletContext().getInitParameter("authentication-method"); + if ((authN == null) || ("".equals(authN))) { + authN = "None"; + } + log.info("Authentication type set to: " + authN); - /** - * Process the GET request. + String maxUploadSizeStr = getServletContext().getInitParameter("maxUploadSize"); + if ((maxUploadSizeStr == null) || + (maxUploadSizeStr.equals("")) || + (maxUploadSizeStr.equals("-1"))) { + maxUploadSize = -1; + log.warn("No maxUploadSize set, so setting max file upload size to unlimited."); + } + else + { + try { + maxUploadSize = Integer.parseInt(maxUploadSizeStr); + log.info("Setting max file upload size to " + maxUploadSize); + } + catch (NumberFormatException nfe) + { + maxUploadSize = -1; + log.warn("maxUploadSize not a number, so setting max file upload size to unlimited."); + } + } + } + + /** + * Process the GET request. * @param request the request. * @param response the response. * @throws javax.servlet.ServletException passed through. * @throws java.io.IOException passed through. - */ + */ @Override - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - // Create the ServiceDocumentRequest - ServiceDocumentRequest sdr = new ServiceDocumentRequest(); + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + // Create the ServiceDocumentRequest + ServiceDocumentRequest sdr = new ServiceDocumentRequest(); // Are there any authentication details? - String usernamePassword = getUsernamePassword(request); - if ((usernamePassword != null) && (!usernamePassword.equals(""))) { - int p = usernamePassword.indexOf(':'); - if (p != -1) { - sdr.setUsername(usernamePassword.substring(0, p)); - sdr.setPassword(usernamePassword.substring(p + 1)); - } - } else if (authenticateWithBasic()) { - String s = "Basic realm=\"SWORD\""; - response.setHeader("WWW-Authenticate", s); - response.setStatus(401); - return; - } + String usernamePassword = getUsernamePassword(request); + if ((usernamePassword != null) && (!usernamePassword.equals(""))) { + int p = usernamePassword.indexOf(':'); + if (p != -1) { + sdr.setUsername(usernamePassword.substring(0, p)); + sdr.setPassword(usernamePassword.substring(p + 1)); + } + } + else if (authenticateWithBasic()) + { + String s = "Basic realm=\"SWORD\""; + response.setHeader("WWW-Authenticate", s); + response.setStatus(401); + return; + } - // Set the x-on-behalf-of header - sdr.setOnBehalfOf(request.getHeader(HttpHeaders.X_ON_BEHALF_OF)); + // Set the x-on-behalf-of header + sdr.setOnBehalfOf(request.getHeader(HttpHeaders.X_ON_BEHALF_OF)); - // Set the IP address - sdr.setIPAddress(request.getRemoteAddr()); + // Set the IP address + sdr.setIPAddress(request.getRemoteAddr()); - // Set the deposit location - sdr.setLocation(getUrl(request)); + // Set the deposit location + sdr.setLocation(getUrl(request)); - // Get the ServiceDocument - try { - ServiceDocument sd = myRepository.doServiceDocument(sdr); - if ((sd.getService().getMaxUploadSize() == -1) && (maxUploadSize != -1)) { - sd.getService().setMaxUploadSize(maxUploadSize); - } - - // Print out the Service Document - response.setContentType("application/atomsvc+xml; charset=UTF-8"); - PrintWriter out = response.getWriter(); - out.write(sd.marshall()); - out.flush(); - } catch (SWORDAuthenticationException sae) { - if (authN.equals("Basic")) { - String s = "Basic realm=\"SWORD\""; - response.setHeader("WWW-Authenticate", s); - response.setStatus(401); - } - } catch (SWORDErrorException see) { - // Return the relevant HTTP status code - response.sendError(see.getStatus(), see.getDescription()); - } catch (SWORDException se) { + // Get the ServiceDocument + try { + ServiceDocument sd = myRepository.doServiceDocument(sdr); + if ((sd.getService().getMaxUploadSize() == -1) && (maxUploadSize != -1)) + { + sd.getService().setMaxUploadSize(maxUploadSize); + } + + // Print out the Service Document + response.setContentType("application/atomsvc+xml; charset=UTF-8"); + PrintWriter out = response.getWriter(); + out.write(sd.marshall()); + out.flush(); + } + catch (SWORDAuthenticationException sae) + { + if (authN.equals("Basic")) { + String s = "Basic realm=\"SWORD\""; + response.setHeader("WWW-Authenticate", s); + response.setStatus(401); + } + } + catch (SWORDErrorException see) + { + // Return the relevant HTTP status code + response.sendError(see.getStatus(), see.getDescription()); + } + catch (SWORDException se) + { log.error("Internal error", se); - // Throw a HTTP 500 - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, se.getMessage()); - } - } + // Throw a HTTP 500 + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, se.getMessage()); + } + } - /** - * Process the post request. This will return an unimplemented response. + /** + * Process the post request. This will return an unimplemented response. * @param request the request. * @param response the response. * @throws javax.servlet.ServletException passed through. * @throws java.io.IOException passed through. - */ + */ @Override - protected void doPost(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - // Send a '501 Not Implemented' - response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); - } + protected void doPost(HttpServletRequest request, + HttpServletResponse response) + throws ServletException, IOException + { + // Send a '501 Not Implemented' + response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); + } - /** - * Utility method to return the username and password (separated by a colon - * ':') - * - * @param request - * @return The username and password combination - */ - private String getUsernamePassword(HttpServletRequest request) { - try { - String authHeader = request.getHeader("Authorization"); - if (authHeader != null) { - StringTokenizer st = new StringTokenizer(authHeader); - if (st.hasMoreTokens()) { - String basic = st.nextToken(); - if (basic.equalsIgnoreCase("Basic")) { - String credentials = st.nextToken(); - String userPass = new String(Base64 - .decodeBase64(credentials.getBytes())); - return userPass; - } - } - } - } catch (Exception e) { - log.debug(e.toString()); - } - return null; - } + /** + * Utility method to return the username and password (separated by a colon + * ':') + * + * @param request + * @return The username and password combination + */ + private String getUsernamePassword(HttpServletRequest request) { + try + { + String authHeader = request.getHeader("Authorization"); + if (authHeader != null) + { + StringTokenizer st = new StringTokenizer(authHeader); + if (st.hasMoreTokens()) + { + String basic = st.nextToken(); + if (basic.equalsIgnoreCase("Basic")) + { + String credentials = st.nextToken(); + String userPass = new String(Base64 + .decodeBase64(credentials.getBytes())); + return userPass; + } + } + } + } + catch (Exception e) + { + log.debug(e.toString()); + } + return null; + } - /** - * Utility method to decide if we are using HTTP Basic authentication - * - * @return if HTTP Basic authentication is in use or not - */ - private boolean authenticateWithBasic() { - return (authN.equalsIgnoreCase("Basic")); - } - - /** - * Utility method to construct the URL called for this Servlet - * - * @param req The request object - * @return The URL - */ - private static String getUrl(HttpServletRequest req) { - String reqUrl = req.getRequestURL().toString(); - String queryString = req.getQueryString(); + /** + * Utility method to decide if we are using HTTP Basic authentication + * + * @return if HTTP Basic authentication is in use or not + */ + private boolean authenticateWithBasic() + { + return (authN.equalsIgnoreCase("Basic")); + } + + /** + * Utility method to construct the URL called for this Servlet + * + * @param req The request object + * @return The URL + */ + private static String getUrl(HttpServletRequest req) + { + String reqUrl = req.getRequestURL().toString(); + String queryString = req.getQueryString(); log.debug("Requested url is: " + reqUrl); - if (queryString != null) { - reqUrl += "?" + queryString; - } + if (queryString != null) + { + reqUrl += "?" + queryString; + } log.debug("Requested url with Query String is: " + reqUrl); - return reqUrl; - } + return reqUrl; + } } diff --git a/dspace-swordv2/pom.xml b/dspace-swordv2/pom.xml index 783f03f755..138e9435a3 100644 --- a/dspace-swordv2/pom.xml +++ b/dspace-swordv2/pom.xml @@ -13,7 +13,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/AbstractSwordContentIngester.java b/dspace-swordv2/src/main/java/org/dspace/sword2/AbstractSwordContentIngester.java index 04c6f0b3f0..b31956e32c 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/AbstractSwordContentIngester.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/AbstractSwordContentIngester.java @@ -27,14 +27,14 @@ import java.util.StringTokenizer; public abstract class AbstractSwordContentIngester implements SwordContentIngester { - public static final Logger log = Logger - .getLogger(AbstractSwordContentIngester.class); + public static final Logger log = Logger.getLogger( + AbstractSwordContentIngester.class); - protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory - .getInstance().getBitstreamFormatService(); + protected BitstreamFormatService bitstreamFormatService = + ContentServiceFactory.getInstance().getBitstreamFormatService(); - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); public DepositResult ingest(Context context, Deposit deposit, DSpaceObject dso, VerboseDescription verboseDescription) @@ -53,12 +53,12 @@ public abstract class AbstractSwordContentIngester if (dso instanceof Collection) { return this.ingestToCollection(context, deposit, (Collection) dso, - verboseDescription, result); + verboseDescription, result); } else if (dso instanceof Item) { return this.ingestToItem(context, deposit, (Item) dso, - verboseDescription, result); + verboseDescription, result); } return null; } @@ -110,31 +110,35 @@ public abstract class AbstractSwordContentIngester * the field in which to store this metadata in the configuration * sword.updated.field * - * * @param context + * The relevant DSpace Context. * @param item + * target item + * @param verboseDescription + * The description. * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ protected void setUpdatedDate(Context context, Item item, VerboseDescription verboseDescription) throws DSpaceSwordException { String field = ConfigurationManager - .getProperty("swordv2-server", "updated.field"); + .getProperty("swordv2-server", "updated.field"); if (field == null || "".equals(field)) { throw new DSpaceSwordException( - "No configuration, or configuration is invalid for: sword.updated.field"); + "No configuration, or configuration is invalid for: sword.updated.field"); } MetadataFieldInfo info = this.configToDC(field, null); try { itemService.clearMetadata(context, item, info.schema, info.element, - info.qualifier, Item.ANY); + info.qualifier, Item.ANY); DCDate date = new DCDate(new Date()); itemService.addMetadata(context, item, info.schema, info.element, - info.qualifier, null, date.toString()); + info.qualifier, null, date.toString()); } catch (SQLException e) { @@ -142,8 +146,8 @@ public abstract class AbstractSwordContentIngester throw new DSpaceSwordException(e); } - verboseDescription - .append("Updated date added to response from item metadata where available"); + verboseDescription.append( + "Updated date added to response from item metadata where available"); } /** @@ -152,11 +156,16 @@ public abstract class AbstractSwordContentIngester * field in which to store this metadata in the configuration * sword.slug.field * - * * @param context + * The relevant DSpace Context. * @param item + * target item * @param slugVal + * slug value + * @param verboseDescription + * The description. * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ protected void setSlug(Context context, Item item, String slugVal, VerboseDescription verboseDescription) @@ -169,20 +178,20 @@ public abstract class AbstractSwordContentIngester } String field = ConfigurationManager - .getProperty("swordv2-server", "slug.field"); + .getProperty("swordv2-server", "slug.field"); if (field == null || "".equals(field)) { throw new DSpaceSwordException( - "No configuration, or configuration is invalid for: sword.slug.field"); + "No configuration, or configuration is invalid for: sword.slug.field"); } MetadataFieldInfo info = this.configToDC(field, null); try { itemService.clearMetadata(context, item, info.schema, info.element, - info.qualifier, Item.ANY); + info.qualifier, Item.ANY); itemService.addMetadata(context, item, info.schema, info.element, - info.qualifier, null, slugVal); + info.qualifier, null, slugVal); } catch (SQLException e) { diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/AtomCollectionGenerator.java b/dspace-swordv2/src/main/java/org/dspace/sword2/AtomCollectionGenerator.java index 6b98e720c5..d0940d4e2c 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/AtomCollectionGenerator.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/AtomCollectionGenerator.java @@ -22,9 +22,16 @@ public interface AtomCollectionGenerator /** * Build the ATOM Collection which represents the given DSpace Object. * + * @param context + * The relevant DSpace Context. * @param dso + * target DSpace object + * @param config + * SWORD configuration + * @return ATOM Collection which represents the given DSpace Object * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public SwordCollection buildCollection(Context context, DSpaceObject dso, - SwordConfigurationDSpace config) throws DSpaceSwordException; + SwordConfigurationDSpace config) throws DSpaceSwordException; } diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/BinaryContentIngester.java b/dspace-swordv2/src/main/java/org/dspace/sword2/BinaryContentIngester.java index 373c9f242f..9d70abce77 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/BinaryContentIngester.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/BinaryContentIngester.java @@ -31,14 +31,14 @@ import java.util.List; public class BinaryContentIngester extends AbstractSwordContentIngester { - protected WorkspaceItemService workspaceItemService = ContentServiceFactory - .getInstance().getWorkspaceItemService(); + protected WorkspaceItemService workspaceItemService = + ContentServiceFactory.getInstance().getWorkspaceItemService(); - protected BundleService bundleService = ContentServiceFactory.getInstance() - .getBundleService(); + protected BundleService bundleService = + ContentServiceFactory.getInstance().getBundleService(); - protected BitstreamService bitstreamService = ContentServiceFactory - .getInstance().getBitstreamService(); + protected BitstreamService bitstreamService = + ContentServiceFactory.getInstance().getBitstreamService(); public DepositResult ingestToCollection(Context context, Deposit deposit, Collection collection, VerboseDescription verboseDescription, @@ -66,11 +66,10 @@ public class BinaryContentIngester extends AbstractSwordContentIngester item = wsi.getItem(); } - Bitstream bs = itemService - .createSingleBitstream(context, deposit.getInputStream(), - item); - BitstreamFormat format = this - .getFormat(context, deposit.getFilename()); + Bitstream bs = itemService.createSingleBitstream( + context, deposit.getInputStream(), item); + BitstreamFormat format = this.getFormat( + context, deposit.getFilename()); bs.setName(context, deposit.getFilename()); bs.setFormat(context, format); bitstreamService.update(context, bs); @@ -78,10 +77,10 @@ public class BinaryContentIngester extends AbstractSwordContentIngester // now we have an item in the workspace, and we need to consider adding some metadata to it, // but since the binary file didn't contain anything, what do we do? itemService.addMetadata(context, item, "dc", "title", null, null, - "Untitled: " + deposit.getFilename()); - itemService - .addMetadata(context, item, "dc", "description", null, null, - "Zip file deposted by SWORD without accompanying metadata"); + "Untitled: " + deposit.getFilename()); + itemService.addMetadata( + context, item, "dc", "description", null, null, + "Zip file deposted by SWORD without accompanying metadata"); // update the item metadata to inclue the current time as // the updated date @@ -100,9 +99,8 @@ public class BinaryContentIngester extends AbstractSwordContentIngester context.restoreAuthSystemState(); verboseDescription.append("Ingest successful"); - verboseDescription - .append("Item created with internal identifier: " + - item.getID()); + verboseDescription.append( + "Item created with internal identifier: " + item.getID()); result.setItem(item); result.setTreatment(this.getTreatment()); @@ -192,13 +190,14 @@ public class BinaryContentIngester extends AbstractSwordContentIngester * The human readable description of the treatment this ingester has * put the deposit through * - * @return + * @return human readable description * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ private String getTreatment() throws DSpaceSwordException { return "The package has been ingested and unpacked into the item. Template metadata for " + - "the collection has been used, and a default title with the name of the file has " + - "been set"; + "the collection has been used, and a default title with the name of the file has " + + "been set"; } } diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionCollectionGenerator.java b/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionCollectionGenerator.java index 32838e5fe0..8859cb3c49 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionCollectionGenerator.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionCollectionGenerator.java @@ -29,18 +29,21 @@ import java.util.List; */ public class CollectionCollectionGenerator implements AtomCollectionGenerator { - private static Logger log = Logger - .getLogger(CommunityCollectionGenerator.class); + private static Logger log = Logger.getLogger( + CommunityCollectionGenerator.class); - protected CollectionService collectionService = ContentServiceFactory - .getInstance().getCollectionService(); + protected CollectionService collectionService = + ContentServiceFactory.getInstance().getCollectionService(); /** * Build the collection for the given DSpaceObject. In this implementation, * if the object is not a DSpace Collection, it will throw DSpaceSwordException - * @param dso + * @param context + * The relevant DSpace Context. + * @param dso DSpace object * @return the SWORD ATOM collection * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public SwordCollection buildCollection(Context context, DSpaceObject dso, SwordConfigurationDSpace swordConfig) @@ -49,9 +52,9 @@ public class CollectionCollectionGenerator implements AtomCollectionGenerator if (!(dso instanceof org.dspace.content.Collection)) { log.error( - "buildCollection passed argument which is not of type Collection"); + "buildCollection passed argument which is not of type Collection"); throw new DSpaceSwordException( - "Incorrect ATOMCollectionGenerator instantiated"); + "Incorrect ATOMCollectionGenerator instantiated"); } // get the things we need out of the service @@ -127,8 +130,8 @@ public class CollectionCollectionGenerator implements AtomCollectionGenerator // should we offer the items in the collection up as deposit // targets? - boolean itemService = ConfigurationManager - .getBooleanProperty("sword.expose-items"); + boolean itemService = ConfigurationManager.getBooleanProperty( + "sword.expose-items"); if (itemService) { String subService = urlManager.constructSubServiceUrl(col); diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionListManagerDSpace.java b/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionListManagerDSpace.java index b3b3e7e7dc..f56edb5732 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionListManagerDSpace.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/CollectionListManagerDSpace.java @@ -52,7 +52,7 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI SwordUrlManager urlManager = config.getUrlManager(context, config); Collection collection = urlManager - .getCollection(context, colIRI.toString()); + .getCollection(context, colIRI.toString()); if (collection == null) { throw new SwordError(404); @@ -80,8 +80,8 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI throws DSpaceSwordException { SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig; - SwordUrlManager urlManager = config - .getUrlManager(sc.getContext(), config); + SwordUrlManager urlManager = config.getUrlManager( + sc.getContext(), config); Abdera abdera = new Abdera(); Feed feed = abdera.newFeed(); @@ -91,11 +91,11 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI Entry entry = feed.addEntry(); entry.setId(urlManager.getEditIRI(item).toString()); String title = this.stringMetadata(item, ConfigurationManager - .getProperty("swordv2-server", "title.field")); + .getProperty("swordv2-server", "title.field")); title = title == null ? "Untitled" : title; entry.setTitle(title); - entry.addLink(urlManager.getContentUrl(item).toString(), - "edit-media"); + entry.addLink( + urlManager.getContentUrl(item).toString(), "edit-media"); } return feed; @@ -108,13 +108,13 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI try { EPerson person = sc.getOnBehalfOf() != null ? - sc.getOnBehalfOf() : - sc.getAuthenticated(); + sc.getOnBehalfOf() : + sc.getAuthenticated(); List collectionItems = new ArrayList<>(); // first get the ones out of the archive Iterator items = itemService - .findBySubmitter(sc.getContext(), person); + .findBySubmitter(sc.getContext(), person); while (items.hasNext()) { Item item = items.next(); diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/ContainerManagerDSpace.java b/dspace-swordv2/src/main/java/org/dspace/sword2/ContainerManagerDSpace.java index f31f297b24..718e7e86f9 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/ContainerManagerDSpace.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/ContainerManagerDSpace.java @@ -35,14 +35,14 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { private static Logger log = Logger.getLogger(ContainerManagerDSpace.class); - protected AuthorizeService authorizeService = AuthorizeServiceFactory - .getInstance().getAuthorizeService(); + protected AuthorizeService authorizeService = + AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected WorkflowItemService workflowItemService = WorkflowServiceFactory - .getInstance().getWorkflowItemService(); + protected WorkflowItemService workflowItemService = + WorkflowServiceFactory.getInstance().getWorkflowItemService(); - protected WorkspaceItemService workspaceItemService = ContentServiceFactory - .getInstance().getWorkspaceItemService(); + protected WorkspaceItemService workspaceItemService = + ContentServiceFactory.getInstance().getWorkspaceItemService(); private VerboseDescription verboseDescription = new VerboseDescription(); @@ -81,7 +81,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { log.error("caught exception:", e); throw new SwordServerException( - "There was a problem determining the request type", e); + "There was a problem determining the request type", e); } finally { @@ -145,8 +145,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Date start = new Date(); // store up the verbose description, which we can then give back at the end if necessary - this.verboseDescription - .append("Initialising verbose replace of metadata"); + this.verboseDescription.append( + "Initialising verbose replace of metadata"); SwordContext sc = null; SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig; @@ -184,30 +184,28 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { oboEmail = sc.getOnBehalfOf().getEmail(); } - log.info(LogManager - .getHeader(context, "replace_failed_authorisation", - "user=" + - sc.getAuthenticated().getEmail() + - ",on_behalf_of=" + oboEmail)); + log.info(LogManager.getHeader( + context, "replace_failed_authorisation", + "user=" + sc.getAuthenticated().getEmail() + + ",on_behalf_of=" + oboEmail)); throw new SwordAuthException( "Cannot replace the given item with this context"); } // make a note of the authentication in the verbose string - this.verboseDescription.append("Authenticated user: " + - sc.getAuthenticated().getEmail()); + this.verboseDescription.append( + "Authenticated user: " + sc.getAuthenticated().getEmail()); if (sc.getOnBehalfOf() != null) { this.verboseDescription.append("Depositing on behalf of: " + - sc.getOnBehalfOf().getEmail()); + sc.getOnBehalfOf().getEmail()); } DepositResult result = null; try { - result = this - .doReplaceMetadata(sc, item, deposit, authCredentials, - config); + result = this.doReplaceMetadata( + sc, item, deposit, authCredentials, config); } catch (DSpaceSwordException | SwordError e) { @@ -229,15 +227,14 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI wfm.resolveState(context, deposit, result, this.verboseDescription); ReceiptGenerator genny = new ReceiptGenerator(); - DepositReceipt receipt = genny - .createReceipt(context, result, config); + DepositReceipt receipt = genny.createReceipt( + context, result, config); Date finish = new Date(); long delta = finish.getTime() - start.getTime(); - this.verboseDescription - .append("Total time for deposit processing: " + delta + - " ms"); + this.verboseDescription.append( + "Total time for deposit processing: " + delta + " ms"); this.addVerboseDescription(receipt, this.verboseDescription); // if something hasn't killed it already (allowed), then complete the transaction @@ -249,7 +246,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { log.error("caught exception:", e); throw new SwordServerException( - "There was a problem depositing the item", e); + "There was a problem depositing the item", e); } finally { @@ -270,8 +267,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Date start = new Date(); // store up the verbose description, which we can then give back at the end if necessary - this.verboseDescription - .append("Initialising verbose multipart replace"); + this.verboseDescription.append( + "Initialising verbose multipart replace"); SwordContext sc = null; SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig; @@ -285,8 +282,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI if (log.isDebugEnabled()) { - log.debug( - LogManager.getHeader(context, "sword_create_new", "")); + log.debug(LogManager.getHeader( + context, "sword_create_new", "")); } // get the deposit target @@ -311,29 +308,28 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { oboEmail = sc.getOnBehalfOf().getEmail(); } - log.info(LogManager - .getHeader(context, "deposit_failed_authorisation", - "user=" + - sc.getAuthenticated().getEmail() + - ",on_behalf_of=" + oboEmail)); + log.info(LogManager.getHeader(context, + "deposit_failed_authorisation", + "user=" + sc.getAuthenticated().getEmail() + + ",on_behalf_of=" + oboEmail)); throw new SwordAuthException( - "Cannot submit to the given collection with this context"); + "Cannot submit to the given collection with this context"); } // make a note of the authentication in the verbose string - this.verboseDescription.append("Authenticated user: " + - sc.getAuthenticated().getEmail()); + this.verboseDescription.append( + "Authenticated user: " + sc.getAuthenticated().getEmail()); if (sc.getOnBehalfOf() != null) { this.verboseDescription.append("Depositing on behalf of: " + - sc.getOnBehalfOf().getEmail()); + sc.getOnBehalfOf().getEmail()); } DepositResult result = null; try { - result = this.replaceFromMultipart(sc, item, deposit, - authCredentials, config); + result = this.replaceFromMultipart( + sc, item, deposit, authCredentials, config); } catch (DSpaceSwordException | SwordError e) { @@ -357,15 +353,14 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI wfm.resolveState(context, deposit, result, this.verboseDescription); ReceiptGenerator genny = new ReceiptGenerator(); - DepositReceipt receipt = genny - .createReceipt(context, result, config); + DepositReceipt receipt = genny.createReceipt( + context, result, config); Date finish = new Date(); long delta = finish.getTime() - start.getTime(); - this.verboseDescription - .append("Total time for deposit processing: " + delta + - " ms"); + this.verboseDescription.append( + "Total time for deposit processing: " + delta + " ms"); this.addVerboseDescription(receipt, this.verboseDescription); // if something hasn't killed it already (allowed), then complete the transaction @@ -377,7 +372,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { log.error("caught exception:", e); throw new SwordServerException( - "There was a problem depositing the item", e); + "There was a problem depositing the item", e); } finally { @@ -404,8 +399,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Date start = new Date(); // store up the verbose description, which we can then give back at the end if necessary - this.verboseDescription - .append("Initialising verbose replace of metadata"); + this.verboseDescription.append( + "Initialising verbose replace of metadata"); SwordContext sc = null; SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig; @@ -443,29 +438,28 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { oboEmail = sc.getOnBehalfOf().getEmail(); } - log.info(LogManager - .getHeader(context, "replace_failed_authorisation", - "user=" + - sc.getAuthenticated().getEmail() + - ",on_behalf_of=" + oboEmail)); + log.info(LogManager.getHeader( + context, "replace_failed_authorisation", + "user=" + sc.getAuthenticated().getEmail() + + ",on_behalf_of=" + oboEmail)); throw new SwordAuthException( - "Cannot replace the given item with this context"); + "Cannot replace the given item with this context"); } // make a note of the authentication in the verbose string this.verboseDescription.append("Authenticated user: " + - sc.getAuthenticated().getEmail()); + sc.getAuthenticated().getEmail()); if (sc.getOnBehalfOf() != null) { this.verboseDescription.append("Depositing on behalf of: " + - sc.getOnBehalfOf().getEmail()); + sc.getOnBehalfOf().getEmail()); } DepositResult result = null; try { - result = this.doAddMetadata(sc, item, deposit, authCredentials, - config); + result = this.doAddMetadata( + sc, item, deposit, authCredentials, config); } catch (DSpaceSwordException | SwordError e) { @@ -487,15 +481,14 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI wfm.resolveState(context, deposit, result, this.verboseDescription); ReceiptGenerator genny = new ReceiptGenerator(); - DepositReceipt receipt = genny - .createReceipt(context, result, config); + DepositReceipt receipt = genny.createReceipt( + context, result, config); Date finish = new Date(); long delta = finish.getTime() - start.getTime(); - this.verboseDescription - .append("Total time for deposit processing: " + delta + - " ms"); + this.verboseDescription.append( + "Total time for deposit processing: " + delta + " ms"); this.addVerboseDescription(receipt, this.verboseDescription); // if something hasn't killed it already (allowed), then complete the transaction @@ -507,7 +500,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { log.error("caught exception:", e); throw new SwordServerException( - "There was a problem depositing the item", e); + "There was a problem depositing the item", e); } finally { @@ -572,22 +565,21 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { oboEmail = sc.getOnBehalfOf().getEmail(); } - log.info(LogManager - .getHeader(context, "replace_failed_authorisation", - "user=" + - sc.getAuthenticated().getEmail() + - ",on_behalf_of=" + oboEmail)); + log.info(LogManager.getHeader(context, + "replace_failed_authorisation", + "user=" + sc.getAuthenticated().getEmail() + + ",on_behalf_of=" + oboEmail)); throw new SwordAuthException( - "Cannot delete the given item with this context"); + "Cannot delete the given item with this context"); } // make a note of the authentication in the verbose string this.verboseDescription.append("Authenticated user: " + - sc.getAuthenticated().getEmail()); + sc.getAuthenticated().getEmail()); if (sc.getOnBehalfOf() != null) { this.verboseDescription.append("Depositing on behalf of: " + - sc.getOnBehalfOf().getEmail()); + sc.getOnBehalfOf().getEmail()); } this.doContainerDelete(sc, item, authCredentials, config); @@ -595,9 +587,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Date finish = new Date(); long delta = finish.getTime() - start.getTime(); - this.verboseDescription - .append("Total time for deposit processing: " + delta + - " ms"); + this.verboseDescription.append( + "Total time for deposit processing: " + delta + " ms"); // if something hasn't killed it already (allowed), then complete the transaction sc.commit(); @@ -606,7 +597,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { log.error("caught exception:", e); throw new SwordServerException( - "There was a problem depositing the item", e); + "There was a problem depositing the item", e); } finally { @@ -626,8 +617,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Date start = new Date(); // store up the verbose description, which we can then give back at the end if necessary - this.verboseDescription - .append("Initialising verbose empty request (headers only)"); + this.verboseDescription.append( + "Initialising verbose empty request (headers only)"); SwordContext sc = null; SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig; @@ -639,8 +630,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI if (log.isDebugEnabled()) { - log.debug(LogManager - .getHeader(context, "sword_modify_by_headers", "")); + log.debug(LogManager.getHeader( + context, "sword_modify_by_headers", "")); } // get the deposit target @@ -666,22 +657,21 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { oboEmail = sc.getOnBehalfOf().getEmail(); } - log.info(LogManager - .getHeader(context, "modify_failed_authorisation", - "user=" + - sc.getAuthenticated().getEmail() + - ",on_behalf_of=" + oboEmail)); + log.info(LogManager.getHeader(context, + "modify_failed_authorisation", + "user=" + sc.getAuthenticated().getEmail() + + ",on_behalf_of=" + oboEmail)); throw new SwordAuthException( - "Cannot modify the given item with this context"); + "Cannot modify the given item with this context"); } // make a note of the authentication in the verbose string this.verboseDescription.append("Authenticated user: " + - sc.getAuthenticated().getEmail()); + sc.getAuthenticated().getEmail()); if (sc.getOnBehalfOf() != null) { this.verboseDescription.append("Modifying on behalf of: " + - sc.getOnBehalfOf().getEmail()); + sc.getOnBehalfOf().getEmail()); } DepositResult result = new DepositResult(); @@ -697,9 +687,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Date finish = new Date(); long delta = finish.getTime() - start.getTime(); - this.verboseDescription - .append("Total time for modify processing: " + delta + - " ms"); + this.verboseDescription.append( + "Total time for modify processing: " + delta + " ms"); this.addVerboseDescription(receipt, this.verboseDescription); // if something hasn't killed it already (allowed), then complete the transaction @@ -711,7 +700,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI { log.error("caught exception:", e); throw new SwordServerException( - "There was a problem depositing the item", e); + "There was a problem depositing the item", e); } finally { @@ -742,10 +731,10 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI .append("Loaded content ingester: " + sci.getClass().getName()); // obtain the relevant entry intester from the factory - SwordEntryIngester sei = SwordIngesterFactory - .getEntryInstance(context, deposit, item); - this.verboseDescription - .append("Loaded entry ingester: " + sei.getClass().getName()); + SwordEntryIngester sei = SwordIngesterFactory.getEntryInstance( + context, deposit, item); + this.verboseDescription.append( + "Loaded entry ingester: " + sei.getClass().getName()); try { @@ -767,31 +756,31 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI if (swordConfig.isEntryFirst()) { // do the entry deposit - result = sei.ingest(context, deposit, item, this.verboseDescription, - null, true); + result = sei.ingest( + context, deposit, item, this.verboseDescription, null, true); // do the content deposit - result = sci.ingest(context, deposit, item, this.verboseDescription, - result); - this.verboseDescription - .append("Archive ingest completed successfully"); + result = sci.ingest( + context, deposit, item, this.verboseDescription, result); + this.verboseDescription.append( + "Archive ingest completed successfully"); } else { // do the content deposit - result = sci.ingest(context, deposit, item, this.verboseDescription, - null); + result = sci.ingest( + context, deposit, item, this.verboseDescription, null); // do the entry deposit - result = sei.ingest(context, deposit, item, this.verboseDescription, - result, true); - this.verboseDescription - .append("Archive ingest completed successfully"); + result = sei.ingest( + context, deposit, item, this.verboseDescription, result, true); + this.verboseDescription.append( + "Archive ingest completed successfully"); } // store the originals (this code deals with the possibility that that's not required) - this.storeOriginals(swordConfig, context, this.verboseDescription, - deposit, result); + this.storeOriginals( + swordConfig, context, this.verboseDescription, deposit, result); return result; } @@ -806,20 +795,19 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Context context = swordContext.getContext(); // Obtain the relevant ingester from the factory - SwordEntryIngester si = SwordIngesterFactory - .getEntryInstance(context, deposit, null); - this.verboseDescription - .append("Loaded ingester: " + si.getClass().getName()); + SwordEntryIngester si = SwordIngesterFactory.getEntryInstance( + context, deposit, null); + this.verboseDescription.append( + "Loaded ingester: " + si.getClass().getName()); // do the deposit - DepositResult result = si - .ingest(context, deposit, item, this.verboseDescription, null, - true); + DepositResult result = si.ingest( + context, deposit, item, this.verboseDescription, null, true); this.verboseDescription.append("Replace completed successfully"); // store the originals (this code deals with the possibility that that's not required) - this.storeOriginals(swordConfig, context, this.verboseDescription, - deposit, result); + this.storeOriginals( + swordConfig, context, this.verboseDescription, deposit, result); return result; } @@ -830,8 +818,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException { - return this.doAddMetadata(swordContext, item, deposit, authCredentials, - swordConfig, null); + return this.doAddMetadata( + swordContext, item, deposit, authCredentials, swordConfig, null); } protected DepositResult doAddMetadata(SwordContext swordContext, Item item, @@ -849,20 +837,19 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI Context context = swordContext.getContext(); // Obtain the relevant ingester from the factory - SwordEntryIngester si = SwordIngesterFactory - .getEntryInstance(context, deposit, null); - this.verboseDescription - .append("Loaded ingester: " + si.getClass().getName()); + SwordEntryIngester si = SwordIngesterFactory.getEntryInstance( + context, deposit, null); + this.verboseDescription.append( + "Loaded ingester: " + si.getClass().getName()); // do the deposit - result = si - .ingest(context, deposit, item, this.verboseDescription, result, - false); + result = si.ingest( + context, deposit, item, this.verboseDescription, result, false); this.verboseDescription.append("Replace completed successfully"); // store the originals (this code deals with the possibility that that's not required) - this.storeOriginals(swordConfig, context, this.verboseDescription, - deposit, result); + this.storeOriginals( + swordConfig, context, this.verboseDescription, deposit, result); return result; } @@ -915,11 +902,10 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI throw new SwordError(404); } - this.verboseDescription - .append("Performing replace using edit-media URL: " + editUrl); - this.verboseDescription - .append("Location resolves to item with handle: " + - item.getHandle()); + this.verboseDescription.append( + "Performing replace using edit-media URL: " + editUrl); + this.verboseDescription.append( + "Location resolves to item with handle: " + item.getHandle()); return item; } diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/DSpaceSwordAPI.java b/dspace-swordv2/src/main/java/org/dspace/sword2/DSpaceSwordAPI.java index f56162289f..3385a89255 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/DSpaceSwordAPI.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/DSpaceSwordAPI.java @@ -54,17 +54,17 @@ public class DSpaceSwordAPI { private static Logger log = Logger.getLogger(DSpaceSwordAPI.class); - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); - protected BundleService bundleService = ContentServiceFactory.getInstance() - .getBundleService(); + protected BundleService bundleService = + ContentServiceFactory.getInstance().getBundleService(); - protected BitstreamService bitstreamService = ContentServiceFactory - .getInstance().getBitstreamService(); + protected BitstreamService bitstreamService = + ContentServiceFactory.getInstance().getBitstreamService(); - protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory - .getInstance().getBitstreamFormatService(); + protected BitstreamFormatService bitstreamFormatService = + ContentServiceFactory.getInstance().getBitstreamFormatService(); public SwordContext noAuthContext() throws DSpaceSwordException @@ -150,8 +150,8 @@ public class DSpaceSwordAPI if (components[1].trim().startsWith("q=")) { // "type;q" - q = Float.parseFloat(components[1].trim().substring( - 2)); //strip the "q=" from the start of the q value + //strip the "q=" from the start of the q value + q = Float.parseFloat(components[1].trim().substring( 2)); // if the q value is the highest one we've seen so far, record it if (q > highest_q) @@ -250,10 +250,10 @@ public class DSpaceSwordAPI .isAcceptableContentType(context, deposit.getMimeType(), dso)) { log.error("Unacceptable content type detected: " + - deposit.getMimeType() + " for object " + dso.getID()); + deposit.getMimeType() + " for object " + dso.getID()); throw new SwordError(UriRegistry.ERROR_CONTENT, - "Unacceptable content type in deposit request: " + - deposit.getMimeType()); + "Unacceptable content type in deposit request: " + + deposit.getMimeType()); } // determine if this is an acceptable packaging type for the deposit @@ -261,10 +261,10 @@ public class DSpaceSwordAPI if (!swordConfig.isAcceptedPackaging(deposit.getPackaging(), dso)) { log.error("Unacceptable packaging type detected: " + - deposit.getPackaging() + " for object " + dso.getID()); + deposit.getPackaging() + " for object " + dso.getID()); throw new SwordError(UriRegistry.ERROR_CONTENT, - "Unacceptable packaging type in deposit request: " + - deposit.getPackaging()); + "Unacceptable packaging type in deposit request: " + + deposit.getPackaging()); } } @@ -279,16 +279,16 @@ public class DSpaceSwordAPI { if (swordConfig.isKeepOriginal()) { - verboseDescription - .append("DSpace will store an original copy of the deposit, " + - "as well as ingesting the item into the archive"); + verboseDescription.append( + "DSpace will store an original copy of the deposit, " + + "as well as ingesting the item into the archive"); // in order to be allowed to add the file back to the item, we need to ignore authorisations // for a moment context.turnOffAuthorisationSystem(); - String bundleName = ConfigurationManager - .getProperty("swordv2-server", "bundle.name"); + String bundleName = ConfigurationManager.getProperty( + "swordv2-server", "bundle.name"); if (bundleName == null || "".equals(bundleName)) { bundleName = "SWORD"; @@ -306,23 +306,22 @@ public class DSpaceSwordAPI } if (swordBundle == null) { - swordBundle = bundleService - .create(context, item, bundleName); + swordBundle = bundleService.create( + context, item, bundleName); } if (deposit.isMultipart() || deposit.isEntryOnly()) { String entry = deposit.getSwordEntry().toString(); ByteArrayInputStream bais = new ByteArrayInputStream( - entry.getBytes()); - Bitstream entryBitstream = bitstreamService - .create(context, swordBundle, bais); + entry.getBytes()); + Bitstream entryBitstream = bitstreamService.create( + context, swordBundle, bais); - String fn = this - .createEntryFilename(context, deposit, true); + String fn = this.createEntryFilename(context, deposit, true); entryBitstream.setName(context, fn); entryBitstream.setDescription(context, - "Original SWORD entry document"); + "Original SWORD entry document"); BitstreamFormat bf = bitstreamFormatService .findByMIMEType(context, "application/xml"); @@ -366,7 +365,7 @@ public class DSpaceSwordAPI bitstream.setName(context, fn); bitstream.setDescription(context, - "Original SWORD deposit file"); + "Original SWORD deposit file"); BitstreamFormat bf = bitstreamFormatService .findByMIMEType(context, deposit.getMimeType()); @@ -382,9 +381,9 @@ public class DSpaceSwordAPI // shouldn't mess with it result.setOriginalDeposit(bitstream); } - verboseDescription - .append("Original deposit stored as " + fn + - ", in item bundle " + swordBundle); + verboseDescription.append( + "Original deposit stored as " + fn + + ", in item bundle " + swordBundle); } bundleService.update(context, swordBundle); @@ -405,9 +404,14 @@ public class DSpaceSwordAPI * Construct the most appropriate filename for the incoming deposit. * * @param context + * The relevant DSpace Context. * @param deposit + * deposit request * @param original + * use the ".original" filename suffix? + * @return filename for deposit * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String createFilename(Context context, Deposit deposit, boolean original) @@ -463,10 +467,17 @@ public class DSpaceSwordAPI } /** - * Store original package on disk and companion file containing SWORD headers as found in the deposit object - * Also write companion file with header info from the deposit object. + * Store original package on disk and companion file containing SWORD headers as found in the deposit object + * Also write companion file with header info from the deposit object. * * @param deposit + * deposit object to store as package + * @param auth + * authentication credentials + * @param config + * SWORD configuration + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ protected void storePackageAsFile(Deposit deposit, AuthCredentials auth, SwordConfigurationDSpace config) throws IOException @@ -477,7 +488,7 @@ public class DSpaceSwordAPI if (!dir.exists() || !dir.isDirectory()) { throw new IOException( - "Directory does not exist for writing packages on ingest error."); + "Directory does not exist for writing packages on ingest error."); } String filenameBase = @@ -508,10 +519,17 @@ public class DSpaceSwordAPI } /** - * Store original package on disk and companion file containing SWORD headers as found in the deposit object - * Also write companion file with header info from the deposit object. + * Store original package on disk and companion file containing SWORD headers as found in the deposit object + * Also write companion file with header info from the deposit object. * * @param deposit + * deposit object to store as package + * @param auth + * authentication credentials + * @param config + * SWORD configuration + * @throws IOException + * A general class of exceptions produced by failed or interrupted I/O operations. */ protected void storeEntryAsFile(Deposit deposit, AuthCredentials auth, SwordConfigurationDSpace config) throws IOException @@ -522,7 +540,7 @@ public class DSpaceSwordAPI if (!dir.exists() || !dir.isDirectory()) { throw new IOException( - "Directory does not exist for writing packages on ingest error."); + "Directory does not exist for writing packages on ingest error."); } String filenameBase = diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/ReceiptGenerator.java b/dspace-swordv2/src/main/java/org/dspace/sword2/ReceiptGenerator.java index 6baea052e3..b14c081a3e 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/ReceiptGenerator.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/ReceiptGenerator.java @@ -38,8 +38,8 @@ public class ReceiptGenerator /** logger */ private static Logger log = Logger.getLogger(ReceiptGenerator.class); - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance() .getItemService(); protected DepositReceipt createFileReceipt(Context context, DepositResult result, SwordConfigurationDSpace config) @@ -49,7 +49,7 @@ public class ReceiptGenerator DepositReceipt receipt = new DepositReceipt(); receipt.setLocation(new IRI(urlManager - .getActionableBitstreamUrl(result.getOriginalDeposit()))); + .getActionableBitstreamUrl(result.getOriginalDeposit()))); receipt.setEmpty(true); return receipt; @@ -75,7 +75,21 @@ public class ReceiptGenerator /** * Construct the entry * + * @param context + * The relevant DSpace Context. + * @param result + * deposit result + * @param config + * SWORD configuration + * @param mediaResourceLocation + * set media resource URL + * @return deposit receipt * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SwordError + * SWORD error per SWORD spec + * @throws SwordServerException + * thrown by SWORD server implementation */ protected DepositReceipt createReceipt(Context context, DepositResult result, SwordConfigurationDSpace config, @@ -86,17 +100,17 @@ public class ReceiptGenerator DepositReceipt receipt = new DepositReceipt(); receipt.setAtomStatementURI( - urlManager.getAtomStatementUri(result.getItem())); + urlManager.getAtomStatementUri(result.getItem())); receipt.setOREStatementURI( - urlManager.getOreStatementUri(result.getItem())); + urlManager.getOreStatementUri(result.getItem())); receipt.setEditIRI(urlManager.getEditIRI(result.getItem())); receipt.setSplashUri(urlManager.getSplashUrl(result.getItem())); receipt.setSwordEditIRI(urlManager.getEditIRI(result.getItem())); receipt.setTreatment(result.getTreatment()); - receipt.setContent(urlManager.getContentUrl(result.getItem()), - "application/zip"); - receipt.addEditMediaIRI(urlManager.getContentUrl(result.getItem()), - "application/zip"); + receipt.setContent( + urlManager.getContentUrl(result.getItem()), "application/zip"); + receipt.addEditMediaIRI( + urlManager.getContentUrl(result.getItem()), "application/zip"); receipt.setMediaFeedIRI(urlManager.getMediaFeedUrl(result.getItem())); receipt.setLastModified(result.getItem().getLastModified()); @@ -116,8 +130,8 @@ public class ReceiptGenerator { // note here that we don't provide an actionable url receipt.setOriginalDeposit( - urlManager.getActionableBitstreamUrl(od), - od.getFormat(context).getMIMEType()); + urlManager.getActionableBitstreamUrl(od), + od.getFormat(context).getMIMEType()); } Map derived = new HashMap(); @@ -128,7 +142,7 @@ public class ReceiptGenerator { // here we provide actionable urls for the parts of the resource derived.put(urlManager.getActionableBitstreamUrl(bs), - bs.getFormat(context).getMIMEType()); + bs.getFormat(context).getMIMEType()); } } receipt.setDerivedResources(derived); @@ -146,7 +160,7 @@ public class ReceiptGenerator // add the item's metadata SwordEntryDisseminator disseminator = SwordDisseminatorFactory - .getEntryInstance(); + .getEntryInstance(); disseminator.disseminate(context, result.getItem(), receipt); StringBuilder rightsString = new StringBuilder(); @@ -178,7 +192,19 @@ public class ReceiptGenerator /** * Construct the entry * + * @param context + * The relevant DSpace Context. + * @param item + * the target item to generate the ATOM document for + * @param config + * SWORD configuration + * @return deposit receipt * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SwordError + * SWORD error per SWORD spec + * @throws SwordServerException + * thrown by SWORD server implementation */ protected DepositReceipt createReceipt(Context context, Item item, SwordConfigurationDSpace config) @@ -194,8 +220,8 @@ public class ReceiptGenerator receipt.setSplashUri(urlManager.getSplashUrl(item)); receipt.setSwordEditIRI(urlManager.getEditIRI(item)); receipt.setContent(urlManager.getContentUrl(item), "application/zip"); - receipt.addEditMediaIRI(urlManager.getContentUrl(item), - "application/zip"); + receipt.addEditMediaIRI( + urlManager.getContentUrl(item), "application/zip"); receipt.setMediaFeedIRI(urlManager.getMediaFeedUrl(item)); receipt.setLastModified(item.getLastModified()); @@ -240,22 +266,34 @@ public class ReceiptGenerator * Add all the subject classifications from the bibliographic * metadata. * + * @param result + * represents the results of a deposit request + * @param receipt + * deposit receipt */ protected void addCategories(DepositResult result, DepositReceipt receipt) { - List dcv = itemService - .getMetadataByMetadataString(result.getItem(), "dc.subject.*"); + List dcv = itemService.getMetadataByMetadataString( + result.getItem(), "dc.subject.*"); if (dcv != null) { for (MetadataValue aDcv : dcv) { - receipt.getWrappedEntry() - .addCategory(UriRegistry.DC_NAMESPACE, aDcv.getValue(), - aDcv.getValue()); + receipt.getWrappedEntry().addCategory( + UriRegistry.DC_NAMESPACE, aDcv.getValue(), aDcv.getValue()); } } } + /** + * Add all the subject classifications from the bibliographic + * metadata. + * + * @param item + * target item + * @param receipt + * deposit receipt + */ protected void addCategories(Item item, DepositReceipt receipt) { List dcv = itemService @@ -264,9 +302,8 @@ public class ReceiptGenerator { for (MetadataValue aDcv : dcv) { - receipt.getWrappedEntry() - .addCategory(UriRegistry.DC_NAMESPACE, aDcv.getValue(), - aDcv.getValue()); + receipt.getWrappedEntry().addCategory( + UriRegistry.DC_NAMESPACE, aDcv.getValue(), aDcv.getValue()); } } } @@ -274,12 +311,15 @@ public class ReceiptGenerator /** * Add the date of publication from the bibliographic metadata * + * @param result + * represents the results of a deposit request + * @param receipt + * deposit receipt */ protected void addPublishDate(DepositResult result, DepositReceipt receipt) { - List dcv = itemService - .getMetadataByMetadataString(result.getItem(), - "dc.date.issued"); + List dcv = itemService.getMetadataByMetadataString( + result.getItem(), "dc.date.issued"); if (dcv != null && !dcv.isEmpty()) { try @@ -296,10 +336,18 @@ public class ReceiptGenerator } } + /** + * Add the date of publication from the bibliographic metadata + * + * @param item + * target item + * @param receipt + * deposit receipt + */ protected void addPublishDate(Item item, DepositReceipt receipt) { - List dcv = itemService - .getMetadataByMetadataString(item, "dc.date.issued"); + List dcv = itemService.getMetadataByMetadataString( + item, "dc.date.issued"); if (dcv != null && dcv.size() == 1) { try @@ -319,14 +367,18 @@ public class ReceiptGenerator /** * Add the date that this item was last updated * + * @param result + * represents the results of a deposit request + * @param receipt + * deposit receipt */ protected void addLastUpdatedDate(DepositResult result, DepositReceipt receipt) { - String config = ConfigurationManager - .getProperty("swordv2-server", "updated.field"); - List dcv = itemService - .getMetadataByMetadataString(result.getItem(), config); + String config = ConfigurationManager.getProperty( + "swordv2-server", "updated.field"); + List dcv = itemService.getMetadataByMetadataString( + result.getItem(), config); if (dcv != null && dcv.size() == 1) { try @@ -343,12 +395,20 @@ public class ReceiptGenerator } } + /** + * Add the date that this item was last updated + * + * @param item + * target item + * @param receipt + * deposit receipt + */ protected void addLastUpdatedDate(Item item, DepositReceipt receipt) { - String config = ConfigurationManager - .getProperty("swordv2-server", "updated.field"); - List dcv = itemService - .getMetadataByMetadataString(item, config); + String config = ConfigurationManager.getProperty( + "swordv2-server", "updated.field"); + List dcv = itemService.getMetadataByMetadataString( + item, config); if (dcv != null && dcv.size() == 1) { try diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleDCEntryIngester.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleDCEntryIngester.java index 9305673a85..63d66d6dcc 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleDCEntryIngester.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleDCEntryIngester.java @@ -27,14 +27,14 @@ import org.apache.commons.lang.StringUtils; public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntryIngester { - private static final Logger log = Logger - .getLogger(SimpleDCEntryIngester.class); + private static final Logger log = + Logger.getLogger(SimpleDCEntryIngester.class); - protected WorkspaceItemService workspaceItemService = ContentServiceFactory - .getInstance().getWorkspaceItemService(); + protected WorkspaceItemService workspaceItemService = + ContentServiceFactory.getInstance().getWorkspaceItemService(); - protected ConfigurationService configurationService = DSpaceServicesFactory - .getInstance().getConfigurationService(); + protected ConfigurationService configurationService = + DSpaceServicesFactory.getInstance().getConfigurationService(); public SimpleDCEntryIngester() { @@ -46,8 +46,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException { - return this - .ingest(context, deposit, dso, verboseDescription, null, false); + return this.ingest( + context, deposit, dso, verboseDescription, null, false); } public DepositResult ingest(Context context, Deposit deposit, @@ -59,12 +59,12 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC if (dso instanceof Collection) { return this.ingestToCollection(context, deposit, (Collection) dso, - verboseDescription, result); + verboseDescription, result); } else if (dso instanceof Item) { return this.ingestToItem(context, deposit, (Item) dso, - verboseDescription, result, replace); + verboseDescription, result, replace); } return null; } @@ -121,16 +121,15 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC throws DSpaceSwordException { String[] replaceableMetadata = configurationService - .getArrayProperty("swordv2-server.metadata.replaceable"); + .getArrayProperty("swordv2-server.metadata.replaceable"); for (String part : replaceableMetadata) { - MetadataValueInfo info = this - .makeMetadataValueInfo(part.trim(), null); + MetadataValueInfo info = + this.makeMetadataValueInfo(part.trim(), null); try { - itemService - .clearMetadata(context, item, info.schema, info.element, - info.qualifier, Item.ANY); + itemService.clearMetadata(context, item, + info.schema, info.element, info.qualifier, Item.ANY); } catch (SQLException e) { @@ -154,8 +153,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC { lang = Item.ANY; } - List existing = itemService - .getMetadata(item, info.schema, info.element, qual, lang); + List existing = itemService.getMetadata( + item, info.schema, info.element, qual, lang); for (MetadataValue dcValue : existing) { // FIXME: probably we want to be slightly more careful about qualifiers and languages @@ -186,8 +185,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC String titleField = this.dcMap.get("title"); if (titleField != null) { - MetadataValueInfo info = this - .makeMetadataValueInfo(titleField, title); + MetadataValueInfo info = + this.makeMetadataValueInfo(titleField, title); try { this.addUniqueMetadata(context, info, item); @@ -204,8 +203,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC String abstractField = this.dcMap.get("abstract"); if (abstractField != null) { - MetadataValueInfo info = this - .makeMetadataValueInfo(abstractField, summary); + MetadataValueInfo info = + this.makeMetadataValueInfo(abstractField, summary); try { this.addUniqueMetadata(context, info, item); @@ -292,9 +291,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC context.restoreAuthSystemState(); verboseDescription.append("Ingest successful"); - verboseDescription - .append("Item created with internal identifier: " + - item.getID()); + verboseDescription.append( + "Item created with internal identifier: " + item.getID()); result.setItem(item); result.setTreatment(this.getTreatment()); @@ -335,10 +333,14 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC * the field in which to store this metadata in the configuration * sword.updated.field * - * * @param context + * The relevant DSpace Context. * @param item + * item to add date metadata to + * @param verboseDescription + * The description. * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ protected void setUpdatedDate(Context context, Item item, VerboseDescription verboseDescription) @@ -349,17 +351,17 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC if (StringUtils.isBlank(field)) { throw new DSpaceSwordException( - "No configuration, or configuration is invalid for: swordv2-server.updated.field"); + "No configuration, or configuration is invalid for: swordv2-server.updated.field"); } MetadataValueInfo info = this.makeMetadataValueInfo(field, null); try { - itemService.clearMetadata(context, item, info.schema, info.element, - info.qualifier, Item.ANY); + itemService.clearMetadata(context, item, + info.schema, info.element, info.qualifier, Item.ANY); DCDate date = new DCDate(new Date()); - itemService.addMetadata(context, item, info.schema, info.element, - info.qualifier, null, date.toString()); + itemService.addMetadata(context, item, info.schema, + info.element, info.qualifier, null, date.toString()); } catch (SQLException e) { @@ -367,8 +369,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC throw new DSpaceSwordException(e); } - verboseDescription - .append("Updated date added to response from item metadata where available"); + verboseDescription.append( + "Updated date added to response from item metadata where available"); } /** @@ -377,11 +379,16 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC * field in which to store this metadata in the configuration * sword.slug.field * - * * @param context + * The relevant DSpace Context. * @param item + * the item to modify * @param slugVal + * the value to store to metadata + * @param verboseDescription + * The description. * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ protected void setSlug(Context context, Item item, String slugVal, VerboseDescription verboseDescription) @@ -393,21 +400,21 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC return; } - String field = configurationService - .getProperty("swordv2-server.slug.field"); + String field = configurationService.getProperty( + "swordv2-server.slug.field"); if (StringUtils.isBlank(field)) { throw new DSpaceSwordException( - "No configuration, or configuration is invalid for: swordv2-server.slug.field"); + "No configuration, or configuration is invalid for: swordv2-server.slug.field"); } MetadataValueInfo info = this.makeMetadataValueInfo(field, null); try { - itemService.clearMetadata(context, item, info.schema, info.element, - info.qualifier, Item.ANY); - itemService.addMetadata(context, item, info.schema, info.element, - info.qualifier, null, slugVal); + itemService.clearMetadata(context, item, + info.schema, info.element, info.qualifier, Item.ANY); + itemService.addMetadata(context, item, + info.schema, info.element, info.qualifier, null, slugVal); } catch (SQLException e) { @@ -422,8 +429,9 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC * The human readable description of the treatment this ingester has * put the deposit through * - * @return + * @return human readable description * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ private String getTreatment() throws DSpaceSwordException { diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleZipContentIngester.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleZipContentIngester.java index 0319ec9b3c..f4e1b168dd 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleZipContentIngester.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SimpleZipContentIngester.java @@ -251,8 +251,9 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester * The human readable description of the treatment this ingester has * put the deposit through * - * @return + * @return human readable description * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ private String getTreatment() throws DSpaceSwordException { diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordAuthenticator.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordAuthenticator.java index 11a9904644..6de0b09b4a 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordAuthenticator.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordAuthenticator.java @@ -50,40 +50,43 @@ public class SwordAuthenticator /** logger */ private static Logger log = Logger.getLogger(SwordAuthenticator.class); - protected AuthenticationService authenticationService = AuthenticateServiceFactory - .getInstance().getAuthenticationService(); + protected AuthenticationService authenticationService = + AuthenticateServiceFactory.getInstance().getAuthenticationService(); - protected AuthorizeService authorizeService = AuthorizeServiceFactory - .getInstance().getAuthorizeService(); + protected AuthorizeService authorizeService = + AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected EPersonService ePersonService = EPersonServiceFactory - .getInstance().getEPersonService(); + protected EPersonService ePersonService = + EPersonServiceFactory.getInstance().getEPersonService(); - protected CommunityService communityService = ContentServiceFactory - .getInstance().getCommunityService(); + protected CommunityService communityService = + ContentServiceFactory.getInstance().getCommunityService(); - protected CollectionService collectionService = ContentServiceFactory - .getInstance().getCollectionService(); + protected CollectionService collectionService = + ContentServiceFactory.getInstance().getCollectionService(); - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); - protected ConfigurationService configurationService = DSpaceServicesFactory - .getInstance().getConfigurationService(); + protected ConfigurationService configurationService = + DSpaceServicesFactory.getInstance().getConfigurationService(); /** * Does the given username and password authenticate for the * given DSpace Context? * * @param context + * The relevant DSpace Context. * @param un + * username * @param pw - * @return true if yes, false if not + * password + * @return true if authenticates successfully, false if not */ public boolean authenticates(Context context, String un, String pw) { - int auth = authenticationService - .authenticate(context, un, pw, null, null); + int auth = authenticationService.authenticate( + context, un, pw, null, null); return auth == AuthenticationMethod.SUCCESS; } @@ -92,7 +95,8 @@ public class SwordAuthenticator * using the passed IP address as part of the loggable * information * - * @throws org.dspace.sword2.DSpaceSwordException + * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ private Context constructContext() throws DSpaceSwordException @@ -110,10 +114,14 @@ public class SwordAuthenticator * method * * @param auth + * authentication credentials * @return SWORD context * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation * @throws SwordError + * SWORD error per SWORD spec * @throws SwordAuthException + * thrown if unable to authenticate */ public SwordContext authenticate(AuthCredentials auth) throws DSpaceSwordException, SwordError, SwordAuthException @@ -142,11 +150,16 @@ public class SwordAuthenticator * must exist in the user database. * * @param context + * The relevant DSpace Context. * @param auth + * authentication credentials * @return a SWORD context holding the various user information * @throws SwordAuthException + * thrown if unable to authenticate * @throws SwordError + * SWORD error per SWORD spec * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ private SwordContext authenticate(Context context, AuthCredentials auth) throws SwordAuthException, SwordError, DSpaceSwordException @@ -169,13 +182,13 @@ public class SwordAuthenticator { // user is trying to do a mediated deposit on a repository which does not support it log.error( - "Attempted mediated deposit on service not configured to do so"); + "Attempted mediated deposit on service not configured to do so"); throw new SwordError(UriRegistry.ERROR_MEDIATION_NOT_ALLOWED, - "Mediated deposit to this service is not permitted"); + "Mediated deposit to this service is not permitted"); } log.info(LogManager.getHeader(context, "sword_authenticate", - "username=" + un + ",on_behalf_of=" + obo)); + "username=" + un + ",on_behalf_of=" + obo)); try { @@ -194,13 +207,13 @@ public class SwordAuthenticator sc.setAuthenticated(ep); // Set any special groups - invoke the authentication mgr. List specialGroups = authenticationService - .getSpecialGroups(context, null); + .getSpecialGroups(context, null); for (Group specialGroup : specialGroups) { context.setSpecialGroup(specialGroup.getID()); log.debug("Adding Special Group id=" + - specialGroup.getID()); + specialGroup.getID()); } sc.setAuthenticatorContext(context); @@ -226,13 +239,13 @@ public class SwordAuthenticator oboContext.setCurrentUser(epObo); // Set any special groups - invoke the authentication mgr. List specialGroups = authenticationService - .getSpecialGroups(oboContext, null); + .getSpecialGroups(oboContext, null); for (Group specialGroup : specialGroups) { oboContext.setSpecialGroup(specialGroup.getID()); log.debug("Adding Special Group id=" + - specialGroup.getID()); + specialGroup.getID()); } sc.setContext(oboContext); } @@ -240,8 +253,8 @@ public class SwordAuthenticator { authenticated = false; throw new SwordError( - UriRegistry.ERROR_TARGET_OWNER_UNKNOWN, - "unable to identify on-behalf-of user: " + obo); + UriRegistry.ERROR_TARGET_OWNER_UNKNOWN, + "unable to identify on-behalf-of user: " + obo); } } } @@ -251,21 +264,20 @@ public class SwordAuthenticator // decide what kind of error to throw if (ep != null) { - log.info(LogManager - .getHeader(context, "sword_unable_to_set_user", - "username=" + un)); + log.info(LogManager.getHeader(context, + "sword_unable_to_set_user", "username=" + un)); throw new SwordAuthException( - "Unable to authenticate with the supplied credentials"); + "Unable to authenticate with the supplied credentials"); } else { // FIXME: this shouldn't ever happen now, but may as well leave it in just in case // there's a bug elsewhere log.info(LogManager.getHeader(context, - "sword_unable_to_set_on_behalf_of", - "username=" + un + ",on_behalf_of=" + obo)); + "sword_unable_to_set_on_behalf_of", + "username=" + un + ",on_behalf_of=" + obo)); throw new SwordAuthException( - "Unable to authenticate the onBehalfOf account"); + "Unable to authenticate the onBehalfOf account"); } } @@ -275,8 +287,8 @@ public class SwordAuthenticator { log.error("caught exception: ", e); throw new DSpaceSwordException( - "There was a problem accessing the repository user database", - e); + "There was a problem accessing the repository user database", + e); } } @@ -287,8 +299,15 @@ public class SwordAuthenticator * See javadocs for individual canSubmitTo methods to see the conditions * which are applied in each situation * - * @return true if yes, false if not + * @param swordContext + * The relevant SWORD Context. + * @param dso DSpace object + * @param msg message to append result to + * @return true if can submit, false if not * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SwordError + * never. */ public boolean canSubmit(SwordContext swordContext, DSpaceObject dso, VerboseDescription msg) @@ -315,8 +334,10 @@ public class SwordAuthenticator * of the special DSpace group Administrator, with id 1 * * @param swordContext + * The relevant SWORD Context. * @return true if administrator, false if not - * @throws java.sql.SQLException + * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isUserAdmin(SwordContext swordContext) throws DSpaceSwordException @@ -326,8 +347,8 @@ public class SwordAuthenticator EPerson authenticated = swordContext.getAuthenticated(); if (authenticated != null) { - return authorizeService - .isAdmin(swordContext.getAuthenticatorContext()); + return authorizeService.isAdmin( + swordContext.getAuthenticatorContext()); } return false; } @@ -344,8 +365,10 @@ public class SwordAuthenticator * of the special DSpace group Administrator, with id 1 * * @param swordContext + * The relevant SWORD Context. * @return true if administrator, false if not - * @throws java.sql.SQLException + * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isOnBehalfOfAdmin(SwordContext swordContext) throws DSpaceSwordException @@ -355,8 +378,8 @@ public class SwordAuthenticator { if (onBehalfOf != null) { - return authorizeService - .isAdmin(swordContext.getOnBehalfOfContext()); + return authorizeService.isAdmin( + swordContext.getOnBehalfOfContext()); } return false; } @@ -371,7 +394,11 @@ public class SwordAuthenticator * Is the authenticated user a member of the given group * or one of its sub groups? * - * @param group + * @param swordContext + * The relevant SWORD Context. + * @param group group to search recursively + * @return true if the authenticated user is a member of the given group + * or one of its sub groups */ public boolean isUserInGroup(SwordContext swordContext, Group group) { @@ -387,7 +414,11 @@ public class SwordAuthenticator * Is the onBehalfOf user a member of the given group or * one of its sub groups? * - * @param group + * @param swordContext + * The relevant SWORD Context. + * @param group group to search recursively + * @return true if onBehalfOf user is a member of the given group or + * one of its sub groups */ public boolean isOnBehalfOfInGroup(SwordContext swordContext, Group group) { @@ -405,8 +436,8 @@ public class SwordAuthenticator * until it has exhausted the tree of groups or finds the given * eperson * - * @param group - * @param eperson + * @param group group to search recursively + * @param eperson EPerson to find * @return true if in group, false if not */ public boolean isInGroup(Group group, EPerson eperson) @@ -449,17 +480,19 @@ public class SwordAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to READ * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. * @return the array of allowed collections * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedCommunities(SwordContext swordContext) throws DSpaceSwordException @@ -496,8 +529,8 @@ public class SwordAuthenticator if (!authAllowed) { authAllowed = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), comm, - Constants.READ); + swordContext.getAuthenticatorContext(), comm, + Constants.READ); } // if we have not already determined that the obo user is ok to submit, look up the READ policy on the @@ -505,8 +538,8 @@ public class SwordAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), comm, - Constants.READ); + swordContext.getOnBehalfOfContext(), comm, + Constants.READ); } // final check to see if we are allowed to READ @@ -534,17 +567,21 @@ public class SwordAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to READ * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to READ - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to READ + * OR the on-behalf-of user is null) * + * @param swordContext + * The relevant SWORD Context. * @param community + * parent community to check recursively * @return the array of allowed collections * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getCommunities(SwordContext swordContext, Community community) @@ -581,8 +618,8 @@ public class SwordAuthenticator if (!authAllowed) { authAllowed = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), comm, - Constants.READ); + swordContext.getAuthenticatorContext(), comm, + Constants.READ); } // if we have not already determined that the obo user is ok to submit, look up the READ policy on the @@ -590,8 +627,8 @@ public class SwordAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), comm, - Constants.READ); + swordContext.getOnBehalfOfContext(), comm, + Constants.READ); } // final check to see if we are allowed to READ @@ -621,8 +658,10 @@ public class SwordAuthenticator * See that method for details of the conditions applied * * @param swordContext + * The relevant SWORD Context. * @return the array of allowed collections * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedCollections( SwordContext swordContext) @@ -638,17 +677,21 @@ public class SwordAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to ADD * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. + * @param community + * community to check * @return the array of allowed collections * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedCollections( SwordContext swordContext, Community community) @@ -671,8 +714,8 @@ public class SwordAuthenticator Context authContext = swordContext.getAuthenticatorContext(); // short cut by obtaining the collections to which the authenticated user can submit - List cols = collectionService - .findAuthorized(authContext, community, Constants.ADD); + List cols = collectionService.findAuthorized( + authContext, community, Constants.ADD); List allowed = new ArrayList<>(); // now find out if the obo user is allowed to submit to any of these collections @@ -691,8 +734,8 @@ public class SwordAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), col, - Constants.ADD); + swordContext.getOnBehalfOfContext(), col, + Constants.ADD); } // final check to see if we are allowed to READ @@ -718,17 +761,21 @@ public class SwordAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to WRITE on the item and ADD on the ORIGINAL bundle * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to WRITE on the item and ADD on the ORIGINAL bundle + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. + * @param collection + * collection to check * @return the array of allowed collections * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAllowedItems(SwordContext swordContext, org.dspace.content.Collection collection) @@ -749,7 +796,7 @@ public class SwordAuthenticator { List allowed = new ArrayList<>(); Iterator ii = itemService - .findByCollection(swordContext.getContext(), collection); + .findByCollection(swordContext.getContext(), collection); while (ii.hasNext()) { @@ -772,26 +819,26 @@ public class SwordAuthenticator if (!authAllowed) { boolean write = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), item, - Constants.WRITE); + swordContext.getAuthenticatorContext(), item, + Constants.WRITE); boolean add = false; if (bundles.isEmpty()) { add = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), item, - Constants.ADD); + swordContext.getAuthenticatorContext(), item, + Constants.ADD); } else { for (Bundle bundle : bundles) { if (Constants.CONTENT_BUNDLE_NAME - .equals(bundle.getName())) + .equals(bundle.getName())) { add = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), - bundle, Constants.ADD); + swordContext.getAuthenticatorContext(), + bundle, Constants.ADD); if (!add) { break; @@ -808,15 +855,15 @@ public class SwordAuthenticator if (!oboAllowed) { boolean write = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), item, - Constants.WRITE); + swordContext.getOnBehalfOfContext(), item, + Constants.WRITE); boolean add = false; if (bundles.isEmpty()) { add = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), item, - Constants.ADD); + swordContext.getAuthenticatorContext(), item, + Constants.ADD); } else { @@ -861,17 +908,21 @@ public class SwordAuthenticator * IF: the authenticated user is an administrator * AND: * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * OR IF: the authenticated user is authorised to ADD * AND: - * (the on-behalf-of user is an administrator - * OR the on-behalf-of user is authorised to ADD - * OR the on-behalf-of user is null) + * (the on-behalf-of user is an administrator + * OR the on-behalf-of user is authorised to ADD + * OR the on-behalf-of user is null) * * @param swordContext + * The relevant SWORD Context. * @param collection + * collection to check + * @return true if context can deposit into collection * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean canSubmitTo(SwordContext swordContext, org.dspace.content.Collection collection) @@ -904,8 +955,8 @@ public class SwordAuthenticator if (!authAllowed) { authAllowed = authorizeService.authorizeActionBoolean( - swordContext.getAuthenticatorContext(), collection, - Constants.ADD); + swordContext.getAuthenticatorContext(), collection, + Constants.ADD); } // if we have not already determined that the obo user is ok to submit, look up the READ policy on the @@ -913,8 +964,8 @@ public class SwordAuthenticator if (!oboAllowed) { oboAllowed = authorizeService.authorizeActionBoolean( - swordContext.getOnBehalfOfContext(), collection, - Constants.ADD); + swordContext.getOnBehalfOfContext(), collection, + Constants.ADD); } // final check to see if we are allowed to READ @@ -963,16 +1014,14 @@ public class SwordAuthenticator // we now need to check whether the selected context that we are authorising // has the appropriate permissions boolean write = authorizeService - .authorizeActionBoolean(allowContext, item, - Constants.WRITE); + .authorizeActionBoolean(allowContext, item, Constants.WRITE); List bundles = item.getBundles(); boolean add = false; if (bundles.isEmpty()) { - add = authorizeService - .authorizeActionBoolean(allowContext, item, - Constants.ADD); + add = authorizeService.authorizeActionBoolean( + allowContext, item, Constants.ADD); } else { @@ -980,9 +1029,8 @@ public class SwordAuthenticator { if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName())) { - add = authorizeService - .authorizeActionBoolean(allowContext, bundle, - Constants.ADD); + add = authorizeService.authorizeActionBoolean( + allowContext, bundle, Constants.ADD); if (!add) { break; @@ -1005,7 +1053,7 @@ public class SwordAuthenticator { // get the configuration String[] mediators = configurationService - .getArrayProperty("swordv2-server.on-behalf-of.update.mediators"); + .getArrayProperty("swordv2-server.on-behalf-of.update.mediators"); if (mediators == null || mediators.length==0) { // if there's no explicit list of mediators, then anyone can mediate @@ -1044,8 +1092,12 @@ public class SwordAuthenticator * see their documentation for details of the conditions. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object + * @return true if context can submit to dso * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean canSubmitTo(SwordContext context, DSpaceObject dso) throws DSpaceSwordException diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordConfigurationDSpace.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordConfigurationDSpace.java index fbfcd547b3..1182ffdc04 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordConfigurationDSpace.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordConfigurationDSpace.java @@ -30,13 +30,13 @@ public class SwordConfigurationDSpace implements SwordConfiguration { /** logger */ public static final Logger log = Logger - .getLogger(SwordConfigurationDSpace.class); + .getLogger(SwordConfigurationDSpace.class); protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory - .getInstance().getBitstreamFormatService(); + .getInstance().getBitstreamFormatService(); protected ConfigurationService configurationService = DSpaceServicesFactory - .getInstance().getConfigurationService(); + .getInstance().getConfigurationService(); /** whether we can be verbose */ private boolean verbose = true; @@ -74,7 +74,7 @@ public class SwordConfigurationDSpace implements SwordConfiguration { // set the max upload size int mus = configurationService - .getIntProperty("swordv2-server.max-upload-size"); + .getIntProperty("swordv2-server.max-upload-size"); if (mus > 0) { this.maxUploadSize = mus; @@ -82,15 +82,15 @@ public class SwordConfigurationDSpace implements SwordConfiguration // set the mediation value this.mediated = configurationService - .getBooleanProperty("swordv2-server.on-behalf-of.enable", false); + .getBooleanProperty("swordv2-server.on-behalf-of.enable", false); // find out if we keep the original as bitstream this.keepOriginal = configurationService - .getBooleanProperty("swordv2-server.keep-original-package"); + .getBooleanProperty("swordv2-server.keep-original-package"); // get the sword bundle String bundle = configurationService - .getProperty("swordv2-server.bundle.name"); + .getProperty("swordv2-server.bundle.name"); if (StringUtils.isBlank(bundle)) { this.swordBundle = bundle; @@ -98,16 +98,15 @@ public class SwordConfigurationDSpace implements SwordConfiguration // find out if we keep the package as a file in specified directory this.keepPackageOnFailedIngest = configurationService - .getBooleanProperty("swordv2-server.keep-package-on-fail", - false); + .getBooleanProperty("swordv2-server.keep-package-on-fail", false); // get directory path and name this.failedPackageDir = configurationService - .getProperty("swordv2-server.failed-package.dir"); + .getProperty("swordv2-server.failed-package.dir"); // Get the accepted formats String[] acceptsFormats = configurationService - .getArrayProperty("swordv2-server.accepts"); + .getArrayProperty("swordv2-server.accepts"); swordaccepts = new ArrayList(); if (ArrayUtils.isEmpty(acceptsFormats)) { @@ -120,12 +119,11 @@ public class SwordConfigurationDSpace implements SwordConfiguration // find out if community deposit is allowed this.allowCommunityDeposit = configurationService - .getBooleanProperty("swordv2-server.allow-community-deposit"); + .getBooleanProperty("swordv2-server.allow-community-deposit"); // find out if we keep the package as a file in specified directory this.entryFirst = configurationService - .getBooleanProperty("swordv2-server.multipart.entry-first", - false); + .getBooleanProperty("swordv2-server.multipart.entry-first", false); } @@ -208,7 +206,7 @@ public class SwordConfigurationDSpace implements SwordConfiguration public String getAuthType() { return this.getStringProperty("swordv2-server.auth-type", "Basic", - new String[] { "Basic", "None" }); + new String[] { "Basic", "None" }); } public boolean storeAndCheckBinary() @@ -224,13 +222,13 @@ public class SwordConfigurationDSpace implements SwordConfiguration public String getAlternateUrl() { return configurationService - .getProperty("swordv2-server.error.alternate.url"); + .getProperty("swordv2-server.error.alternate.url"); } public String getAlternateUrlContentType() { return configurationService - .getProperty("swordv2-server.error.alternate.content-type"); + .getProperty("swordv2-server.error.alternate.content-type"); } /////////////////////////////////////////////////////////////////////////////////// @@ -286,6 +284,7 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Get the bundle name that SWORD will store its original deposit packages in, when * storing them inside an item + * * @return SWORD bundle name */ public String getSwordBundle() @@ -296,6 +295,7 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Set the bundle name that SWORD will store its original deposit packages in, when * storing them inside an item + * * @param swordBundle SWORD bundle name */ public void setSwordBundle(String swordBundle) @@ -305,6 +305,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Is this a verbose deposit? + * + * @return true if this is verbose deposit */ public boolean isVerbose() { @@ -313,7 +315,9 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Set whether this is a verbose deposit. + * * @param verbose + * verbose deposit */ public void setVerbose(boolean verbose) { @@ -322,6 +326,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * What is the max upload size (in bytes) for the SWORD interface? + * + * @return max upload size */ public int getMaxUploadSize() { @@ -329,8 +335,10 @@ public class SwordConfigurationDSpace implements SwordConfiguration } /** - * Set the max uplaod size (in bytes) for the SWORD interface. + * Set the max upload size (in bytes) for the SWORD interface. + * * @param maxUploadSize + * max upload size to set */ public void setMaxUploadSize(int maxUploadSize) { @@ -339,6 +347,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Does the server support mediated deposit (aka on-behalf-of)? + * + * @return true if server supports mediated deposit */ public boolean isMediated() { @@ -347,7 +357,9 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Set whether the server supports mediated deposit (aka on-behalf-of). + * * @param mediated + * mediated deposit state to set */ public void setMediated(boolean mediated) { @@ -356,6 +368,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Should the repository keep the original package? + * + * @return true if should keep original package */ public boolean isKeepOriginal() { @@ -364,7 +378,9 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * set whether the repository should keep copies of the original package + * * @param keepOriginal + * should keep original package? */ public void setKeepOriginal(boolean keepOriginal) { @@ -373,7 +389,9 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * set whether the repository should write file of the original package if ingest fails + * * @param keepOriginalOnFail + * should keep original package if ingest fails? */ public void setKeepPackageOnFailedIngest(boolean keepOriginalOnFail) { @@ -382,7 +400,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * should the repository write file of the original package if ingest fails - * @return keepPackageOnFailedIngest + * + * @return whether the repository should keep original package if ingest fails */ public boolean isKeepPackageOnFailedIngest() { @@ -391,7 +410,9 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * set the directory to write file of the original package + * * @param dir + * directory where to store the original package */ public void setFailedPackageDir(String dir) { @@ -401,7 +422,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * directory location of the files with original packages * for failed ingests - * @return failedPackageDir + * + * @return directory where to store the original package */ public String getFailedPackageDir() { @@ -413,8 +435,13 @@ public class SwordConfigurationDSpace implements SwordConfiguration * accept as packages. * * @param context + * The relevant DSpace Context. * @param dso + * DSpace object to check + * @return list of MIME types that the given DSpace object will + * accept as packages. * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getAccepts(Context context, DSpaceObject dso) throws DSpaceSwordException @@ -461,6 +488,7 @@ public class SwordConfigurationDSpace implements SwordConfiguration * * @return the list of mime types * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public List getCollectionAccepts() throws DSpaceSwordException { @@ -482,9 +510,12 @@ public class SwordConfigurationDSpace implements SwordConfiguration * http://purl.org/net/sword-types/METSDSpaceSIP * * and the Q value is a floating point between 0 and 1 which defines - * how much the server "likes" this packaging type. + * how much the server "likes" this packaging type. * * @param col + * target collection + * @return map of packaging URIs to Q values for the packaging types which + * the given collection will accept. */ public List getAcceptPackaging(Collection col) { @@ -550,9 +581,14 @@ public class SwordConfigurationDSpace implements SwordConfiguration * object? * * @param packageFormat + * packaging/media type to check * @param dso + * DSpace object to check + * @return true if supported * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation * @throws SwordError + * SWORD error per SWORD spec */ public boolean isAcceptedPackaging(String packageFormat, DSpaceObject dso) throws DSpaceSwordException, SwordError @@ -590,10 +626,17 @@ public class SwordConfigurationDSpace implements SwordConfiguration /** * Is the given content MIME type acceptable to the given DSpace object. + * * @param context + * The relevant DSpace Context. * @param type + * MIME type to check * @param dso + * DSpace object to compare to + * @return true if acceptable * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isAcceptableContentType(Context context, String type, DSpaceObject dso) @@ -646,13 +689,13 @@ public class SwordConfigurationDSpace implements SwordConfiguration public String getStateUri(String state) { return configurationService - .getProperty("swordv2-server.state." + state + ".uri"); + .getProperty("swordv2-server.state." + state + ".uri"); } public String getStateDescription(String state) { return configurationService - .getProperty("swordv2-server.state." + state + ".description"); + .getProperty("swordv2-server.state." + state + ".description"); } public boolean allowUnauthenticatedMediaAccess() diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContentIngester.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContentIngester.java index 0d5c078104..463b370a8d 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContentIngester.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContentIngester.java @@ -28,9 +28,23 @@ public interface SwordContentIngester * Ingest the package as described in the given Deposit object * within the given DSpace Context * + * @param context + * The relevant DSpace Context. * @param deposit + * the original deposit request + * @param target + * target DSpace object + * @param verboseDescription + * The description. * @return the result of the deposit * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SwordError + * SWORD error per SWORD spec + * @throws SwordAuthException + * thrown if unable to authenticate + * @throws SwordServerException + * thrown by SWORD server implementation */ DepositResult ingest(Context context, Deposit deposit, DSpaceObject target, VerboseDescription verboseDescription) diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContext.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContext.java index ec9f432240..80baf6b2e0 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContext.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordContext.java @@ -85,6 +85,8 @@ public class SwordContext * Returns the most appropriate context for operations on the * database. This is the on-behalf-of user's context if the * user exists, or the authenticated user's context otherwise. + * + * @return appropriate DSpace context */ public Context getContext() { @@ -104,6 +106,8 @@ public class SwordContext * getContext() * * on this class instead. + * + * @return DSpace context of the user who authenticated */ public Context getAuthenticatorContext() { @@ -123,6 +127,8 @@ public class SwordContext * * on this class instead. If there is no on-behalf-of user, this * method will return null. + * + * @return DSpace context of the on-behalf-of user */ public Context getOnBehalfOfContext() { @@ -160,6 +166,7 @@ public class SwordContext * when using the sword api. * * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public void commit() throws DSpaceSwordException diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordDisseminatorFactory.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordDisseminatorFactory.java index db1ca7ba05..2deaf53aa7 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordDisseminatorFactory.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordDisseminatorFactory.java @@ -93,7 +93,7 @@ public class SwordDisseminatorFactory } } - if(StringUtils.isNotEmpty(disseminateFormat)) + if (StringUtils.isNotEmpty(disseminateFormat)) { disseminator.setContentType(disseminateFormat); } diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordIngesterFactory.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordIngesterFactory.java index 6d2e265e87..2731b2456a 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordIngesterFactory.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordIngesterFactory.java @@ -35,8 +35,16 @@ public class SwordIngesterFactory * documentation for more details. * * @param context + * The relevant DSpace Context. * @param deposit + * The original deposit request + * @param dso + * target DSpace object + * @return SWORDIngester object * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SwordError + * if no suitable ingester is configured. */ public static SwordContentIngester getContentInstance(Context context, Deposit deposit, DSpaceObject dso) @@ -48,7 +56,7 @@ public class SwordIngesterFactory // first look to see if there's an intester for the content type ingester = (SwordContentIngester) pluginService - .getNamedPlugin(SwordContentIngester.class, deposit.getMimeType()); + .getNamedPlugin(SwordContentIngester.class, deposit.getMimeType()); if (ingester != null) { return ingester; @@ -57,11 +65,11 @@ public class SwordIngesterFactory // if no ingester, then // look to see if there's an ingester for the package format ingester = (SwordContentIngester) pluginService - .getNamedPlugin(SwordContentIngester.class, deposit.getPackaging()); + .getNamedPlugin(SwordContentIngester.class, deposit.getPackaging()); if (ingester == null) { throw new SwordError(UriRegistry.ERROR_CONTENT, - "No ingester configured for this package type"); + "No ingester configured for this package type"); } return ingester; } @@ -71,11 +79,11 @@ public class SwordIngesterFactory throws DSpaceSwordException, SwordError { SwordEntryIngester ingester = (SwordEntryIngester) CoreServiceFactory.getInstance().getPluginService() - .getSinglePlugin(SwordEntryIngester.class); + .getSinglePlugin(SwordEntryIngester.class); if (ingester == null) { throw new SwordError(UriRegistry.ERROR_CONTENT, - "No ingester configured for handling sword entry documents"); + "No ingester configured for handling SWORD entry documents"); } return ingester; } diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordMETSContentIngester.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordMETSContentIngester.java index 94e5fd688b..c9e57e59e6 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordMETSContentIngester.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordMETSContentIngester.java @@ -35,17 +35,17 @@ import org.swordapp.server.SwordServerException; public class SwordMETSContentIngester extends AbstractSwordContentIngester { /** Log4j logger */ - public static final Logger log = Logger - .getLogger(SwordMETSContentIngester.class); + public static final Logger log = Logger.getLogger( + SwordMETSContentIngester.class); - protected WorkspaceItemService workspaceItemService = ContentServiceFactory - .getInstance().getWorkspaceItemService(); + protected WorkspaceItemService workspaceItemService = + ContentServiceFactory.getInstance().getWorkspaceItemService(); - protected CollectionService collectionService = ContentServiceFactory - .getInstance().getCollectionService(); + protected CollectionService collectionService = + ContentServiceFactory.getInstance().getCollectionService(); - protected HandleService handleService = HandleServiceFactory.getInstance() - .getHandleService(); + protected HandleService handleService = + HandleServiceFactory.getInstance() .getHandleService(); public DepositResult ingest(Context context, Deposit deposit, DSpaceObject dso, VerboseDescription verboseDescription) @@ -69,8 +69,8 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester if (result != null) { Item item = result.getItem(); - return this.ingestToItem(context, deposit, item, - verboseDescription, result); + return this.ingestToItem( + context, deposit, item, verboseDescription, result); } // otherwise, go on and do a create ... @@ -80,16 +80,16 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester // us finer control over the workflow state of the item, whereas asking // the ingester to /create/ this item causes it to be injected into the workflow, // irrespective of the In-Progress header provided by the depositor - WorkspaceItem wsi = workspaceItemService - .create(context, collection, true); + WorkspaceItem wsi = workspaceItemService.create( + context, collection, true); Item item = wsi.getItem(); // need to add a licence file, otherwise the METS replace function raises a NullPointerException String licence = collectionService.getLicense(collection); if (PackageUtils.findDepositLicense(context, item) == null) { - PackageUtils - .addDepositLicense(context, licence, item, collection); + PackageUtils.addDepositLicense( + context, licence, item, collection); } // get deposited file as InputStream @@ -105,9 +105,9 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester verboseDescription.append("Using package manifest format: " + cfg); PackageIngester pi = (PackageIngester) CoreServiceFactory.getInstance().getPluginService() - .getNamedPlugin(PackageIngester.class, cfg); + .getNamedPlugin(PackageIngester.class, cfg); verboseDescription.append("Loaded package ingester: " + - pi.getClass().getName()); + pi.getClass().getName()); // Initialize parameters to packager PackageParameters params = new PackageParameters(); @@ -116,35 +116,33 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester params.setWorkflowEnabled(true); // Should restore mode be enabled, i.e. keep existing handle? - if (ConfigurationManager - .getBooleanProperty("sword-server", "restore-mode.enable", - false)) + if (ConfigurationManager.getBooleanProperty( + "sword-server", "restore-mode.enable", false)) { params.setRestoreModeEnabled(true); } // Whether or not to use the collection template params.setUseCollectionTemplate(ConfigurationManager - .getBooleanProperty( - "mets.default.ingest.useCollectionTemplate", - false)); + .getBooleanProperty( + "mets.default.ingest.useCollectionTemplate", false)); // ingest the item from the temp file - DSpaceObject ingestedObject = pi - .replace(context, item, depositFile, params); + DSpaceObject ingestedObject = pi.replace( + context, item, depositFile, params); if (ingestedObject == null) { - verboseDescription - .append("Failed to ingest the package; throwing exception"); + verboseDescription.append( + "Failed to ingest the package; throwing exception"); throw new SwordError(DSpaceUriRegistry.UNPACKAGE_FAIL, - "METS package ingester failed to unpack package"); + "METS package ingester failed to unpack package"); } // Verify we have an Item as a result if (!(ingestedObject instanceof Item)) { throw new DSpaceSwordException( - "DSpace Ingester returned wrong object type -- not an Item result."); + "DSpace Ingester returned wrong object type -- not an Item result."); } else { @@ -162,7 +160,7 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester // DSpace ignores the slug value as suggested identifier, but // it does store it in the metadata this.setSlug(context, installedItem, deposit.getSlug(), - verboseDescription); + verboseDescription); // in order to write these changes, we need to bypass the // authorisation briefly, because although the user may be @@ -177,19 +175,18 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester String handle = handleService.findHandle(context, installedItem); verboseDescription.append("Ingest successful"); - verboseDescription - .append("Item created with internal identifier: " + - installedItem.getID()); + verboseDescription.append( + "Item created with internal identifier: " + + installedItem.getID()); if (handle != null) { - verboseDescription - .append("Item created with external identifier: " + - handle); + verboseDescription.append( + "Item created with external identifier: " + handle); } else { - verboseDescription - .append("No external identifier available at this stage (item in workflow)"); + verboseDescription.append( + "No external identifier available at this stage (item in workflow)"); } DepositResult dr = new DepositResult(); @@ -228,8 +225,8 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester File depositFile = deposit.getFile(); // load the plugin manager for the required configuration - String cfg = ConfigurationManager.getProperty("sword-server", - "mets-ingester.package-ingester"); + String cfg = ConfigurationManager.getProperty( + "sword-server", "mets-ingester.package-ingester"); if (cfg == null || "".equals(cfg)) { cfg = "METS"; // default to METS @@ -237,9 +234,9 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester verboseDescription.append("Using package manifest format: " + cfg); PackageIngester pi = (PackageIngester) CoreServiceFactory.getInstance().getPluginService() - .getNamedPlugin(PackageIngester.class, cfg); + .getNamedPlugin(PackageIngester.class, cfg); verboseDescription.append("Loaded package ingester: " + - pi.getClass().getName()); + pi.getClass().getName()); // Initialize parameters to packager PackageParameters params = new PackageParameters(); @@ -248,35 +245,33 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester params.setWorkflowEnabled(true); // Should restore mode be enabled, i.e. keep existing handle? - if (ConfigurationManager - .getBooleanProperty("sword-server", "restore-mode.enable", - false)) + if (ConfigurationManager.getBooleanProperty( + "sword-server", "restore-mode.enable", false)) { params.setRestoreModeEnabled(true); } // Whether or not to use the collection template params.setUseCollectionTemplate(ConfigurationManager - .getBooleanProperty( - "mets.default.ingest.useCollectionTemplate", - false)); + .getBooleanProperty( + "mets.default.ingest.useCollectionTemplate", false)); // ingest the item from the temp file - DSpaceObject ingestedObject = pi - .replace(context, item, depositFile, params); + DSpaceObject ingestedObject = pi.replace( + context, item, depositFile, params); if (ingestedObject == null) { - verboseDescription - .append("Failed to replace the package; throwing exception"); + verboseDescription.append( + "Failed to replace the package; throwing exception"); throw new SwordError(DSpaceUriRegistry.UNPACKAGE_FAIL, - "METS package ingester failed to unpack package"); + "METS package ingester failed to unpack package"); } // Verify we have an Item as a result if (!(ingestedObject instanceof Item)) { throw new DSpaceSwordException( - "DSpace Ingester returned wrong object type -- not an Item result."); + "DSpace Ingester returned wrong object type -- not an Item result."); } // get reference to item so that we can report on it @@ -319,14 +314,15 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester * The human readable description of the treatment this ingester has * put the deposit through * - * @return + * @return human readable description * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ private String getTreatment() throws DSpaceSwordException { return "The package has been deposited into DSpace. Each file has been unpacked " + - "and provided with a unique identifier. The metadata in the manifest has been " + - "extracted and attached to the DSpace item, which has been provided with " + - "an identifier leading to an HTML splash page."; + "and provided with a unique identifier. The metadata in the manifest has been " + + "extracted and attached to the DSpace item, which has been provided with " + + "an identifier leading to an HTML splash page."; } } diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordUrlManager.java b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordUrlManager.java index 35a3b53ae2..b3ceebdb50 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/SwordUrlManager.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/SwordUrlManager.java @@ -27,24 +27,24 @@ import java.util.List; /** * @author Richard Jones * - * Class responsible for constructing and de-constructing sword url space - * urls + * Class responsible for constructing and de-constructing SWORD URL space + * URLs */ public class SwordUrlManager { - protected ItemService itemService = ContentServiceFactory.getInstance() - .getItemService(); + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); - protected BitstreamService bitstreamService = ContentServiceFactory - .getInstance().getBitstreamService(); + protected BitstreamService bitstreamService = + ContentServiceFactory.getInstance().getBitstreamService(); - protected HandleService handleService = HandleServiceFactory.getInstance() - .getHandleService(); + protected HandleService handleService = + HandleServiceFactory.getInstance().getHandleService(); - /** the sword configuration */ + /** the SWORD configuration */ private SwordConfigurationDSpace config; - /** the active dspace context */ + /** the active DSpace context */ private Context context; public SwordUrlManager(SwordConfigurationDSpace config, Context context) @@ -59,8 +59,10 @@ public class SwordUrlManager * unless configuration changes are made to DSpace * * @param collection + * target collection * @return The Deposit URL * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getDepositLocation(Collection collection) throws DSpaceSwordException @@ -74,8 +76,10 @@ public class SwordUrlManager * unless configuration changes are made to DSpace * * @param community + * target community * @return The Deposit URL * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getDepositLocation(Community community) throws DSpaceSwordException @@ -94,25 +98,25 @@ public class SwordUrlManager if (sUrl == null || "".equals(sUrl)) { String dspaceUrl = ConfigurationManager - .getProperty("dspace.baseUrl"); + .getProperty("dspace.baseUrl"); if (dspaceUrl == null || "".equals(dspaceUrl)) { throw new DSpaceSwordException( - "Unable to construct service document urls, due to missing/invalid " + - "config in sword2.url and/or dspace.baseUrl"); + "Unable to construct service document urls, due to missing/invalid " + + "config in sword2.url and/or dspace.baseUrl"); } try { URL url = new URL(dspaceUrl); sUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), - "/swordv2").toString(); + "/swordv2").toString(); } catch (MalformedURLException e) { throw new DSpaceSwordException( - "Unable to construct service document urls, due to invalid dspace.baseUrl " + - e.getMessage(), e); + "Unable to construct service document urls, due to invalid dspace.baseUrl " + + e.getMessage(), e); } } return sUrl; @@ -143,7 +147,7 @@ public class SwordUrlManager else { throw new SwordError(DSpaceUriRegistry.BAD_URL, - "The item URL is invalid"); + "The item URL is invalid"); } String iid = location.substring(cBaseUrl.length()); @@ -165,7 +169,7 @@ public class SwordUrlManager { // log.error("Caught exception:", e); throw new DSpaceSwordException( - "There was a problem resolving the item", e); + "There was a problem resolving the item", e); } } @@ -193,6 +197,9 @@ public class SwordUrlManager * @param location the URL to resolve to a collection * @return The collection to which the url resolves * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation + * @throws SwordError + * if a proper URL cannot be calculated. */ // FIXME: we need to generalise this to DSpaceObjects, so that we can support // Communities, Collections and Items separately @@ -205,7 +212,7 @@ public class SwordUrlManager if (baseUrl.length() == location.length()) { throw new SwordError(DSpaceUriRegistry.BAD_URL, - "The deposit URL is incomplete"); + "The deposit URL is incomplete"); } String handle = location.substring(baseUrl.length()); if (handle.startsWith("/")) @@ -215,7 +222,7 @@ public class SwordUrlManager if ("".equals(handle)) { throw new SwordError(DSpaceUriRegistry.BAD_URL, - "The deposit URL is incomplete"); + "The deposit URL is incomplete"); } DSpaceObject dso = handleService.resolveToObject(context, handle); @@ -227,7 +234,7 @@ public class SwordUrlManager if (!(dso instanceof Collection)) { throw new SwordError(DSpaceUriRegistry.BAD_URL, - "The deposit URL does not resolve to a valid collection"); + "The deposit URL does not resolve to a valid collection"); } return (Collection) dso; @@ -236,7 +243,7 @@ public class SwordUrlManager { // log.error("Caught exception:", e); throw new DSpaceSwordException( - "There was a problem resolving the collection", e); + "There was a problem resolving the collection", e); } } @@ -246,7 +253,10 @@ public class SwordUrlManager * entries. * * @param community + * target community + * @return service document URL * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String constructSubServiceUrl(Community community) throws DSpaceSwordException @@ -262,7 +272,10 @@ public class SwordUrlManager * entries. * * @param collection + * target collection + * @return service document URL * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String constructSubServiceUrl(Collection collection) throws DSpaceSwordException @@ -276,9 +289,14 @@ public class SwordUrlManager * Extract a DSpaceObject from the given URL. If this method is unable to * locate a meaningful and appropriate DSpace object it will throw the * appropriate SWORD error. + * * @param url + * URL to get DSpace object from + * @return DSpace object from URL * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation * @throws SwordError + * SWORD error per SWORD spec */ public DSpaceObject extractDSpaceObject(String url) throws DSpaceSwordException, SwordError @@ -315,14 +333,14 @@ public class SwordUrlManager else { throw new SwordError(DSpaceUriRegistry.BAD_URL, - "Service Document request does not refer to a DSpace Collection or Community"); + "Service Document request does not refer to a DSpace Collection or Community"); } } else { throw new SwordError(DSpaceUriRegistry.BAD_URL, - "Unable to recognise URL as a valid service document: " + - url); + "Unable to recognise URL as a valid service document: " + + url); } } catch (SQLException e) @@ -334,35 +352,37 @@ public class SwordUrlManager /** * Get the base URL for service document requests. * + * @return service document base URL * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getBaseServiceDocumentUrl() throws DSpaceSwordException { String sdUrl = ConfigurationManager - .getProperty("swordv2-server", "servicedocument.url"); + .getProperty("swordv2-server", "servicedocument.url"); if (sdUrl == null || "".equals(sdUrl)) { String dspaceUrl = ConfigurationManager - .getProperty("dspace.baseUrl"); + .getProperty("dspace.baseUrl"); if (dspaceUrl == null || "".equals(dspaceUrl)) { throw new DSpaceSwordException( - "Unable to construct service document urls, due to missing/invalid " + - "config in swordv2-server.cfg servicedocument.url and/or dspace.baseUrl"); + "Unable to construct service document urls, due to missing/invalid " + + "config in swordv2-server.cfg servicedocument.url and/or dspace.baseUrl"); } try { URL url = new URL(dspaceUrl); sdUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), - "/swordv2/servicedocument").toString(); + "/swordv2/servicedocument").toString(); } catch (MalformedURLException e) { throw new DSpaceSwordException( - "Unable to construct service document urls, due to invalid dspace.baseUrl " + - e.getMessage(), e); + "Unable to construct service document urls, due to invalid dspace.baseUrl " + + e.getMessage(), e); } } return sdUrl; @@ -381,36 +401,37 @@ public class SwordUrlManager * * where dspace.baseUrl is also in the configuration file. * - * @return the base URL for sword deposit + * @return the base URL for SWORD deposit * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getBaseCollectionUrl() throws DSpaceSwordException { String depositUrl = ConfigurationManager - .getProperty("swordv2-server", "collection.url"); + .getProperty("swordv2-server", "collection.url"); if (depositUrl == null || "".equals(depositUrl)) { String dspaceUrl = ConfigurationManager - .getProperty("dspace.baseUrl"); + .getProperty("dspace.baseUrl"); if (dspaceUrl == null || "".equals(dspaceUrl)) { throw new DSpaceSwordException( - "Unable to construct deposit urls, due to missing/invalid config in " + - "swordv2-server.cfg deposit.url and/or dspace.baseUrl"); + "Unable to construct deposit urls, due to missing/invalid config in " + + "swordv2-server.cfg deposit.url and/or dspace.baseUrl"); } try { URL url = new URL(dspaceUrl); depositUrl = new URL(url.getProtocol(), url.getHost(), - url.getPort(), "/swordv2/collection").toString(); + url.getPort(), "/swordv2/collection").toString(); } catch (MalformedURLException e) { throw new DSpaceSwordException( - "Unable to construct deposit urls, due to invalid dspace.baseUrl " + - e.getMessage(), e); + "Unable to construct deposit urls, due to invalid dspace.baseUrl " + + e.getMessage(), e); } } @@ -421,7 +442,10 @@ public class SwordUrlManager * Is the given URL the base service document URL? * * @param url + * URL to check + * @return true if URL is service document base URL * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isBaseServiceDocumentUrl(String url) throws DSpaceSwordException @@ -431,10 +455,13 @@ public class SwordUrlManager /** * Central location for constructing usable URLs for DSpace bitstreams. - * There is no place in the main DSpace code base for doing this. + * There is no place in the main DSpace codebase for doing this. * * @param bitstream + * target bitstream + * @return URL of given bitstream * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public String getBitstreamUrl(Bitstream bitstream) throws DSpaceSwordException @@ -450,7 +477,7 @@ public class SwordUrlManager else { throw new DSpaceSwordException( - "Encountered orphaned bitstream"); + "Encountered orphaned bitstream"); } List items = parent.getItems(); @@ -470,7 +497,7 @@ public class SwordUrlManager if (handle != null && !"".equals(handle)) { bsLink = bsLink + "/bitstream/" + handle + "/" + - bitstream.getSequenceID() + "/" + bitstream.getName(); + bitstream.getSequenceID() + "/" + bitstream.getName(); } else { @@ -490,7 +517,7 @@ public class SwordUrlManager throws DSpaceSwordException { return this.getSwordBaseUrl() + "/edit-media/bitstream/" + - bitstream.getID() + "/" + bitstream.getName(); + bitstream.getID() + "/" + bitstream.getName(); } public boolean isActionableBitstreamUrl(Context context, String url) @@ -508,7 +535,7 @@ public class SwordUrlManager if (!location.startsWith(emBaseUrl)) { throw new SwordError(DSpaceUriRegistry.BAD_URL, - "The bitstream URL is invalid"); + "The bitstream URL is invalid"); } String bitstreamParts = location.substring(emBaseUrl.length()); @@ -516,15 +543,15 @@ public class SwordUrlManager // the bitstream id is the part up to the first "/" int firstSlash = bitstreamParts.indexOf("/"); String bid = bitstreamParts.substring(0, firstSlash); - Bitstream bitstream = bitstreamService - .findByIdOrLegacyId(context, bid); + Bitstream bitstream = + bitstreamService.findByIdOrLegacyId(context, bid); return bitstream; } catch (SQLException e) { // log.error("Caught exception:", e); throw new DSpaceSwordException( - "There was a problem resolving the collection", e); + "There was a problem resolving the collection", e); } } @@ -567,7 +594,7 @@ public class SwordUrlManager if (urlTemplate != null) { return urlTemplate.replace("#wsid#", Integer.toString( - wft.getWorkspaceItem(context, item).getID())); + wft.getWorkspaceItem(context, item).getID())); } } // otherwise, it may be in the workflow, in which case there is @@ -596,6 +623,6 @@ public class SwordUrlManager throws DSpaceSwordException { return new IRI(this.getSwordBaseUrl() + "/edit-media/" + item.getID() + - ".atom"); + ".atom"); } } diff --git a/dspace-swordv2/src/main/java/org/dspace/sword2/WorkflowTools.java b/dspace-swordv2/src/main/java/org/dspace/sword2/WorkflowTools.java index 607a6344e3..b3da189fc4 100644 --- a/dspace-swordv2/src/main/java/org/dspace/sword2/WorkflowTools.java +++ b/dspace-swordv2/src/main/java/org/dspace/sword2/WorkflowTools.java @@ -25,14 +25,14 @@ import java.sql.SQLException; public class WorkflowTools { - protected WorkspaceItemService workspaceItemService = ContentServiceFactory - .getInstance().getWorkspaceItemService(); + protected WorkspaceItemService workspaceItemService = + ContentServiceFactory.getInstance().getWorkspaceItemService(); - protected WorkflowItemService workflowItemService = WorkflowServiceFactory - .getInstance().getWorkflowItemService(); + protected WorkflowItemService workflowItemService = + WorkflowServiceFactory.getInstance().getWorkflowItemService(); - protected WorkflowService workflowService = WorkflowServiceFactory - .getInstance().getWorkflowService(); + protected WorkflowService workflowService = + WorkflowServiceFactory.getInstance().getWorkflowService(); /** * Is the given item in the DSpace workflow? @@ -41,8 +41,12 @@ public class WorkflowTools * case rather than using the DSpace API (which is very slow). * * @param context + * The relevant DSpace Context. * @param item + * item to check + * @return true if item is in workflow * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isItemInWorkflow(Context context, Item item) throws DSpaceSwordException @@ -64,8 +68,12 @@ public class WorkflowTools * case rather than using the DSpace API (which is very slow). * * @param context + * The relevant DSpace Context. * @param item + * item to check + * @return true if item is in workspace * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public boolean isItemInWorkspace(Context context, Item item) throws DSpaceSwordException @@ -87,8 +95,12 @@ public class WorkflowTools * case rather than using the DSpace API (which is very slow). * * @param context + * The relevant DSpace Context. * @param item + * item to check + * @return workflow item * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public WorkflowItem getWorkflowItem(Context context, Item item) throws DSpaceSwordException @@ -110,8 +122,12 @@ public class WorkflowTools * case rather than using the DSpace API (which is very slow). * * @param context + * The relevant DSpace Context. * @param item + * item to check + * @return workspace item * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public WorkspaceItem getWorkspaceItem(Context context, Item item) throws DSpaceSwordException @@ -129,8 +145,12 @@ public class WorkflowTools /** * Start the DSpace workflow on the given item * + * @param context + * The relevant DSpace Context. * @param item + * item to check * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public void startWorkflow(Context context, Item item) throws DSpaceSwordException @@ -161,8 +181,12 @@ public class WorkflowTools /** * Stop the DSpace workflow, and return the item to the user workspace * + * @param context + * The relevant DSpace Context. * @param item + * item to check * @throws DSpaceSwordException + * can be thrown by the internals of the DSpace SWORD implementation */ public void stopWorkflow(Context context, Item item) throws DSpaceSwordException diff --git a/dspace-xmlui-mirage2/pom.xml b/dspace-xmlui-mirage2/pom.xml index 430f438213..d4c7567ea7 100644 --- a/dspace-xmlui-mirage2/pom.xml +++ b/dspace-xmlui-mirage2/pom.xml @@ -11,7 +11,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-xmlui/pom.xml b/dspace-xmlui/pom.xml index a0b6b0ab5b..67fb35564e 100644 --- a/dspace-xmlui/pom.xml +++ b/dspace-xmlui/pom.xml @@ -11,7 +11,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanel.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanel.java index 4b7b0c868d..408cf48788 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanel.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanel.java @@ -51,18 +51,18 @@ public class ControlPanel extends AbstractDSpaceTransformer implements Serviceab private static final Logger log = Logger.getLogger(ControlPanel.class); /** Language Strings */ - private static final Message T_DSPACE_HOME = message("xmlui.general.dspace_home"); - private static final Message T_title = message("xmlui.administrative.ControlPanel.title"); - private static final Message T_trail = message("xmlui.administrative.ControlPanel.trail"); - private static final Message T_head = message("xmlui.administrative.ControlPanel.head"); - - private static final Message T_select_panel = message("xmlui.administrative.ControlPanel.select_panel"); + private static final Message T_DSPACE_HOME = message("xmlui.general.dspace_home"); + private static final Message T_title = message("xmlui.administrative.ControlPanel.title"); + private static final Message T_trail = message("xmlui.administrative.ControlPanel.trail"); + private static final Message T_head = message("xmlui.administrative.ControlPanel.head"); + + private static final Message T_select_panel = message("xmlui.administrative.ControlPanel.select_panel"); protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); protected ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); /** - * The service manager allows us to access the continuation's + * The service manager allows us to access the continuation's * manager. It is obtained from the Serviceable API */ private ServiceManager serviceManager; @@ -86,9 +86,9 @@ public class ControlPanel extends AbstractDSpaceTransformer implements Serviceab * The Cocoon Persistent Store (used for cache statistics) */ private Store storePersistent; - + /** - * From the org.apache.avalon.framework.service.Serviceable API, + * From the org.apache.avalon.framework.service.Serviceable API, * give us the current ServiceManager instance. *

    * Much of this ServiceManager logic/code has been borrowed from the source @@ -96,26 +96,32 @@ public class ControlPanel extends AbstractDSpaceTransformer implements Serviceab * http://svn.apache.org/repos/asf/cocoon/tags/cocoon-2.2/cocoon-sitemap-components/cocoon-sitemap-components-1.0.0/src/main/java/org/apache/cocoon/generation/StatusGenerator.java */ @Override - public void service(ServiceManager serviceManager) throws ServiceException + public void service(ServiceManager serviceManager) throws ServiceException { this.serviceManager = serviceManager; - + this.settings = (Settings) this.serviceManager.lookup(Settings.ROLE); - - if(this.serviceManager.hasService(StoreJanitor.ROLE)) + + if (this.serviceManager.hasService(StoreJanitor.ROLE)) + { this.storeJanitor = (StoreJanitor) this.serviceManager.lookup(StoreJanitor.ROLE); - + } + if (this.serviceManager.hasService(Store.ROLE)) + { this.storeDefault = (Store) this.serviceManager.lookup(Store.ROLE); - - if(this.serviceManager.hasService(Store.PERSISTENT_STORE)) + } + + if (this.serviceManager.hasService(Store.PERSISTENT_STORE)) + { this.storePersistent = (Store) this.serviceManager.lookup(Store.PERSISTENT_STORE); + } } @Override - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { pageMeta.addMetadata("title").addContent(T_title); @@ -124,8 +130,9 @@ public class ControlPanel extends AbstractDSpaceTransformer implements Serviceab } @Override - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { if (!authorizeService.isAdmin(context)) @@ -133,7 +140,8 @@ public class ControlPanel extends AbstractDSpaceTransformer implements Serviceab throw new AuthorizeException("You are not authorized to view this page."); } - Division div = body.addInteractiveDivision("control-panel", contextPath+"/admin/panel", Division.METHOD_POST, "primary administrative"); + Division div = body.addInteractiveDivision("control-panel", contextPath + + "/admin/panel", Division.METHOD_POST, "primary administrative"); div.setHead(T_head); Request request = ObjectModelHelper.getRequest(objectModel); @@ -141,60 +149,75 @@ public class ControlPanel extends AbstractDSpaceTransformer implements Serviceab if (request.getParameter("tab") != null) { - selected_tab = request.getParameter("tab"); - div.addHidden("tab").setValue(selected_tab); + selected_tab = request.getParameter("tab"); + div.addHidden("tab").setValue(selected_tab); } // LIST: options List options = div.addList("options", List.TYPE_SIMPLE, "horizontal"); - + String tabs[] = configurationService.getArrayProperty("controlpanel.tabs"); - - for(String tab : tabs) { - tab = tab.trim(); + + for (String tab : tabs) + { + tab = tab.trim(); Message linkText = message("xmlui.administrative.ControlPanel.tabs." + tab); - if(tab.equals(selected_tab)) { - options.addItem().addHighlight("bold").addXref("?tab=" + selected_tab, linkText); - } else { - options.addItemXref(contextPath + "/admin/panel?tab=" + tab, linkText); - } + if (tab.equals(selected_tab)) + { + options.addItem().addHighlight("bold").addXref("?tab=" + selected_tab, linkText); + } + else + { + options.addItemXref(contextPath + "/admin/panel?tab=" + tab, linkText); + } + } + + if (selected_tab.equals("")) + { + div.addPara(T_select_panel); + } + else + { + ControlPanelTab cpTab = (ControlPanelTab)CoreServiceFactory + .getInstance().getPluginService().getNamedPlugin( + ControlPanelTab.class, selected_tab); + if (cpTab instanceof AbstractControlPanelTab) + { + try + { + ((AbstractControlPanelTab) cpTab).setup(null, objectModel, null, parameters); + ((AbstractControlPanelTab) cpTab).service(serviceManager); + ((AbstractControlPanelTab) cpTab).setWebLink(contextPath + "/admin/panel?tab=" + selected_tab); + } + catch (ServiceException e) + { + log.error(e); + } + catch (ProcessingException e) + { + log.error(e); + } + } + cpTab.addBody(objectModel, div); } - - if(selected_tab.equals("")) { - div.addPara(T_select_panel); - } else { - ControlPanelTab cpTab = (ControlPanelTab)CoreServiceFactory.getInstance().getPluginService().getNamedPlugin(ControlPanelTab.class, selected_tab); - if(cpTab instanceof AbstractControlPanelTab) { - try { - ((AbstractControlPanelTab) cpTab).setup(null, objectModel, null, parameters); - ((AbstractControlPanelTab) cpTab).service(serviceManager); - ((AbstractControlPanelTab) cpTab).setWebLink(contextPath + "/admin/panel?tab=" + selected_tab); - } catch (ServiceException e) { - log.error(e); - } catch (ProcessingException e) { - log.error(e); - } - } - cpTab.addBody(objectModel, div); - } } - + /** * Release all Cocoon resources. * @see org.apache.avalon.framework.activity.Disposable#dispose() */ @Override - public void dispose() + public void dispose() { - if (this.serviceManager != null) + if (this.serviceManager != null) { this.serviceManager.release(this.storePersistent); this.serviceManager.release(this.storeJanitor); this.serviceManager.release(this.storeDefault); this.serviceManager.release(this.settings); this.storePersistent = null; - this.storeJanitor = null; + this.storeJanitor = null; this.storeDefault = null; this.settings = null; } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanelAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanelAction.java index eea80e92fd..9bdfdbca72 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanelAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ControlPanelAction.java @@ -21,7 +21,7 @@ import org.dspace.harvest.service.HarvestSchedulingService; /** * Update the alert system based upon the form submitted from the control panel. - * + * * @author Scott Phillips */ @@ -37,69 +37,68 @@ public class ControlPanelAction extends AbstractAction String source, Parameters parameters) throws Exception { Request request = ObjectModelHelper.getRequest(objectModel); - + // In any case update the system-wide alert system String message = request.getParameter("message"); String countdownString = request.getParameter("countdown"); String restrictsessions = request.getParameter("restrictsessions"); - + int countdown = -1; if (countdownString != null) { - try { - countdown = Integer.valueOf(countdownString); - } - catch (NumberFormatException nfe) - { - // just ignore it. - } + try { + countdown = Integer.valueOf(countdownString); + } + catch (NumberFormatException nfe) + { + // just ignore it. + } } - - + + // Update the message if (message != null) { SystemwideAlerts.setMessage(message); } - + if (countdown >= 0) { - // Convert from minutes to milliseconds; - countdown = countdown * 60 * 1000; - - // Figure out when the count down is. - long countDownTo = System.currentTimeMillis() + countdown; - - // set it. - SystemwideAlerts.setCountDownToo(countDownTo); + // Convert from minutes to milliseconds; + countdown = countdown * 60 * 1000; + + // Figure out when the count down is. + long countDownTo = System.currentTimeMillis() + countdown; + + // set it. + SystemwideAlerts.setCountDownToo(countDownTo); } - + if (restrictsessions != null && restrictsessions.length() > 0) { - try { - int newState = Integer.valueOf(restrictsessions); - SystemwideAlerts.setRestrictSessions(newState); - } - catch (NumberFormatException nfe) - { - // ignore it - } + try + { + int newState = Integer.valueOf(restrictsessions); + SystemwideAlerts.setRestrictSessions(newState); + } + catch (NumberFormatException nfe) + { + // ignore it + } } - - - + + if (request.getParameter("submit_activate") != null) { - SystemwideAlerts.activateAlert(); - - // Ensure the alert is active for this request, return - // a success so the sitemap can add the alert in. - return new HashMap(); - + SystemwideAlerts.activateAlert(); + + // Ensure the alert is active for this request, return + // a success so the sitemap can add the alert in. + return new HashMap(); } else if (request.getParameter("submit_deactivate") != null) { - SystemwideAlerts.deactivateAlert(); + SystemwideAlerts.deactivateAlert(); } else if (request.getParameter("submit_harvest_start") != null) { harvestSchedulingService.startNewScheduler(); @@ -119,5 +118,4 @@ public class ControlPanelAction extends AbstractAction return null; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/CurrentActivityAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/CurrentActivityAction.java index bb35d11af7..5da26551a9 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/CurrentActivityAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/CurrentActivityAction.java @@ -40,53 +40,55 @@ import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; public class CurrentActivityAction extends AbstractAction { - /** The maximum number of events that are recorded */ - public static final int MAX_EVENTS; - - /** The HTTP header that contains the real IP for this request, this is used when DSpace is placed behind a load balancer */ - public static final String IP_HEADER; - - /** The ordered list of events, by access time */ - private static Queue events = new LinkedList(); - - /** record events that are from anonymous users */ - private static boolean recordAnonymousEvents = true; - + /** The maximum number of events that are recorded */ + public static final int MAX_EVENTS; + + /** The HTTP header that contains the real IP for this request, this is used + * when DSpace is placed behind a load balancer */ + public static final String IP_HEADER; + + /** The ordered list of events, by access time */ + private static Queue events = new LinkedList(); + + /** record events that are from anonymous users */ + private static boolean recordAnonymousEvents = true; + /** record events from automatic bots */ - private static boolean recordBotEvents = DSpaceServicesFactory.getInstance().getConfigurationService() - .getBooleanProperty("currentActivityAction.recordBotEvents", false); + private static boolean recordBotEvents = DSpaceServicesFactory.getInstance() + .getConfigurationService().getBooleanProperty( + "currentActivityAction.recordBotEvents", false); private static String[] botStrings = (new DSpace()).getSingletonService( - ConfigurationService.class).getPropertyAsType( - "currentActivityAction.botStrings", - new String[] { "google/", "msnbot/", "googlebot/", "webcrawler/", - "inktomi", "teoma", "baiduspider", "bot" }); - - /** - * Allow the DSpace.cfg to override our activity max and ip header. - */ - static { - // If the dspace.cfg has a max event count then use it. - if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.controlpanel.activity.max") != null) + ConfigurationService.class).getPropertyAsType( + "currentActivityAction.botStrings", + new String[] { "google/", "msnbot/", "googlebot/", "webcrawler/", + "inktomi", "teoma", "baiduspider", "bot" }); + + /** + * Allow the DSpace.cfg to override our activity max and ip header. + */ + static { + // If the dspace.cfg has a max event count then use it. + if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.controlpanel.activity.max") != null) { - MAX_EVENTS = DSpaceServicesFactory.getInstance().getConfigurationService().getIntProperty("xmlui.controlpanel.activity.max"); + MAX_EVENTS = DSpaceServicesFactory.getInstance().getConfigurationService().getIntProperty("xmlui.controlpanel.activity.max"); } else { MAX_EVENTS = 250; } - - if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.controlpanel.activity.ipheader") != null) + + if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.controlpanel.activity.ipheader") != null) { - IP_HEADER = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.controlpanel.activity.ipheader"); + IP_HEADER = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.controlpanel.activity.ipheader"); } else { IP_HEADER = "X-Forwarded-For"; } - } - - + } + + /** * Record this current event. * @@ -100,418 +102,423 @@ public class CurrentActivityAction extends AbstractAction */ @Override public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, - String source, Parameters parameters) throws Exception + String source, Parameters parameters) + throws Exception { Request request = ObjectModelHelper.getRequest(objectModel); Context context = ContextUtil.obtainContext(objectModel); - + // Ensure only one thread is manipulating the events queue at a time. synchronized (events) { - // Create and store our events - Event event = new Event(context,request); - - // Check if we should record the event - boolean record = true; - if (!recordAnonymousEvents && event.isAnonymous()) + // Create and store our events + Event event = new Event(context,request); + + // Check if we should record the event + boolean record = true; + if (!recordAnonymousEvents && event.isAnonymous()) { - record = false; + record = false; } - if (!recordBotEvents && event.isBot()) + if (!recordBotEvents && event.isBot()) { - record = false; + record = false; } - - if (record) + + if (record) { - events.add(event); + events.add(event); } - - // Remove the oldest element from the list if we are over our max - // number of elements. - while (events.size() > MAX_EVENTS) + + // Remove the oldest element from the list if we are over our max + // number of elements. + while (events.size() > MAX_EVENTS) { - events.poll(); + events.poll(); } } - + return null; } - + /** * @return a list of all current events. */ public static List getEvents() { - List list = new ArrayList(); - // Make sure only one thread is manipulating the events queue at a time. - synchronized (events) { - list.addAll(events); - } - return list; + List list = new ArrayList(); + // Make sure only one thread is manipulating the events queue at a time. + synchronized (events) { + list.addAll(events); + } + return list; } - - + + public static boolean getRecordAnonymousEvents() { - return recordAnonymousEvents; + return recordAnonymousEvents; } - + public static void setRecordAnonymousEvents(boolean record) { - recordAnonymousEvents = record; + recordAnonymousEvents = record; } - + public static boolean getRecordBotEvents() { - return recordBotEvents; + return recordBotEvents; } - + public static void setRecordBotEvents(boolean record) { - recordBotEvents = record; + recordBotEvents = record; } - + /** * An object that represents an activity event. */ public static class Event { - /** The Servlet session */ - private String sessionID; - - /** The eperson ID */ - private UUID epersonID = null; - - /** The url being viewed */ - private String url; - - /** A timestap of this event */ - private long timestamp; - - /** The user-agent for the request */ - private String userAgent; - - /** The ip address of the requester */ - private String ip; - - /** The host address of the requester */ - public String host = null; - public Map cookieMap = new HashMap(); - public Map headers = new HashMap(); - public String qs = null; - public String puser = null; - - /** - * Construct a new activity event, grabbing various bits of data about + /** The Servlet session */ + private String sessionID; + + /** The eperson ID */ + private UUID epersonID = null; + + /** The url being viewed */ + private String url; + + /** A timestap of this event */ + private long timestamp; + + /** The user-agent for the request */ + private String userAgent; + + /** The ip address of the requester */ + private String ip; + + /** The host address of the requester */ + public String host = null; + public Map cookieMap = new HashMap(); + public Map headers = new HashMap(); + public String qs = null; + public String puser = null; + + /** + * Construct a new activity event, grabbing various bits of data about * the request from the context and request. * @param context session context. * @param request current request. - */ - public Event(Context context, Request request) - { - if (context != null) - { - EPerson eperson = context.getCurrentUser(); - if (eperson != null) + */ + public Event(Context context, Request request) + { + if (context != null) + { + EPerson eperson = context.getCurrentUser(); + if (eperson != null) { epersonID = eperson.getID(); } - } - - if (request != null) - { - url = request.getSitemapURI(); - HttpSession session = request.getSession(true); - if (session != null) + } + + if (request != null) + { + url = request.getSitemapURI(); + HttpSession session = request.getSession(true); + if (session != null) { sessionID = session.getId(); } - - userAgent = request.getHeader("User-Agent"); - - ip = request.getHeader(IP_HEADER); - if (ip == null) + + userAgent = request.getHeader("User-Agent"); + + ip = request.getHeader(IP_HEADER); + if (ip == null) { ip = request.getRemoteAddr(); } - host = request.getRemoteHost(); - // values should be copied - if ( request.getCookieMap() != null ) { - for ( Object key : request.getCookieMap().keySet() ) { - Object val = request.getCookieMap().get(key); - String cookstr = ((Cookie)val).getName() + ":" + ((Cookie)val).getValue(); - cookieMap.put( (String)key, cookstr ); - } - } - // values should be copied - if ( request.getHeaders() != null ) { - for ( Object key : request.getHeaders().keySet() ) { - Object val = request.getHeaders().get(key); - headers.put( (String)key, (String)val ); - } - } - qs = request.getQueryString(); - puser = request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : "None"; - } - - // The current time - timestamp = System.currentTimeMillis(); - } - - - public String getSessionID() - { - return sessionID; - } - - public UUID getEPersonID() - { - return epersonID; - } - - public String getURL() - { - return url; - } - - public long getTimeStamp() - { - return timestamp; - } - - public String getUserAgent() - { - return userAgent; - } - - public String getIP() - { - return ip; - } - - /** - * Is this event anonymous? + host = request.getRemoteHost(); + // values should be copied + if ( request.getCookieMap() != null ) + { + for ( Object key : request.getCookieMap().keySet() ) + { + Object val = request.getCookieMap().get(key); + String cookstr = ((Cookie)val).getName() + ":" + ((Cookie)val).getValue(); + cookieMap.put( (String)key, cookstr ); + } + } + // values should be copied + if ( request.getHeaders() != null ) + { + for ( Object key : request.getHeaders().keySet() ) + { + Object val = request.getHeaders().get(key); + headers.put( (String)key, (String)val ); + } + } + qs = request.getQueryString(); + puser = request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : "None"; + } + + // The current time + timestamp = System.currentTimeMillis(); + } + + + public String getSessionID() + { + return sessionID; + } + + public UUID getEPersonID() + { + return epersonID; + } + + public String getURL() + { + return url; + } + + public long getTimeStamp() + { + return timestamp; + } + + public String getUserAgent() + { + return userAgent; + } + + public String getIP() + { + return ip; + } + + /** + * Is this event anonymous? * @return true if session has no EPerson ID. - */ - public boolean isAnonymous() - { - return (epersonID == null); - } - - /** - * Is this event from a bot? + */ + public boolean isAnonymous() + { + return (epersonID == null); + } + + /** + * Is this event from a bot? * @return true if user agent matches a bot string. - */ - public boolean isBot() - { - if (userAgent == null) + */ + public boolean isBot() + { + if (userAgent == null) { return false; } - String ua = userAgent.toLowerCase(); + String ua = userAgent.toLowerCase(); - for(String botString : botStrings){ - if (ua.contains(botString)){ - return true; - } - } - return false; - } - - /** - * Return the activity viewer's best guess as to what browser or bot - * was initiating the request. - * - * @return A short name for the browser or bot. - */ - public String getDectectedBrowser() - { - if (userAgent == null) + for (String botString : botStrings) + { + if (ua.contains(botString)){ + return true; + } + } + return false; + } + + /** + * Return the activity viewer's best guess as to what browser or bot + * was initiating the request. + * + * @return A short name for the browser or bot. + */ + public String getDectectedBrowser() + { + if (userAgent == null) { return "No browser provided"; } String userAgentLower = userAgent.toLowerCase(); - - // BOTS - if (userAgentLower.contains("google/")) + + // BOTS + if (userAgentLower.contains("google/")) { return "Google (bot)"; } - - if (userAgentLower.contains("msnbot/")) + + if (userAgentLower.contains("msnbot/")) { return "MSN (bot)"; } - - if (userAgentLower.contains("googlebot/")) + + if (userAgentLower.contains("googlebot/")) { return "Google (bot)"; } - - if (userAgentLower.contains("webcrawler/")) + + if (userAgentLower.contains("webcrawler/")) { return "WebCrawler (bot)"; } - - if (userAgentLower.contains("inktomi")) + + if (userAgentLower.contains("inktomi")) { return "Inktomi (bot)"; } - - if (userAgentLower.contains("teoma")) + + if (userAgentLower.contains("teoma")) { return "Teoma (bot)"; } - - if (userAgentLower.contains("baiduspider")) + + if (userAgentLower.contains("baiduspider")) { return "Baidu (bot)"; } - - if (userAgentLower.contains("bot")) + + if (userAgentLower.contains("bot")) { return "Unknown (bot)"; } - - // Normal Browsers - if (userAgent.contains("Lotus-Notes/")) + + // Normal Browsers + if (userAgent.contains("Lotus-Notes/")) { return "Lotus-Notes"; } - - if (userAgent.contains("Opera")) + + if (userAgent.contains("Opera")) { return "Opera"; } - - if (userAgent.contains("Safari/")) - { - if (userAgent.contains("Chrome")) + + if (userAgent.contains("Safari/")) + { + if (userAgent.contains("Chrome")) { return "Chrome"; } - - return "Safari"; - } - - if (userAgent.contains("Konqueror/")) + + return "Safari"; + } + + if (userAgent.contains("Konqueror/")) { return "Konqueror"; } - - // Internet explorer browsers - if (userAgent.contains("MSIE")) - { - if (userAgent.contains("MSIE 9")) + + // Internet explorer browsers + if (userAgent.contains("MSIE")) + { + if (userAgent.contains("MSIE 9")) { return "MSIE 9"; } - if (userAgent.contains("MSIE 8")) + if (userAgent.contains("MSIE 8")) { return "MSIE 8"; } - if (userAgent.contains("MSIE 7")) + if (userAgent.contains("MSIE 7")) { return "MSIE 7"; } - if (userAgent.contains("MSIE 6")) + if (userAgent.contains("MSIE 6")) { return "MSIE 6"; } - if (userAgent.contains("MSIE 5")) + if (userAgent.contains("MSIE 5")) { return "MSIE 5"; } - - // Can't fine the version number - return "MSIE"; - } - - // Gecko based browsers - if (userAgent.contains("Gecko/")) - { - if (userAgent.contains("Camio/")) + + // Can't fine the version number + return "MSIE"; + } + + // Gecko based browsers + if (userAgent.contains("Gecko/")) + { + if (userAgent.contains("Camio/")) { return "Gecko/Camino"; } - - if (userAgent.contains("Chimera/")) + + if (userAgent.contains("Chimera/")) { return "Gecko/Chimera"; } - - if (userAgent.contains("Firebird/")) + + if (userAgent.contains("Firebird/")) { return "Gecko/Firebird"; } - - if (userAgent.contains("Phoenix/")) + + if (userAgent.contains("Phoenix/")) { return "Gecko/Phoenix"; } - - if (userAgent.contains("Galeon")) + + if (userAgent.contains("Galeon")) { return "Gecko/Galeon"; } - - if (userAgent.contains("Firefox/1")) + + if (userAgent.contains("Firefox/1")) { return "Firefox 1.x"; } - - if (userAgent.contains("Firefox/2")) + + if (userAgent.contains("Firefox/2")) { return "Firefox 2.x"; } - - if (userAgent.contains("Firefox/3")) + + if (userAgent.contains("Firefox/3")) { return "Firefox 3.x"; } - - if (userAgent.contains("Firefox/4")) + + if (userAgent.contains("Firefox/4")) { return "Firefox 4.x"; } - - if (userAgent.contains("Firefox/")) + + if (userAgent.contains("Firefox/")) { return "Firefox"; // can't find the exact version } - - if (userAgent.contains("Netscape/")) + + if (userAgent.contains("Netscape/")) { return "Netscape"; } - - // Can't find the exact distribution - return "Gecko"; - } - - // Generic browser types (lots of things report these names) - - if (userAgent.contains("KHTML/")) + + // Can't find the exact distribution + return "Gecko"; + } + + // Generic browser types (lots of things report these names) + + if (userAgent.contains("KHTML/")) { return "KHTML"; } - - if (userAgent.contains("Netscape/")) + + if (userAgent.contains("Netscape/")) { return "Netscape"; } - - if (userAgent.contains("Mozilla/")) + + if (userAgent.contains("Mozilla/")) { return "Mozilla"; // Almost everything says they are mozilla. } - - // if you get all the way to the end and still nothing, return unknown. - return userAgent.length() == 0 ? "Unknown" : escapeHtml( userAgent.substring( 0, Math.min(20, userAgent.length()) ) ); - } - } - - - + // if you get all the way to the end and still nothing, return unknown. + return userAgent.length() == 0 + ? "Unknown" + : escapeHtml(userAgent.substring( + 0, Math.min(20, userAgent.length()) ) ); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowAuthorizationUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowAuthorizationUtils.java index c2850fa913..f408628a1b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowAuthorizationUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowAuthorizationUtils.java @@ -39,127 +39,140 @@ import org.dspace.handle.service.HandleService; /** * FIXME: add documentation - * + * * @author Alexey maslov */ public class FlowAuthorizationUtils { - protected static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); - protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected static final BundleService bundleService = ContentServiceFactory.getInstance().getBundleService(); - protected static final BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); - protected static final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); - protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected static final ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); - protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + protected static final BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); + protected static final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); + protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected static final ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); + protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - /** Language Strings */ - //example language string -// private static final Message T_add_eperson_success_notice = -// new Message("default","xmlui.administrative.FlowUtils.add-eperson-success-notice"); + /** Language Strings */ + // example language string + // private static final Message T_add_eperson_success_notice = + // new Message("default","xmlui.administrative.FlowUtils.add-eperson-success-notice"); /** - * Resolve an identifier submitted into the item lookup box. If it contains a slash, it's assumed to be a - * handle and is resolved by that mechanism into an item, collection or community. Otherwise, it's assumed - * to be an item and looked up by ID. - * - * @param context The current DSpace context. - * @param identifier The identifier that is to be resolved. - * @return A process result's object. + * Resolve an identifier submitted into the item lookup box. If it contains a slash, it's assumed to be a + * handle and is resolved by that mechanism into an item, collection or community. Otherwise, it's assumed + * to be an item and looked up by ID. + * + * @param context The current DSpace context. + * @param identifier The identifier that is to be resolved. + * @return A process result's object. * @throws java.sql.SQLException passed through. - */ - public static FlowResult resolveItemIdentifier(Context context, String identifier) throws SQLException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - //Check whether it's a handle or internal id (by check ing if it has a slash in the string) - if (identifier.contains("/")) { - DSpaceObject dso = handleService.resolveToObject(context, identifier); - - if (dso != null && dso.getType() == Constants.ITEM) { - result.setParameter("itemID", dso.getID()); - result.setParameter("type", Constants.ITEM); - result.setContinue(true); - return result; - } - else if (dso != null && dso.getType() == Constants.COLLECTION) { - result.setParameter("collectionID", dso.getID()); - result.setParameter("type", Constants.COLLECTION); - result.setContinue(true); - return result; - } - else if (dso != null && dso.getType() == Constants.COMMUNITY) { - result.setParameter("communityID", dso.getID()); - result.setParameter("type", Constants.COMMUNITY); - result.setContinue(true); - return result; - } - } - // Otherwise, it's assumed to be a DSpace Item - else { - Item item = null; - try { - item = itemService.find(context, UUID.fromString(identifier)); - } catch (Exception e) { - // ignoring the exception in case of a malformed input string - } - - if (item != null) { - result.setParameter("itemID", item.getID()); - result.setParameter("type", Constants.ITEM); - result.setContinue(true); - return result; - } - } - - result.addError("identifier"); - return result; - } + */ + public static FlowResult resolveItemIdentifier(Context context, String identifier) + throws SQLException + { + FlowResult result = new FlowResult(); + result.setContinue(false); + // Check whether it's a handle or internal id (by check ing if it has a slash in the string) + if (identifier.contains("/")) + { + DSpaceObject dso = handleService.resolveToObject(context, identifier); - /** - * Process the editing of an existing or a newly created policy. - * - * @param context The current DSpace context. - * @param objectType The type of the policy's parent object (ITEM, COLLECTION, COMMUNITY) - * @param objectID The ID of the policy's parent object - * @param policyID The ID of the policy being edited (-1 if a new policy is being created) - * @param groupID The ID of the group to be associated with this policy - * @param actionID The ID of the action (dependent on the objectType) to be associated with this policy + if (dso != null && dso.getType() == Constants.ITEM) + { + result.setParameter("itemID", dso.getID()); + result.setParameter("type", Constants.ITEM); + result.setContinue(true); + return result; + } + else if (dso != null && dso.getType() == Constants.COLLECTION) + { + result.setParameter("collectionID", dso.getID()); + result.setParameter("type", Constants.COLLECTION); + result.setContinue(true); + return result; + } + else if (dso != null && dso.getType() == Constants.COMMUNITY) + { + result.setParameter("communityID", dso.getID()); + result.setParameter("type", Constants.COMMUNITY); + result.setContinue(true); + return result; + } + } + // Otherwise, it's assumed to be a DSpace Item + else + { + Item item = null; + try + { + item = itemService.find(context, UUID.fromString(identifier)); + } + catch (Exception e) + { + // ignoring the exception in case of a malformed input string + } + + if (item != null) + { + result.setParameter("itemID", item.getID()); + result.setParameter("type", Constants.ITEM); + result.setContinue(true); + return result; + } + } + + result.addError("identifier"); + return result; + } + + /** + * Process the editing of an existing or a newly created policy. + * + * @param context The current DSpace context. + * @param objectType The type of the policy's parent object (ITEM, COLLECTION, COMMUNITY) + * @param objectID The ID of the policy's parent object + * @param policyID The ID of the policy being edited (-1 if a new policy is being created) + * @param groupID The ID of the group to be associated with this policy + * @param actionID The ID of the action (dependent on the objectType) to be associated with this policy * @param name name the policy. * @param description describe the policy. * @param startDateParam when the policy starts to apply. * @param endDateParam when the policy no longer applies. - * @return A process result's object. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processEditPolicy(Context context, int objectType, UUID objectID, int policyID, UUID groupID, int actionID, - String name, String description, String startDateParam, String endDateParam) - throws SQLException, AuthorizeException - { - FlowResult result = new FlowResult(); - boolean added = false; - - ResourcePolicy policy = resourcePolicyService.find(context, policyID); - - // check authorization to edit an existent policy - if (policy != null) - { - AuthorizeUtil.authorizeManagePolicy(context, policy); - } - - /* First and foremost, if no group or action was selected, throw an error back to the user */ - if (actionID == -1) { - result.setContinue(false); - result.addError("action_id"); - return result; - } - if (groupID == null) { - result.setContinue(false); - result.addError("group_id"); - return result; - } + */ + public static FlowResult processEditPolicy(Context context, int objectType, + UUID objectID, int policyID, UUID groupID, int actionID, String name, + String description, String startDateParam, String endDateParam) + throws SQLException, AuthorizeException + { + FlowResult result = new FlowResult(); + boolean added = false; + + ResourcePolicy policy = resourcePolicyService.find(context, policyID); + + // check authorization to edit an existent policy + if (policy != null) + { + AuthorizeUtil.authorizeManagePolicy(context, policy); + } + + /* First and foremost, if no group or action was selected, throw an error back to the user */ + if (actionID == -1) + { + result.setContinue(false); + result.addError("action_id"); + return result; + } + if (groupID == null) + { + result.setContinue(false); + result.addError("group_id"); + return result; + } // check dates @@ -167,36 +180,47 @@ public class FlowAuthorizationUtils { Date endDate = null; // 05/01/2012 valid date - if(StringUtils.isNotBlank(startDateParam)){ + if (StringUtils.isNotBlank(startDateParam)){ - try { + try + { startDate = DateUtils.parseDate(startDateParam, new String[]{"yyyy-MM-dd", "yyyy-MM", "yyyy"}); - } catch (ParseException e) { + } + catch (ParseException e) + { startDate = null; } - if(startDate==null){ + if (startDate==null) + { result.setContinue(false); result.addError("startDate"); return result; } } - if(StringUtils.isNotBlank(endDateParam)){ - try { + if (StringUtils.isNotBlank(endDateParam)) + { + try + { endDate = DateUtils.parseDate(endDateParam, new String[]{"yyyy-MM-dd", "yyyy-MM", "yyyy"}); - } catch (ParseException e) { + } + catch (ParseException e) + { endDate = null; } - if(endDate==null){ + if (endDate == null) + { result.setContinue(false); result.addError("endDate"); return result; } } - if(endDate!=null && startDate!=null){ - if(startDate.after(endDate)){ + if (endDate != null && startDate != null) + { + if (startDate.after(endDate)) + { result.setContinue(false); result.addError("startDateGreaterThenEndDate"); return result; @@ -204,17 +228,21 @@ public class FlowAuthorizationUtils { } // end check dates - DSpaceObject dso = ContentServiceFactory.getInstance().getDSpaceObjectService(objectType).find(context, objectID); - // check if a similar policy is already in place - if(policy==null){ - if(authorizeService.isAnIdenticalPolicyAlreadyInPlace(context, dso, groupService.find(context, groupID), actionID, -1)){ + DSpaceObject dso = ContentServiceFactory.getInstance().getDSpaceObjectService(objectType).find(context, objectID); + // check if a similar policy is already in place + if (policy == null) + { + if (authorizeService.isAnIdenticalPolicyAlreadyInPlace(context, dso, groupService.find(context, groupID), actionID, -1)) + { result.setContinue(false); result.addError("duplicatedPolicy"); return result; } } - else{ - if(authorizeService.isAnIdenticalPolicyAlreadyInPlace(context, dso, groupService.find(context, groupID), actionID, policy.getID())){ + else + { + if (authorizeService.isAnIdenticalPolicyAlreadyInPlace(context, dso, groupService.find(context, groupID), actionID, policy.getID())) + { result.setContinue(false); result.addError("duplicatedPolicy"); return result; @@ -222,168 +250,184 @@ public class FlowAuthorizationUtils { } /* If the policy doesn't exist, create a new one and set its parent resource */ - DSpaceObject policyParent = null; - if (policy == null) - { - switch (objectType) { - case Constants.COMMUNITY: - { - policyParent = communityService.find(context, objectID); - AuthorizeUtil.authorizeManageCommunityPolicy(context, (Community)policyParent); - break; - } - case Constants.COLLECTION: - { - policyParent = collectionService.find(context, objectID); - AuthorizeUtil.authorizeManageCollectionPolicy(context, (Collection)policyParent); - break; - } - case Constants.ITEM: - { - policyParent = itemService.find(context, objectID); - AuthorizeUtil.authorizeManageItemPolicy(context, (Item) policyParent); - break; - } - case Constants.BUNDLE: - { - policyParent = bundleService.find(context, objectID); - AuthorizeUtil.authorizeManageItemPolicy(context, (Item) (bundleService.getParentObject(context, (Bundle) policyParent))); - break; - } - case Constants.BITSTREAM: - { - policyParent = bitstreamService.find(context, objectID); - AuthorizeUtil - .authorizeManageItemPolicy(context, (Item) (bitstreamService.getParentObject(context, (Bitstream) policyParent))); - break; - } - default: - //If we can't find a parent the policy will receive a NULL dspace object, this is not something we want. - throw new IllegalArgumentException("Invalid DSpaceObject type provided"); - } - policy = resourcePolicyService.create(context); - policy.setdSpaceObject(policyParent); + DSpaceObject policyParent = null; + if (policy == null) + { + switch (objectType) { + case Constants.COMMUNITY: + { + policyParent = communityService.find(context, objectID); + AuthorizeUtil.authorizeManageCommunityPolicy(context, (Community)policyParent); + break; + } + case Constants.COLLECTION: + { + policyParent = collectionService.find(context, objectID); + AuthorizeUtil.authorizeManageCollectionPolicy(context, (Collection)policyParent); + break; + } + case Constants.ITEM: + { + policyParent = itemService.find(context, objectID); + AuthorizeUtil.authorizeManageItemPolicy(context, (Item) policyParent); + break; + } + case Constants.BUNDLE: + { + policyParent = bundleService.find(context, objectID); + AuthorizeUtil.authorizeManageItemPolicy(context, (Item) (bundleService.getParentObject(context, (Bundle) policyParent))); + break; + } + case Constants.BITSTREAM: + { + policyParent = bitstreamService.find(context, objectID); + AuthorizeUtil + .authorizeManageItemPolicy(context, (Item) (bitstreamService.getParentObject(context, (Bitstream) policyParent))); + break; + } + default: + //If we can't find a parent the policy will receive a NULL dspace object, this is not something we want. + throw new IllegalArgumentException("Invalid DSpaceObject type provided"); + } + policy = resourcePolicyService.create(context); + policy.setdSpaceObject(policyParent); policy.setRpType(ResourcePolicy.TYPE_CUSTOM); - added = true; - } - - Group group = groupService.find(context, groupID); - - // modify the policy - policy.setAction(actionID); - policy.setGroup(group); + added = true; + } + + Group group = groupService.find(context, groupID); + + // modify the policy + policy.setAction(actionID); + policy.setGroup(group); policy.setRpName(name); policy.setRpDescription(description); - if(endDate!=null) policy.setEndDate(endDate); - else policy.setEndDate(null); + if (endDate != null) + { + policy.setEndDate(endDate); + } + else + { + policy.setEndDate(null); + } - if(startDate!=null) policy.setStartDate(startDate); - else policy.setStartDate(null); + if (startDate != null) + { + policy.setStartDate(startDate); + } + else + { + policy.setStartDate(null); + } - - // propagate the changes to the logo, which is treated on the same level as the parent object - Bitstream logo = null; - DSpaceObject logoContainer = null; - if (objectType == Constants.COLLECTION) - { - logoContainer = collectionService.find(context, objectID); - logo = ((Collection)logoContainer).getLogo(); - } - else if (objectType == Constants.COMMUNITY) - { - logoContainer = communityService.find(context, objectID); - logo = ((Community)logoContainer).getLogo(); - } - - if (logo != null) - { - List policySet = authorizeService.getPolicies(context, logoContainer); - authorizeService.removeAllPolicies(context, logo); - authorizeService.addPolicies(context, policySet, logo); - } - - // Perform the update action - resourcePolicyService.update(context, policy); - result.setContinue(true); - result.setOutcome(true); - if (added) + // propagate the changes to the logo, which is treated on the same level as the parent object + Bitstream logo = null; + DSpaceObject logoContainer = null; + if (objectType == Constants.COLLECTION) + { + logoContainer = collectionService.find(context, objectID); + logo = ((Collection)logoContainer).getLogo(); + } + else if (objectType == Constants.COMMUNITY) + { + logoContainer = communityService.find(context, objectID); + logo = ((Community)logoContainer).getLogo(); + } + + if (logo != null) + { + List policySet = authorizeService.getPolicies(context, logoContainer); + authorizeService.removeAllPolicies(context, logo); + authorizeService.addPolicies(context, policySet, logo); + } + + // Perform the update action + resourcePolicyService.update(context, policy); + + result.setContinue(true); + result.setOutcome(true); + if (added) { result.setMessage(new Message("default", "A new policy was created successfully")); } - else + else { result.setMessage(new Message("default", "The policy was edited successfully")); } - - result.setParameter("policyID", policy.getID()); - - return result; - } + + result.setParameter("policyID", policy.getID()); + + return result; + } /** - * Delete the policies specified by the policyIDs parameter. This assumes that the - * deletion has been confirmed. - * - * @param context The current DSpace context - * @param policyIDs The unique ids of the policies being deleted. - * @return A process result's object. + * Delete the policies specified by the policyIDs parameter. This assumes that the + * deletion has been confirmed. + * + * @param context The current DSpace context + * @param policyIDs The unique ids of the policies being deleted. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processDeletePolicies(Context context, String[] policyIDs) - throws NumberFormatException, SQLException, AuthorizeException - { - FlowResult result = new FlowResult(); - - for (String id : policyIDs) - { - ResourcePolicy policyDeleted = resourcePolicyService.find(context, Integer.valueOf(id)); - // check authorization - AuthorizeUtil.authorizeManagePolicy(context, policyDeleted); - resourcePolicyService.delete(context, policyDeleted); - } - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(new Message("default","The policies were deleted successfully")); - - return result; - } + */ + public static FlowResult processDeletePolicies(Context context, String[] policyIDs) + throws NumberFormatException, SQLException, AuthorizeException + { + FlowResult result = new FlowResult(); - /** - * Process addition of a several authorizations at once, as entered in the wildcard/advanced authorizations tool. - * - * @param context The current DSpace context. - * @param groupIDs The IDs of the groups to be associated with the newly created policies - * @param actionID The ID of the action to be associated with the policies - * @param resourceID Whether the policies will apply to Items or Bitstreams - * @param collectionIDs The IDs of the collections that the policies will be applied to + for (String id : policyIDs) + { + ResourcePolicy policyDeleted = resourcePolicyService.find(context, Integer.valueOf(id)); + // check authorization + AuthorizeUtil.authorizeManagePolicy(context, policyDeleted); + resourcePolicyService.delete(context, policyDeleted); + } + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(new Message("default", + "The policies were deleted successfully")); + + return result; + } + + /** + * Process addition of a several authorizations at once, as entered in the wildcard/advanced authorizations tool. + * + * @param context The current DSpace context. + * @param groupIDs The IDs of the groups to be associated with the newly created policies + * @param actionID The ID of the action to be associated with the policies + * @param resourceID Whether the policies will apply to Items or Bitstreams + * @param collectionIDs The IDs of the collections that the policies will be applied to * @param name name the policy. * @param description describe the policy. * @param startDateParam start enforcing the policy now. * @param endDateParam stop enforcing the policy now. - * @return A process result's object. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processAdvancedPolicyAdd(Context context, String[] groupIDs, int actionID, - int resourceID, String [] collectionIDs, String name, String description, String startDateParam, String endDateParam) - throws NumberFormatException, SQLException, AuthorizeException - { - AuthorizeUtil.requireAdminRole(context); - FlowResult result = new FlowResult(); + */ + public static FlowResult processAdvancedPolicyAdd(Context context, + String[] groupIDs, int actionID, int resourceID, String[] collectionIDs, + String name, String description, String startDateParam, String endDateParam) + throws NumberFormatException, SQLException, AuthorizeException + { + AuthorizeUtil.requireAdminRole(context); + FlowResult result = new FlowResult(); - if(groupIDs==null){ + if (groupIDs == null) + { result.setContinue(false); result.addError("groupIDs"); return result; } - if(collectionIDs==null){ + if (collectionIDs == null) + { result.setContinue(false); result.addError("collectionIDs"); return result; @@ -394,34 +438,45 @@ public class FlowAuthorizationUtils { Date endDate = null; // 05/01/2012 valid date - if(StringUtils.isNotBlank(startDateParam)){ - try { + if (StringUtils.isNotBlank(startDateParam)) + { + try + { startDate = DateUtils.parseDate(startDateParam, new String[]{"yyyy-MM-dd", "yyyy-MM", "yyyy"}); - } catch (ParseException e) { + } + catch (ParseException e) + { startDate = null; } - if(startDate==null){ + if (startDate==null) + { result.setContinue(false); result.addError("startDate"); return result; } } - if(StringUtils.isNotBlank(endDateParam)){ - try { + if (StringUtils.isNotBlank(endDateParam)){ + try + { endDate = DateUtils.parseDate(endDateParam, new String[]{"yyyy-MM-dd", "yyyy-MM", "yyyy"}); - } catch (ParseException e) { + } + catch (ParseException e) + { endDate = null; } - if(endDate==null){ + if (endDate==null) + { result.setContinue(false); result.addError("endDate"); return result; } } - if(endDate!=null && startDate!=null){ - if(startDate.after(endDate)){ + if (endDate!=null && startDate!=null) + { + if (startDate.after(endDate)) + { result.setContinue(false); result.addError("startDateGreaterThenEndDate"); return result; @@ -429,64 +484,70 @@ public class FlowAuthorizationUtils { } // end check dates - for (String groupID : groupIDs) - { - for (String collectionID : collectionIDs) - { - PolicySet.setPolicies(context, Constants.COLLECTION, UUID.fromString(collectionID), - resourceID, actionID, UUID.fromString(groupID), false, false, name, description, startDate, endDate); - - // if it's a bitstream, do it to the bundle too - if (resourceID == Constants.BITSTREAM) - { - PolicySet.setPolicies(context, Constants.COLLECTION, UUID.fromString(collectionID), - Constants.BUNDLE, actionID, UUID.fromString(groupID), false, false, name, description, startDate, endDate); - } - } - } - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(new Message("default","The policies were added successfully!")); - - return result; - } - - /** - * Process the deletion of all authorizations across a set of collections, regardless of associated - * actions or groups. This functionality should probably not be used, ever, unless the goal to - * completely reset a collection for one reason or another. - * - * @param context The current DSpace context. - * @param resourceID Whether the policies will apply to Items or Bitstreams - * @param collectionIDs The IDs of the collections that the policy wipe will be applied to - * @return A process result's object. + for (String groupID : groupIDs) + { + for (String collectionID : collectionIDs) + { + PolicySet.setPolicies(context, Constants.COLLECTION, + UUID.fromString(collectionID), resourceID, actionID, + UUID.fromString(groupID), false, false, name, description, + startDate, endDate); + + // if it's a bitstream, do it to the bundle too + if (resourceID == Constants.BITSTREAM) + { + PolicySet.setPolicies(context, Constants.COLLECTION, + UUID.fromString(collectionID), Constants.BUNDLE, + actionID, UUID.fromString(groupID), false, false, name, + description, startDate, endDate); + } + } + } + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(new Message("default","The policies were added successfully!")); + + return result; + } + + /** + * Process the deletion of all authorizations across a set of collections, regardless of associated + * actions or groups. This functionality should probably not be used, ever, unless the goal to + * completely reset a collection for one reason or another. + * + * @param context The current DSpace context. + * @param resourceID Whether the policies will apply to Items or Bitstreams + * @param collectionIDs The IDs of the collections that the policy wipe will be applied to + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processAdvancedPolicyDelete(Context context, int resourceID, String [] collectionIDs) - throws NumberFormatException, SQLException, AuthorizeException - { - AuthorizeUtil.requireAdminRole(context); - FlowResult result = new FlowResult(); - - for (String collectionID : collectionIDs) - { - PolicySet.setPolicies(context, Constants.COLLECTION, UUID.fromString(collectionID), - resourceID, 0, null, false, true); - - // if it's a bitstream, do it to the bundle too - if (resourceID == Constants.BITSTREAM) - { - PolicySet.setPolicies(context, Constants.COLLECTION, UUID.fromString(collectionID), - Constants.BUNDLE, 0, null, false, true); - } - } - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(new Message("default","The policies for the selected collections were cleared.")); - - return result; - } + */ + public static FlowResult processAdvancedPolicyDelete(Context context, int resourceID, String [] collectionIDs) + throws NumberFormatException, SQLException, AuthorizeException + { + AuthorizeUtil.requireAdminRole(context); + FlowResult result = new FlowResult(); + + for (String collectionID : collectionIDs) + { + PolicySet.setPolicies(context, Constants.COLLECTION, UUID.fromString(collectionID), + resourceID, 0, null, false, true); + + // if it's a bitstream, do it to the bundle too + if (resourceID == Constants.BITSTREAM) + { + PolicySet.setPolicies(context, Constants.COLLECTION, + UUID.fromString(collectionID), Constants.BUNDLE, 0, null, + false, true); + } + } + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(new Message("default", + "The policies for the selected collections were cleared.")); + + return result; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowContainerUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowContainerUtils.java index 36cf700050..0db6f74ca1 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowContainerUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowContainerUtils.java @@ -68,119 +68,119 @@ import java.util.UUID; public class FlowContainerUtils { - /** Possible Collection roles */ - public static final String ROLE_ADMIN = "ADMIN"; - public static final String ROLE_WF_STEP1 = "WF_STEP1"; - public static final String ROLE_WF_STEP2 = "WF_STEP2"; - public static final String ROLE_WF_STEP3 = "WF_STEP3"; - public static final String ROLE_SUBMIT = "SUBMIT"; - public static final String ROLE_DEFAULT_READ = "DEFAULT_READ"; + /** Possible Collection roles */ + public static final String ROLE_ADMIN = "ADMIN"; + public static final String ROLE_WF_STEP1 = "WF_STEP1"; + public static final String ROLE_WF_STEP2 = "WF_STEP2"; + public static final String ROLE_WF_STEP3 = "WF_STEP3"; + public static final String ROLE_SUBMIT = "SUBMIT"; + public static final String ROLE_DEFAULT_READ = "DEFAULT_READ"; - protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected static final ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); - protected static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); - protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected static final ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); + protected static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - protected static final HarvestedCollectionService harvestedCollectionService = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); - protected static final WorkflowService workflowService = WorkflowServiceFactory.getInstance().getWorkflowService(); + protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + protected static final HarvestedCollectionService harvestedCollectionService = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); + protected static final WorkflowService workflowService = WorkflowServiceFactory.getInstance().getWorkflowService(); - - // Collection related functions + + // Collection related functions - /** - * Process the collection metadata edit form. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @param deleteLogo Determines if the logo should be deleted along with the metadata editing action. - * @param request the Cocoon request object - * @return A process result's object. + /** + * Process the collection metadata edit form. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @param deleteLogo Determines if the logo should be deleted along with the metadata editing action. + * @param request the Cocoon request object + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processEditCollection(Context context, UUID collectionID, boolean deleteLogo, Request request) throws SQLException, IOException, AuthorizeException - { - FlowResult result = new FlowResult(); - - Collection collection = collectionService.find(context, collectionID); - - // Get the metadata - String name = request.getParameter("name"); - String shortDescription = request.getParameter("short_description"); - String introductoryText = request.getParameter("introductory_text"); - String copyrightText = request.getParameter("copyright_text"); - String sideBarText = request.getParameter("side_bar_text"); - String license = request.getParameter("license"); - String provenanceDescription = request.getParameter("provenance_description"); - - // If they don't have a name then make it untitled. - if (name == null || name.length() == 0) + */ + public static FlowResult processEditCollection(Context context, UUID collectionID, boolean deleteLogo, Request request) throws SQLException, IOException, AuthorizeException + { + FlowResult result = new FlowResult(); + + Collection collection = collectionService.find(context, collectionID); + + // Get the metadata + String name = request.getParameter("name"); + String shortDescription = request.getParameter("short_description"); + String introductoryText = request.getParameter("introductory_text"); + String copyrightText = request.getParameter("copyright_text"); + String sideBarText = request.getParameter("side_bar_text"); + String license = request.getParameter("license"); + String provenanceDescription = request.getParameter("provenance_description"); + + // If they don't have a name then make it untitled. + if (name == null || name.length() == 0) { name = "Untitled"; } - // If empty, make it null. - if (shortDescription != null && shortDescription.length() == 0) + // If empty, make it null. + if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } - if (introductoryText != null && introductoryText.length() == 0) + if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } - if (copyrightText != null && copyrightText.length() == 0) + if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } - if (sideBarText != null && sideBarText.length() == 0) + if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } - if (license != null && license.length() == 0) + if (license != null && license.length() == 0) { license = null; } - if (provenanceDescription != null && provenanceDescription.length() == 0) + if (provenanceDescription != null && provenanceDescription.length() == 0) { provenanceDescription = null; } - - // Save the metadata - collectionService.setMetadata(context, collection, "name", name); - collectionService.setMetadata(context, collection, "short_description", shortDescription); - collectionService.setMetadata(context, collection, "introductory_text", introductoryText); - collectionService.setMetadata(context, collection, "copyright_text", copyrightText); - collectionService.setMetadata(context, collection, "side_bar_text", sideBarText); - collectionService.setMetadata(context, collection, "license", license); - collectionService.setMetadata(context, collection, "provenance_description", provenanceDescription); - - // Change or delete the logo + // Save the metadata + collectionService.setMetadata(context, collection, "name", name); + collectionService.setMetadata(context, collection, "short_description", shortDescription); + collectionService.setMetadata(context, collection, "introductory_text", introductoryText); + collectionService.setMetadata(context, collection, "copyright_text", copyrightText); + collectionService.setMetadata(context, collection, "side_bar_text", sideBarText); + collectionService.setMetadata(context, collection, "license", license); + collectionService.setMetadata(context, collection, "provenance_description", provenanceDescription); + + + // Change or delete the logo if (deleteLogo) { - // Remove the logo - collectionService.setLogo(context, collection, null); + // Remove the logo + collectionService.setLogo(context, collection, null); } else { - // Update the logo - Object object = request.get("logo"); - Part filePart = null; - if (object instanceof Part) + // Update the logo + Object object = request.get("logo"); + Part filePart = null; + if (object instanceof Part) { filePart = (Part) object; } - if (filePart != null && filePart.getSize() > 0) - { - InputStream is = filePart.getInputStream(); - - collectionService.setLogo(context, collection, is); - } + if (filePart != null && filePart.getSize() > 0) + { + InputStream is = filePart.getInputStream(); + + collectionService.setLogo(context, collection, is); + } } // Save everything @@ -189,54 +189,54 @@ public class FlowContainerUtils // No notice... result.setContinue(true); - - return result; - } - - /** - * Process the collection harvesting options form. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @param request the Cocoon request object - * @return A process result's object. + + return result; + } + + /** + * Process the collection harvesting options form. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @param request the Cocoon request object + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processSetupCollectionHarvesting(Context context, UUID collectionID, Request request) throws SQLException, IOException, AuthorizeException - { - FlowResult result = new FlowResult(); - Collection collection = collectionService.find(context, collectionID); - HarvestedCollection hc = harvestedCollectionService.find(context, collection); + */ + public static FlowResult processSetupCollectionHarvesting(Context context, UUID collectionID, Request request) throws SQLException, IOException, AuthorizeException + { + FlowResult result = new FlowResult(); + Collection collection = collectionService.find(context, collectionID); + HarvestedCollection hc = harvestedCollectionService.find(context, collection); - String contentSource = request.getParameter("source"); + String contentSource = request.getParameter("source"); - // First, if this is not a harvested collection (anymore), set the harvest type to 0; possibly also wipe harvest settings - if (contentSource.equals("source_normal")) - { - if (hc != null) + // First, if this is not a harvested collection (anymore), set the harvest type to 0; possibly also wipe harvest settings + if (contentSource.equals("source_normal")) + { + if (hc != null) { - harvestedCollectionService.delete(context, hc); + harvestedCollectionService.delete(context, hc); } - - result.setContinue(true); - } - else - { - FlowResult subResult = testOAISettings(context, request); - - // create a new harvest instance if all the settings check out - if (hc == null) { - hc = harvestedCollectionService.create(context, collection); - } - - // if the supplied options all check out, set the harvesting parameters on the collection - if (subResult.getErrors().isEmpty()) { - String oaiProvider = request.getParameter("oai_provider"); - boolean oaiAllSets = "all".equals(request.getParameter("oai-set-setting")); + + result.setContinue(true); + } + else + { + FlowResult subResult = testOAISettings(context, request); + + // create a new harvest instance if all the settings check out + if (hc == null) { + hc = harvestedCollectionService.create(context, collection); + } + + // if the supplied options all check out, set the harvesting parameters on the collection + if (subResult.getErrors().isEmpty()) { + String oaiProvider = request.getParameter("oai_provider"); + boolean oaiAllSets = "all".equals(request.getParameter("oai-set-setting")); String oaiSetId; - if(oaiAllSets) + if (oaiAllSets) { oaiSetId = "all"; } @@ -246,226 +246,227 @@ public class FlowContainerUtils } - String metadataKey = request.getParameter("metadata_format"); - String harvestType = request.getParameter("harvest_level"); - - hc.setHarvestParams(Integer.parseInt(harvestType), oaiProvider, oaiSetId, metadataKey); - hc.setHarvestStatus(HarvestedCollection.STATUS_READY); - } - else { - result.setErrors(subResult.getErrors()); - result.setContinue(false); - return result; - } - - harvestedCollectionService.update(context, hc); - } - + String metadataKey = request.getParameter("metadata_format"); + String harvestType = request.getParameter("harvest_level"); + + hc.setHarvestParams(Integer.parseInt(harvestType), oaiProvider, oaiSetId, metadataKey); + hc.setHarvestStatus(HarvestedCollection.STATUS_READY); + } + else + { + result.setErrors(subResult.getErrors()); + result.setContinue(false); + return result; + } + + harvestedCollectionService.update(context, hc); + } + // No notice... - //result.setMessage(new Message("default","Harvesting options successfully modified.")); + //result.setMessage(new Message("default", "Harvesting options successfully modified.")); result.setOutcome(true); result.setContinue(true); - - return result; - } - - - /** - * Use the collection's harvest settings to immediately perform a harvest cycle. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @param request the Cocoon request object - * @return A process result's object. + + return result; + } + + + /** + * Use the collection's harvest settings to immediately perform a harvest cycle. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @param request the Cocoon request object + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - * @throws TransformerException passed through. - * @throws SAXException passed through. - * @throws ParserConfigurationException passed through. - * @throws CrosswalkException passed through. - */ - public static FlowResult processRunCollectionHarvest(Context context, UUID collectionID, Request request) + * @throws TransformerException passed through. + * @throws SAXException passed through. + * @throws ParserConfigurationException passed through. + * @throws CrosswalkException passed through. + */ + public static FlowResult processRunCollectionHarvest(Context context, UUID collectionID, Request request) throws SQLException, IOException, AuthorizeException, CrosswalkException, ParserConfigurationException, SAXException, TransformerException - { - FlowResult result = new FlowResult(); - OAIHarvester harvester; - List testErrors = new ArrayList(); - Collection collection = collectionService.find(context, collectionID); - HarvestedCollection hc = harvestedCollectionService.find(context, collection); + { + FlowResult result = new FlowResult(); + OAIHarvester harvester; + List testErrors = new ArrayList(); + Collection collection = collectionService.find(context, collectionID); + HarvestedCollection hc = harvestedCollectionService.find(context, collection); - //TODO: is there a cleaner way to do this? - try - { - if (!HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_STOPPED)) { - synchronized(HarvestScheduler.lock) { - HarvestScheduler.setInterrupt(HarvestScheduler.HARVESTER_INTERRUPT_INSERT_THREAD, collectionID); - HarvestScheduler.lock.notify(); - } - } - else { - // Harvester should return some errors in my opinion.. - harvester = new OAIHarvester(context, collection, hc); - harvester.runHarvest(); // this throws an exception when fetching bitstreams. - } - } - catch (Exception e) { - testErrors.add(e.getMessage()); - result.setErrors(testErrors); - result.setContinue(false); - return result; - } - + //TODO: is there a cleaner way to do this? + try + { + if (!HarvestScheduler.hasStatus(HarvestScheduler.HARVESTER_STATUS_STOPPED)) { + synchronized(HarvestScheduler.lock) { + HarvestScheduler.setInterrupt(HarvestScheduler.HARVESTER_INTERRUPT_INSERT_THREAD, collectionID); + HarvestScheduler.lock.notify(); + } + } + else { + // Harvester should return some errors in my opinion.. + harvester = new OAIHarvester(context, collection, hc); + harvester.runHarvest(); // this throws an exception when fetching bitstreams. + } + } + catch (Exception e) { + testErrors.add(e.getMessage()); + result.setErrors(testErrors); + result.setContinue(false); + return result; + } + result.setContinue(true); - - return result; - } + + return result; + } - /** - * Purge the collection of all items, then run a fresh harvest cycle. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @param request the Cocoon request object - * @return A process result's object. + /** + * Purge the collection of all items, then run a fresh harvest cycle. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @param request the Cocoon request object + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - * @throws TransformerException passed through. - * @throws SAXException passed through. - * @throws ParserConfigurationException passed through. - * @throws CrosswalkException passed through. - * @throws BrowseException passed through. - */ - public static FlowResult processReimportCollection(Context context, UUID collectionID, Request request) throws SQLException, IOException, AuthorizeException, CrosswalkException, ParserConfigurationException, SAXException, TransformerException, BrowseException - { - boolean originalMode = context.isBatchModeEnabled(); - context.enableBatchMode(true); + * @throws TransformerException passed through. + * @throws SAXException passed through. + * @throws ParserConfigurationException passed through. + * @throws CrosswalkException passed through. + * @throws BrowseException passed through. + */ + public static FlowResult processReimportCollection(Context context, UUID collectionID, Request request) throws SQLException, IOException, AuthorizeException, CrosswalkException, ParserConfigurationException, SAXException, TransformerException, BrowseException + { + boolean originalMode = context.isBatchModeEnabled(); + context.enableBatchMode(true); - Collection collection = collectionService.find(context, collectionID); - HarvestedCollection hc = harvestedCollectionService.find(context, collection); - - Iterator it = itemService.findByCollection(context, collection); - //IndexBrowse ib = new IndexBrowse(context); - while (it.hasNext()) { - Item item = it.next(); - //System.out.println("Deleting: " + item.getHandle()); - //ib.itemRemoved(item); - collectionService.removeItem(context, collection, item); + Collection collection = collectionService.find(context, collectionID); + HarvestedCollection hc = harvestedCollectionService.find(context, collection); + + Iterator it = itemService.findByCollection(context, collection); + //IndexBrowse ib = new IndexBrowse(context); + while (it.hasNext()) { + Item item = it.next(); + //System.out.println("Deleting: " + item.getHandle()); + //ib.itemRemoved(item); + collectionService.removeItem(context, collection, item); - } + } - hc.setLastHarvested(null); - hc.setHarvestMessage(""); - harvestedCollectionService.update(context, hc); - collectionService.update(context, collection); + hc.setLastHarvested(null); + hc.setHarvestMessage(""); + harvestedCollectionService.update(context, hc); + collectionService.update(context, collection); // update the context? - //context.dispatchEvent() // not sure if this is required yet.ts(); + //context.dispatchEvent() // not sure if this is required yet.ts(); - context.enableBatchMode(originalMode); + context.enableBatchMode(originalMode); - return processRunCollectionHarvest(context, collectionID, request); - } + return processRunCollectionHarvest(context, collectionID, request); + } - /** - * Test the supplied OAI settings. - * - * @param context session context. - * @param request user's request. + /** + * Test the supplied OAI settings. + * + * @param context session context. + * @param request user's request. * @return result of testing. - */ - public static FlowResult testOAISettings(Context context, Request request) - { - FlowResult result = new FlowResult(); - - String oaiProvider = request.getParameter("oai_provider"); - String oaiSetId = request.getParameter("oai_setid"); + */ + public static FlowResult testOAISettings(Context context, Request request) + { + FlowResult result = new FlowResult(); + + String oaiProvider = request.getParameter("oai_provider"); + String oaiSetId = request.getParameter("oai_setid"); oaiSetId = request.getParameter("oai-set-setting"); - if(!"all".equals(oaiSetId)) + if (!"all".equals(oaiSetId)) { oaiSetId = request.getParameter("oai_setid"); } - String metadataKey = request.getParameter("metadata_format"); - String harvestType = request.getParameter("harvest_level"); - int harvestTypeInt = 0; - - if (oaiProvider == null || oaiProvider.length() == 0) + String metadataKey = request.getParameter("metadata_format"); + String harvestType = request.getParameter("harvest_level"); + int harvestTypeInt = 0; + + if (oaiProvider == null || oaiProvider.length() == 0) { result.addError("oai_provider"); } - if (oaiSetId == null || oaiSetId.length() == 0) + if (oaiSetId == null || oaiSetId.length() == 0) { result.addError("oai_setid"); } - if (metadataKey == null || metadataKey.length() == 0) + if (metadataKey == null || metadataKey.length() == 0) { result.addError("metadata_format"); } - if (harvestType == null || harvestType.length() == 0) + if (harvestType == null || harvestType.length() == 0) { result.addError("harvest_level"); } - else + else { harvestTypeInt = Integer.parseInt(harvestType); } - if (result.getErrors() == null) { - List testErrors = OAIHarvester.verifyOAIharvester(oaiProvider, oaiSetId, metadataKey, (harvestTypeInt>1)); - result.setErrors(testErrors); - } - - if (result.getErrors() == null || result.getErrors().isEmpty()) { - result.setOutcome(true); - // On a successful test we still want to stay in the loop, not continue out of it - //result.setContinue(true); - result.setMessage(new Message("default","Harvesting settings are valid.")); - } - else { - result.setOutcome(false); - result.setContinue(false); - // don't really need a message when the errors are highlighted already - //result.setMessage(new Message("default","Harvesting is not properly configured.")); - } + if (result.getErrors() == null) { + List testErrors = OAIHarvester.verifyOAIharvester(oaiProvider, oaiSetId, metadataKey, (harvestTypeInt>1)); + result.setErrors(testErrors); + } + + if (result.getErrors() == null || result.getErrors().isEmpty()) { + result.setOutcome(true); + // On a successful test we still want to stay in the loop, not continue out of it + //result.setContinue(true); + result.setMessage(new Message("default","Harvesting settings are valid.")); + } + else { + result.setOutcome(false); + result.setContinue(false); + // don't really need a message when the errors are highlighted already + //result.setMessage(new Message("default","Harvesting is not properly configured.")); + } - return result; - } - - /** - * Look up the id of the template item for a given collection. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @return The id of the template item. + return result; + } + + /** + * Look up the id of the template item for a given collection. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @return The id of the template item. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - * @throws IOException passed through. - */ - public static UUID getTemplateItemID(Context context, UUID collectionID) throws SQLException, AuthorizeException, IOException - { - Collection collection = collectionService.find(context, collectionID); - Item template = collection.getTemplateItem(); - - if (template == null) - { - collectionService.createTemplateItem(context, collection); - template = collection.getTemplateItem(); - - collectionService.update(context, collection); - itemService.update(context, template); - } - - return template.getID(); - } + * @throws IOException passed through. + */ + public static UUID getTemplateItemID(Context context, UUID collectionID) throws SQLException, AuthorizeException, IOException + { + Collection collection = collectionService.find(context, collectionID); + Item template = collection.getTemplateItem(); + + if (template == null) + { + collectionService.createTemplateItem(context, collection); + template = collection.getTemplateItem(); + + collectionService.update(context, collection); + itemService.update(context, template); + } + + return template.getID(); + } - /** - * Look up the id of a group authorized for one of the given roles. If no group is currently - * authorized to perform this role then a new group will be created and assigned the role. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ. - * @return The id of the group associated with that particular role, or -1 if the role was not found. + /** + * Look up the id of a group authorized for one of the given roles. If no group is currently + * authorized to perform this role then a new group will be created and assigned the role. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ. + * @return The id of the group associated with that particular role, or -1 if the role was not found. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. @@ -474,77 +475,78 @@ public class FlowContainerUtils * @throws org.dspace.xmlworkflow.WorkflowConfigurationException passed through. * @throws javax.xml.parsers.ParserConfigurationException passed through. * @throws org.dspace.workflow.WorkflowException passed through. - */ - public static UUID getCollectionRole(Context context, UUID collectionID, String roleName) + */ + public static UUID getCollectionRole(Context context, UUID collectionID, String roleName) throws SQLException, AuthorizeException, IOException, TransformerException, SAXException, WorkflowConfigurationException, - ParserConfigurationException, WorkflowException { - Collection collection = collectionService.find(context, collectionID); + ParserConfigurationException, WorkflowException + { + Collection collection = collectionService.find(context, collectionID); - // Determine the group based upon wich role we are looking for. - Group roleGroup = null; - if (ROLE_ADMIN.equals(roleName)) - { - roleGroup = collection.getAdministrators(); - if (roleGroup == null){ - roleGroup = collectionService.createAdministrators(context, collection); + // Determine the group based upon wich role we are looking for. + Group roleGroup = null; + if (ROLE_ADMIN.equals(roleName)) + { + roleGroup = collection.getAdministrators(); + if (roleGroup == null) { + roleGroup = collectionService.createAdministrators(context, collection); } - } - else if (ROLE_SUBMIT.equals(roleName)) - { - roleGroup = collection.getSubmitters(); - if (roleGroup == null) - roleGroup = collectionService.createSubmitters(context, collection); - }else{ - roleGroup = workflowService.getWorkflowRoleGroup(context, collection, roleName, roleGroup); - } + } + else if (ROLE_SUBMIT.equals(roleName)) + { + roleGroup = collection.getSubmitters(); + if (roleGroup == null) + roleGroup = collectionService.createSubmitters(context, collection); + } else { + roleGroup = workflowService.getWorkflowRoleGroup(context, collection, roleName, roleGroup); + } - // In case we needed to create a group, save our changes - collectionService.update(context, collection); + // In case we needed to create a group, save our changes + collectionService.update(context, collection); - // If the role name was valid then role should be non null, - if (roleGroup != null) - return roleGroup.getID(); + // If the role name was valid then role should be non null, + if (roleGroup != null) + return roleGroup.getID(); - return null; + return null; } - /** - * Delete one of collection's roles - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ. - * @param groupID The id of the group associated with this role. - * @return A process result's object. + /** + * Delete one of collection's roles + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ. + * @param groupID The id of the group associated with this role. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws java.io.IOException passed through. * @throws org.dspace.xmlworkflow.WorkflowConfigurationException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processDeleteCollectionRole(Context context, UUID collectionID, String roleName, UUID groupID) + */ + public static FlowResult processDeleteCollectionRole(Context context, UUID collectionID, String roleName, UUID groupID) throws SQLException, UIException, IOException, AuthorizeException, WorkflowConfigurationException { - FlowResult result = new FlowResult(); - - Collection collection = collectionService.find(context,collectionID); - Group role = groupService.find(context, groupID); - - // First, Unregister the role - if (ROLE_ADMIN.equals(roleName)) - { - collectionService.removeAdministrators(context, collection); - } - else if (ROLE_SUBMIT.equals(roleName)) - { - collectionService.removeSubmitters(context, collection); - } - else{ - if(WorkflowServiceFactory.getInstance().getWorkflowService() instanceof XmlWorkflowService) + FlowResult result = new FlowResult(); + + Collection collection = collectionService.find(context,collectionID); + Group role = groupService.find(context, groupID); + + // First, Unregister the role + if (ROLE_ADMIN.equals(roleName)) + { + collectionService.removeAdministrators(context, collection); + } + else if (ROLE_SUBMIT.equals(roleName)) + { + collectionService.removeSubmitters(context, collection); + } + else { + if (WorkflowServiceFactory.getInstance().getWorkflowService() instanceof XmlWorkflowService) { WorkflowUtils.deleteRoleGroup(context, collection, roleName); - }else{ + } else { if (ROLE_WF_STEP1.equals(roleName)) { collection.setWorkflowGroup(1, null); @@ -558,447 +560,462 @@ public class FlowContainerUtils collection.setWorkflowGroup(3, null); } } - } + } - // Second, remove all authorizations for this role by searching for all policies that this - // group has on the collection and remove them otherwise the delete will fail because - // there are dependencies. - @SuppressWarnings("unchecked") // the cast is correct - List policies = authorizeService.getPolicies(context, collection); - for (ResourcePolicy policy : policies) - { - if (policy.getGroup() != null && policy.getGroup().getID().equals(groupID)) + // Second, remove all authorizations for this role by searching for all policies that this + // group has on the collection and remove them otherwise the delete will fail because + // there are dependencies. + @SuppressWarnings("unchecked") // the cast is correct + List policies = authorizeService.getPolicies(context, collection); + for (ResourcePolicy policy : policies) + { + if (policy.getGroup() != null && policy.getGroup().getID().equals(groupID)) { - resourcePolicyService.delete(context, policy); + resourcePolicyService.delete(context, policy); } - } - - // Finally, Delete the role's actual group. - collectionService.update(context, collection); - groupService.delete(context, role); + } + + // Finally, Delete the role's actual group. + collectionService.update(context, collection); + groupService.delete(context, role); - result.setContinue(true); - result.setOutcome(true); - result.setMessage(new Message("default","The role was successfully deleted.")); - return result; - } + result.setContinue(true); + result.setOutcome(true); + result.setMessage(new Message("default","The role was successfully deleted.")); + return result; + } - /** - * Look up the id of a group authorized for one of the given roles. If no group is currently - * authorized to perform this role then a new group will be created and assigned the role. - * - * @param context The current DSpace context. - * @param collection The collection. - * @return The id of the group associated with that particular role or -1 + /** + * Look up the id of a group authorized for one of the given roles. If no group is currently + * authorized to perform this role then a new group will be created and assigned the role. + * FIXME: THIS DOCUMENTATION IS WRONG. PLEASE FIX IT. + * + * @param context The current DSpace context. + * @param collection The collection. + * @return The Group associated with that particular role or -1 * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static Group getCollectionDefaultRead(Context context, Collection collection) throws SQLException, AuthorizeException - { + */ + public static Group getCollectionDefaultRead(Context context, Collection collection) throws SQLException, AuthorizeException + { - List itemGroups = authorizeService.getAuthorizedGroups(context, collection, Constants.DEFAULT_ITEM_READ); - List bitstreamGroups = authorizeService.getAuthorizedGroups(context, collection, Constants.DEFAULT_BITSTREAM_READ); - + List itemGroups = authorizeService.getAuthorizedGroups(context, collection, Constants.DEFAULT_ITEM_READ); + List bitstreamGroups = authorizeService.getAuthorizedGroups(context, collection, Constants.DEFAULT_BITSTREAM_READ); + Group itemGroup = null; - // If there are more than one groups assigned either of these privileges then this role based method will not work. - // The user will need to go to the authorization section to manually straighten this out. - if (itemGroups.size() != 1 || bitstreamGroups.size() != 1) - { + // If there are more than one groups assigned either of these privileges then this role based method will not work. + // The user will need to go to the authorization section to manually straighten this out. + if (itemGroups.size() != 1 || bitstreamGroups.size() != 1) + { itemGroup = null; - } - else - { - itemGroup = itemGroups.get(0); - Group bitstreamGroup = bitstreamGroups.get(0); - + } + else + { + itemGroup = itemGroups.get(0); + Group bitstreamGroup = bitstreamGroups.get(0); + // If the same group is not assigned both of these privileges then this role based method will not work. The user // will need to go to the authorization section to manually straighten this out. - if (!itemGroup.getID().equals(bitstreamGroup.getID())) - { + if (!itemGroup.getID().equals(bitstreamGroup.getID())) + { itemGroup = null; - } - } + } + } - return itemGroup; - } + return itemGroup; + } - /** - * @see #getCollectionDefaultRead(Context, Collection) + /** + * Look up the id of a group authorized for one of the given roles. If no group is currently + * authorized to perform this role then a new group will be created and assigned the role. + * FIXME: THIS DOCUMENTATION IS WRONG. PLEASE FIX IT. + * + * @param context DSpace context. + * @param collectionID The Collection whose roles will be searched. + * @return the UUID of the matching group. + * @throws java.sql.SQLException passed through. + * @throws org.dspace.authorize.AuthorizeException passed through. + * @see #getCollectionDefaultRead(Context, Collection) */ - public static UUID getCollectionDefaultRead(final Context context, final UUID collectionID) throws SQLException, AuthorizeException { - return getCollectionDefaultRead(context, collectionService.find(context,collectionID)).getID(); - } + public static UUID getCollectionDefaultRead(final Context context, final UUID collectionID) throws SQLException, AuthorizeException { + return getCollectionDefaultRead(context, collectionService.find(context,collectionID)).getID(); + } - /** - * Change default privileges from the anonymous group to a new group that will be created and - * appropriate privileges assigned. The id of this new group will be returned. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @return The group ID of the new group. + /** + * Change default privileges from the anonymous group to a new group that will be created and + * appropriate privileges assigned. The id of this new group will be returned. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @return The group ID of the new group. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. - */ - public static UUID createCollectionDefaultReadGroup(Context context, UUID collectionID) throws SQLException, AuthorizeException, UIException - { - Collection collection = collectionService.find(context,collectionID); - Group defaultRead = getCollectionDefaultRead(context, collection); - - if (defaultRead != null && !defaultRead.getName().equals(Group.ANONYMOUS)) + */ + public static UUID createCollectionDefaultReadGroup(Context context, UUID collectionID) throws SQLException, AuthorizeException, UIException + { + Collection collection = collectionService.find(context,collectionID); + Group defaultRead = getCollectionDefaultRead(context, collection); + + if (defaultRead != null && !defaultRead.getName().equals(Group.ANONYMOUS)) { throw new UIException("Unable to create a new default read group because either the group already exists or multiple groups are assigned the default privileges."); } - - Group role = groupService.create(context); + + Group role = groupService.create(context); groupService.setName(role, "COLLECTION_"+collection.getID().toString() +"_DEFAULT_READ"); - - // Remove existing privileges from the anonymous group. - authorizeService.removePoliciesActionFilter(context, collection, Constants.DEFAULT_ITEM_READ); - authorizeService.removePoliciesActionFilter(context, collection, Constants.DEFAULT_BITSTREAM_READ); - - // Grant our new role the default privileges. - authorizeService.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, role); - authorizeService.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, role); - - // Commit the changes - groupService.update(context, role); + + // Remove existing privileges from the anonymous group. + authorizeService.removePoliciesActionFilter( + context, collection, Constants.DEFAULT_ITEM_READ); + authorizeService.removePoliciesActionFilter( + context, collection, Constants.DEFAULT_BITSTREAM_READ); + + // Grant our new role the default privileges. + authorizeService.addPolicy( + context, collection, Constants.DEFAULT_ITEM_READ, role); + authorizeService.addPolicy( + context, collection, Constants.DEFAULT_BITSTREAM_READ, role); + + // Commit the changes + groupService.update(context, role); - return role.getID(); - } - - /** - * Change the default read privileges to the anonymous group. - * - * If getCollectionDefaultRead() returns -1 or the anonymous group then nothing - * is done. - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @return A process result's object. + return role.getID(); + } + + /** + * Change the default read privileges to the anonymous group. + * + * If getCollectionDefaultRead() returns -1 or the anonymous group then nothing + * is done. + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult changeCollectionDefaultReadToAnonymous(Context context, UUID collectionID) + */ + public static FlowResult changeCollectionDefaultReadToAnonymous(Context context, UUID collectionID) throws SQLException, AuthorizeException, UIException, IOException { - FlowResult result = new FlowResult(); - - Collection collection = collectionService.find(context,collectionID); - Group defaultRead = getCollectionDefaultRead(context, collection); - - if (defaultRead == null || defaultRead.getName().equals(Group.ANONYMOUS)) - { - throw new UIException("Unable to delete the default read role because the role is either already assigned to the anonymous group or multiple groups are assigned the default privileges."); - } - - Group anonymous = groupService.findByName(context, Group.ANONYMOUS); - - // Delete the old role, this will remove the default privileges. - groupService.delete(context, defaultRead); - - // Set anonymous as the default read group. - authorizeService.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, anonymous); - authorizeService.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, anonymous); - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(new Message("default","All new items submitted to this collection will default to anonymous read.")); - return result; - } - - /** - * Delete collection itself - * - * @param context The current DSpace context. - * @param collectionID The collection id. - * @return A process result's object. + FlowResult result = new FlowResult(); + + Collection collection = collectionService.find(context,collectionID); + Group defaultRead = getCollectionDefaultRead(context, collection); + + if (defaultRead == null || defaultRead.getName().equals(Group.ANONYMOUS)) + { + throw new UIException("Unable to delete the default read role because the role is either already assigned to the anonymous group or multiple groups are assigned the default privileges."); + } + + Group anonymous = groupService.findByName(context, Group.ANONYMOUS); + + // Delete the old role, this will remove the default privileges. + groupService.delete(context, defaultRead); + + // Set anonymous as the default read group. + authorizeService.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, anonymous); + authorizeService.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, anonymous); + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(new Message("default", + "All new items submitted to this collection will default to anonymous read.")); + return result; + } + + /** + * Delete collection itself + * + * @param context The current DSpace context. + * @param collectionID The collection id. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processDeleteCollection(Context context, UUID collectionID) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - - Collection collection = collectionService.find(context, collectionID); - collectionService.delete(context, collection); - - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(new Message("default","The collection was successfully deleted.")); - - return result; - } - - - /** - * Create a new collection - * - * @param context The current DSpace context. - * @param communityID The id of the parent community. + */ + public static FlowResult processDeleteCollection(Context context, UUID collectionID) throws SQLException, AuthorizeException, IOException + { + FlowResult result = new FlowResult(); + + Collection collection = collectionService.find(context, collectionID); + collectionService.delete(context, collection); + + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(new Message("default","The collection was successfully deleted.")); + + return result; + } + + + /** + * Create a new collection + * + * @param context The current DSpace context. + * @param communityID The id of the parent community. * @param request user's request. - * @return A process result's object. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processCreateCollection(Context context, UUID communityID, Request request) + */ + public static FlowResult processCreateCollection(Context context, UUID communityID, Request request) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - - Community parent = communityService.find(context, communityID); - Collection newCollection = collectionService.create(context, parent); - - // Get the metadata - String name = request.getParameter("name"); - String shortDescription = request.getParameter("short_description"); - String introductoryText = request.getParameter("introductory_text"); - String copyrightText = request.getParameter("copyright_text"); - String sideBarText = request.getParameter("side_bar_text"); - String license = request.getParameter("license"); - String provenanceDescription = request.getParameter("provenance_description"); - - // If they don't have a name then make it untitled. - if (name == null || name.length() == 0) + { + FlowResult result = new FlowResult(); + + Community parent = communityService.find(context, communityID); + Collection newCollection = collectionService.create(context, parent); + + // Get the metadata + String name = request.getParameter("name"); + String shortDescription = request.getParameter("short_description"); + String introductoryText = request.getParameter("introductory_text"); + String copyrightText = request.getParameter("copyright_text"); + String sideBarText = request.getParameter("side_bar_text"); + String license = request.getParameter("license"); + String provenanceDescription = request.getParameter("provenance_description"); + + // If they don't have a name then make it untitled. + if (name == null || name.length() == 0) { name = "Untitled"; } - // If empty, make it null. - if (shortDescription != null && shortDescription.length() == 0) + // If empty, make it null. + if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } - if (introductoryText != null && introductoryText.length() == 0) + if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } - if (copyrightText != null && copyrightText.length() == 0) + if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } - if (sideBarText != null && sideBarText.length() == 0) + if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } - if (license != null && license.length() == 0) + if (license != null && license.length() == 0) { license = null; } - if (provenanceDescription != null && provenanceDescription.length() == 0) + if (provenanceDescription != null && provenanceDescription.length() == 0) { provenanceDescription = null; } - - // Save the metadata - collectionService.setMetadata(context, newCollection, "name", name); - collectionService.setMetadata(context, newCollection, "short_description", shortDescription); - collectionService.setMetadata(context, newCollection, "introductory_text", introductoryText); - collectionService.setMetadata(context, newCollection, "copyright_text", copyrightText); - collectionService.setMetadata(context, newCollection, "side_bar_text", sideBarText); - collectionService.setMetadata(context, newCollection, "license", license); - collectionService.setMetadata(context, newCollection, "provenance_description", provenanceDescription); + + // Save the metadata + collectionService.setMetadata(context, newCollection, "name", name); + collectionService.setMetadata(context, newCollection, "short_description", shortDescription); + collectionService.setMetadata(context, newCollection, "introductory_text", introductoryText); + collectionService.setMetadata(context, newCollection, "copyright_text", copyrightText); + collectionService.setMetadata(context, newCollection, "side_bar_text", sideBarText); + collectionService.setMetadata(context, newCollection, "license", license); + collectionService.setMetadata(context, newCollection, "provenance_description", provenanceDescription); // Set the logo - Object object = request.get("logo"); - Part filePart = null; - if (object instanceof Part) + Object object = request.get("logo"); + Part filePart = null; + if (object instanceof Part) { filePart = (Part) object; } - if (filePart != null && filePart.getSize() > 0) - { - InputStream is = filePart.getInputStream(); - - collectionService.setLogo(context, newCollection, is); - } + if (filePart != null && filePart.getSize() > 0) + { + InputStream is = filePart.getInputStream(); + + collectionService.setLogo(context, newCollection, is); + } // Save everything - collectionService.update(context, newCollection); + collectionService.update(context, newCollection); // success result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The collection was successfully created.")); result.setParameter("collectionID", newCollection.getID()); - - return result; - } + + return result; + } - // Community related functions + // Community related functions - /** - * Create a new community. - * - * @param context The current DSpace context. - * @param communityID The id of the parent community (-1 for a top-level community). + /** + * Create a new community. + * + * @param context The current DSpace context. + * @param communityID The id of the parent community (-1 for a top-level community). * @param request user's request. - * @return A process result's object. + * @return A process result's object. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. * @throws java.sql.SQLException passed through. - */ - public static FlowResult processCreateCommunity(Context context, UUID communityID, Request request) + */ + public static FlowResult processCreateCommunity(Context context, UUID communityID, Request request) throws AuthorizeException, IOException, SQLException - { - FlowResult result = new FlowResult(); + { + FlowResult result = new FlowResult(); - Community newCommunity; + Community newCommunity; - if (communityID != null) + if (communityID != null) { newCommunity = communityService.createSubcommunity(context, communityService.find(context, communityID)); } - else + else { newCommunity = communityService.create(null, context); } - - String name = request.getParameter("name"); - String shortDescription = request.getParameter("short_description"); - String introductoryText = request.getParameter("introductory_text"); - String copyrightText = request.getParameter("copyright_text"); - String sideBarText = request.getParameter("side_bar_text"); + + String name = request.getParameter("name"); + String shortDescription = request.getParameter("short_description"); + String introductoryText = request.getParameter("introductory_text"); + String copyrightText = request.getParameter("copyright_text"); + String sideBarText = request.getParameter("side_bar_text"); - // If they don't have a name then make it untitled. - if (name == null || name.length() == 0) + // If they don't have a name then make it untitled. + if (name == null || name.length() == 0) { name = "Untitled"; } - // If empty, make it null. - if (shortDescription != null && shortDescription.length() == 0) + // If empty, make it null. + if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } - if (introductoryText != null && introductoryText.length() == 0) + if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } - if (copyrightText != null && copyrightText.length() == 0) + if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } - if (sideBarText != null && sideBarText.length() == 0) + if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } - - communityService.setMetadata(context, newCommunity, "name", name); - communityService.setMetadata(context, newCommunity, "short_description", shortDescription); - communityService.setMetadata(context, newCommunity, "introductory_text", introductoryText); - communityService.setMetadata(context, newCommunity, "copyright_text", copyrightText); - communityService.setMetadata(context, newCommunity, "side_bar_text", sideBarText); - // Upload the logo - Object object = request.get("logo"); - Part filePart = null; - if (object instanceof Part) + communityService.setMetadata(context, newCommunity, "name", name); + communityService.setMetadata(context, newCommunity, "short_description", shortDescription); + communityService.setMetadata(context, newCommunity, "introductory_text", introductoryText); + communityService.setMetadata(context, newCommunity, "copyright_text", copyrightText); + communityService.setMetadata(context, newCommunity, "side_bar_text", sideBarText); + + // Upload the logo + Object object = request.get("logo"); + Part filePart = null; + if (object instanceof Part) { filePart = (Part) object; } - if (filePart != null && filePart.getSize() > 0) - { - InputStream is = filePart.getInputStream(); - - communityService.setLogo(context, newCommunity, is); - } + if (filePart != null && filePart.getSize() > 0) + { + InputStream is = filePart.getInputStream(); + + communityService.setLogo(context, newCommunity, is); + } - // Save everything - communityService.update(context, newCommunity); + // Save everything + communityService.update(context, newCommunity); // success result.setContinue(true); result.setOutcome(true); result.setMessage(new Message("default","The community was successfully created.")); result.setParameter("communityID", newCommunity.getID()); - - return result; - } - - - /** - * Process the community metadata edit form. - * - * @param context The current DSpace context. - * @param communityID The community id. - * @param deleteLogo Determines if the logo should be deleted along with the metadata editing action. - * @param request the Cocoon request object - * @return A process result's object. + + return result; + } + + + /** + * Process the community metadata edit form. + * + * @param context The current DSpace context. + * @param communityID The community id. + * @param deleteLogo Determines if the logo should be deleted along with the metadata editing action. + * @param request the Cocoon request object + * @return A process result's object. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. * @throws java.sql.SQLException passed through. - */ - public static FlowResult processEditCommunity(Context context, UUID communityID, boolean deleteLogo, Request request) + */ + public static FlowResult processEditCommunity(Context context, UUID communityID, boolean deleteLogo, Request request) throws AuthorizeException, IOException, SQLException - { - FlowResult result = new FlowResult(); + { + FlowResult result = new FlowResult(); - Community community = communityService.find(context, communityID); - - String name = request.getParameter("name"); - String shortDescription = request.getParameter("short_description"); - String introductoryText = request.getParameter("introductory_text"); - String copyrightText = request.getParameter("copyright_text"); - String sideBarText = request.getParameter("side_bar_text"); + Community community = communityService.find(context, communityID); + + String name = request.getParameter("name"); + String shortDescription = request.getParameter("short_description"); + String introductoryText = request.getParameter("introductory_text"); + String copyrightText = request.getParameter("copyright_text"); + String sideBarText = request.getParameter("side_bar_text"); - // If they don't have a name then make it untitled. - if (name == null || name.length() == 0) + // If they don't have a name then make it untitled. + if (name == null || name.length() == 0) { name = "Untitled"; } - // If empty, make it null. - if (shortDescription != null && shortDescription.length() == 0) + // If empty, make it null. + if (shortDescription != null && shortDescription.length() == 0) { shortDescription = null; } - if (introductoryText != null && introductoryText.length() == 0) + if (introductoryText != null && introductoryText.length() == 0) { introductoryText = null; } - if (copyrightText != null && copyrightText.length() == 0) + if (copyrightText != null && copyrightText.length() == 0) { copyrightText = null; } - if (sideBarText != null && sideBarText.length() == 0) + if (sideBarText != null && sideBarText.length() == 0) { sideBarText = null; } - - // Save the data - communityService.setMetadata(context, community, "name", name); - communityService.setMetadata(context, community, "short_description", shortDescription); + + // Save the data + communityService.setMetadata(context, community, "name", name); + communityService.setMetadata(context, community, "short_description", shortDescription); communityService.setMetadata(context, community, "introductory_text", introductoryText); communityService.setMetadata(context, community, "copyright_text", copyrightText); communityService.setMetadata(context, community, "side_bar_text", sideBarText); if (deleteLogo) { - // Remove the logo - communityService.setLogo(context, community, null); + // Remove the logo + communityService.setLogo(context, community, null); } else { - // Update the logo - Object object = request.get("logo"); - Part filePart = null; - if (object instanceof Part) + // Update the logo + Object object = request.get("logo"); + Part filePart = null; + if (object instanceof Part) { filePart = (Part) object; } - if (filePart != null && filePart.getSize() > 0) - { - InputStream is = filePart.getInputStream(); - - communityService.setLogo(context, community, is); - } + if (filePart != null && filePart.getSize() > 0) + { + InputStream is = filePart.getInputStream(); + + communityService.setLogo(context, community, is); + } } // Save everything @@ -1006,35 +1023,35 @@ public class FlowContainerUtils // No notice... result.setContinue(true); - return result; - } + return result; + } - /** - * Delete community itself. - * - * @param context The current DSpace context. - * @param communityID The community id. - * @return A process result's object. + /** + * Delete community itself. + * + * @param context The current DSpace context. + * @param communityID The community id. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processDeleteCommunity(Context context, UUID communityID) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - - Community community = communityService.find(context, communityID); - - communityService.delete(context, community); + */ + public static FlowResult processDeleteCommunity(Context context, UUID communityID) throws SQLException, AuthorizeException, IOException + { + FlowResult result = new FlowResult(); + + Community community = communityService.find(context, communityID); + + communityService.delete(context, community); - result.setContinue(true); - result.setOutcome(true); - result.setMessage(new Message("default","The community was successfully deleted.")); - - return result; - } - - /** + result.setContinue(true); + result.setOutcome(true); + result.setMessage(new Message("default","The community was successfully deleted.")); + + return result; + } + + /** * Look up the id of a group authorized for one of the given roles. If no group is currently * authorized to perform this role then a new group will be created and assigned the role. * @@ -1049,7 +1066,7 @@ public class FlowContainerUtils public static UUID getCommunityRole(Context context, UUID communityID, String roleName) throws SQLException, AuthorizeException, IOException { Community community = communityService.find(context, communityID); - + // Determine the group based upon which role we are looking for. Group role = null; if (ROLE_ADMIN.equals(roleName)) @@ -1060,9 +1077,9 @@ public class FlowContainerUtils role = communityService.createAdministrators(context, community); } } - + // In case we needed to create a group, save our changes - communityService.update(context, community); + communityService.update(context, community); // If the role name was valid then role should be non null, if (role != null) @@ -1073,7 +1090,7 @@ public class FlowContainerUtils return null; } - /** + /** * Delete one of a community's roles * * @param context The current DSpace context. @@ -1097,7 +1114,7 @@ public class FlowContainerUtils // First, unregister the role if (ROLE_ADMIN.equals(roleName)) { - communityService.removeAdministrators(context, community); + communityService.removeAdministrators(context, community); } // Second, remove all authorizations for this role by searching for all policies that this @@ -1115,7 +1132,7 @@ public class FlowContainerUtils // Finally, delete the role's actual group. communityService.update(context, community); - groupService.delete(context, role); + groupService.delete(context, role); result.setContinue(true); result.setOutcome(true); @@ -1162,7 +1179,7 @@ public class FlowContainerUtils */ public static FlowResult processCurateCollection(Context context, UUID dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception - { + { String task = request.getParameter("curate_task"); Curator curator = FlowCurationUtils.getCurator(task); @@ -1177,13 +1194,13 @@ public class FlowContainerUtils } return FlowCurationUtils.getRunFlowResult(task, curator, true); } - catch (Exception e) + catch (Exception e) { curator.setResult(task, e.getMessage()); return FlowCurationUtils.getRunFlowResult(task, curator, false); - } + } - } + } /** * Queues curation tasks. @@ -1197,28 +1214,28 @@ public class FlowContainerUtils */ public static FlowResult processQueueCollection(Context context, UUID dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception - { - String task = request.getParameter("curate_task"); - Curator curator = FlowCurationUtils.getCurator(task); - String objId = String.valueOf(dsoID); - String taskQueueName = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.ui.queuename"); - boolean status = false; - Collection collection = collectionService.find(context, dsoID); - if (collection != null) - { - objId = collection.getHandle(); - try - { - curator.queue(context, objId, taskQueueName); - status = true; - } - catch (IOException ioe) - { - // no-op - } - } - return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); - } + { + String task = request.getParameter("curate_task"); + Curator curator = FlowCurationUtils.getCurator(task); + String objId = String.valueOf(dsoID); + String taskQueueName = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.ui.queuename"); + boolean status = false; + Collection collection = collectionService.find(context, dsoID); + if (collection != null) + { + objId = collection.getHandle(); + try + { + curator.queue(context, objId, taskQueueName); + status = true; + } + catch (IOException ioe) + { + // no-op + } + } + return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); + } /** * Utility method to process curation tasks submitted via the DSpace GUI. @@ -1233,9 +1250,9 @@ public class FlowContainerUtils */ public static FlowResult processCurateCommunity(Context context, UUID dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception - { + { String task = request.getParameter("curate_task"); - Curator curator = FlowCurationUtils.getCurator(task); + Curator curator = FlowCurationUtils.getCurator(task); try { Community community = communityService.find(context, dsoID); @@ -1250,8 +1267,8 @@ public class FlowContainerUtils { curator.setResult(task, e.getMessage()); return FlowCurationUtils.getRunFlowResult(task, curator, false); - } - } + } + } /** * queues curation tasks. @@ -1266,75 +1283,75 @@ public class FlowContainerUtils */ public static FlowResult processQueueCommunity(Context context, UUID dsoID, Request request) throws AuthorizeException, IOException, SQLException, Exception - { - String task = request.getParameter("curate_task"); - Curator curator = FlowCurationUtils.getCurator(task); - String objId = String.valueOf(dsoID); - String taskQueueName = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.ui.queuename"); - boolean status = false; - Community community = communityService.find(context, dsoID); - if (community != null) - { - objId = community.getHandle(); - try - { - curator.queue(context, objId, taskQueueName); - status = true; - } - catch (IOException ioe) - { - // no-op - } - } - return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); - } + { + String task = request.getParameter("curate_task"); + Curator curator = FlowCurationUtils.getCurator(task); + String objId = String.valueOf(dsoID); + String taskQueueName = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.ui.queuename"); + boolean status = false; + Community community = communityService.find(context, dsoID); + if (community != null) + { + objId = community.getHandle(); + try + { + curator.queue(context, objId, taskQueueName); + status = true; + } + catch (IOException ioe) + { + // no-op + } + } + return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); + } - /** - * Check whether this metadata value is a proper XML fragment. If the value is not - * then an error message will be returned that might (sometimes not) tell the user how - * to correct the problem. - * - * @param value The metadata value - * @return An error string of the problem or null if there is no problem with the metadata value. - */ - public static String checkXMLFragment(String value) - { - // escape the ampersand correctly; - value = escapeXMLEntities(value); - - // Try and parse the XML into a mini-DOM - String xml = ""+value+""; - - ByteArrayInputStream inputStream = null; + /** + * Check whether this metadata value is a proper XML fragment. If the value is not + * then an error message will be returned that might (sometimes not) tell the user how + * to correct the problem. + * + * @param value The metadata value + * @return An error string of the problem or null if there is no problem with the metadata value. + */ + public static String checkXMLFragment(String value) + { + // escape the ampersand correctly; + value = escapeXMLEntities(value); + + // Try and parse the XML into a mini-DOM + String xml = ""+value+""; + + ByteArrayInputStream inputStream = null; try { inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { inputStream = new ByteArrayInputStream(xml.getBytes()); //not supposed to happen, but never hurts } - - SAXBuilder builder = new SAXBuilder(); - try - { - // This will generate an error if not valid XML. - builder.build(inputStream); - } - catch (JDOMException jdome) - { - // It's not XML - return jdome.getMessage(); - } - catch (IOException ioe) - { - // This shouldn't ever occur because we are parsing - // an in-memory string, but in case it does we'll just return - // it as a normal error. - return ioe.getMessage(); - } + + SAXBuilder builder = new SAXBuilder(); + try + { + // This will generate an error if not valid XML. + builder.build(inputStream); + } + catch (JDOMException jdome) + { + // It's not XML + return jdome.getMessage(); + } + catch (IOException ioe) + { + // This shouldn't ever occur because we are parsing + // an in-memory string, but in case it does we'll just return + // it as a normal error. + return ioe.getMessage(); + } - return null; - } - + return null; + } + /** * Sanitize any XML that was inputed by the user, this will clean up * any unescaped characters so that they can be stored as proper XML. @@ -1344,61 +1361,61 @@ public class FlowContainerUtils * @param value The unsanitized value * @return A sanitized value */ - public static String escapeXMLEntities(String value) - { - if (value == null) + public static String escapeXMLEntities(String value) + { + if (value == null) { return null; } - - // Escape any XML entities - int amp = -1; - while ((amp = value.indexOf('&', amp+1)) > -1) - { - // Is it an xml entity named by number? - if (substringCompare(value,amp+1,'#')) + + // Escape any XML entities + int amp = -1; + while ((amp = value.indexOf('&', amp+1)) > -1) + { + // Is it an xml entity named by number? + if (substringCompare(value,amp+1,'#')) { continue; } - - // & - if (substringCompare(value,amp+1,'a','m','p',';')) + + // & + if (substringCompare(value,amp+1,'a','m','p',';')) { continue; } - - // ' - if (substringCompare(value,amp+1,'a','p','o','s',';')) + + // ' + if (substringCompare(value,amp+1,'a','p','o','s',';')) { continue; } - - // " - if (substringCompare(value,amp+1,'q','u','o','t',';')) + + // " + if (substringCompare(value,amp+1,'q','u','o','t',';')) { continue; } - - // < - if (substringCompare(value,amp+1,'l','t',';')) + + // < + if (substringCompare(value,amp+1,'l','t',';')) { continue; } - - // > - if (substringCompare(value,amp+1,'g','t',';')) + + // > + if (substringCompare(value,amp+1,'g','t',';')) { continue; } - - // Replace the ampersand with an XML entity. - value = value.substring(0,amp) + "&" + value.substring(amp+1); - } - - return value; - } - - /** + + // Replace the ampersand with an XML entity. + value = value.substring(0,amp) + "&" + value.substring(amp+1); + } + + return value; + } + + /** * Check if the given character sequence is located in the given * string at the specified index. If it is then return true, otherwise false. * @@ -1409,23 +1426,23 @@ public class FlowContainerUtils */ private static boolean substringCompare(String string, int index, char ... characters) { - // Is the string long enough? - if (string.length() <= index + characters.length) + // Is the string long enough? + if (string.length() <= index + characters.length) { return false; } - - // Do all the characters match? - for (char character : characters) - { - if (string.charAt(index) != character) + + // Do all the characters match? + for (char character : characters) + { + if (string.charAt(index) != character) { return false; } - index++; - } - - return false; + index++; + } + + return false; } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowCurationUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowCurationUtils.java index 400e796063..2016690581 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowCurationUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowCurationUtils.java @@ -40,10 +40,10 @@ public class FlowCurationUtils new Message("default","xmlui.administrative.FlowCurationUtils.queue_success_notice"); private static final Message T_queue_fail_notice = new Message("default","xmlui.administrative.FlowCurationUtils.queue_failed_notice"); - - + + private static final Map map = new HashMap(); - + protected static Curator getCurator(String taskName) { if (taskName != null && taskName.length() == 0) @@ -55,7 +55,7 @@ public class FlowCurationUtils curator.setInvoked(Curator.Invoked.INTERACTIVE); return curator; } - + /** * Build a FlowResult which will provide a Notice to users, notifying them * of whether the Curation task succeeded or failed. @@ -68,7 +68,9 @@ public class FlowCurationUtils { if (map.isEmpty()) { - String[] statusCodes = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("curate.ui.statusmessages"); + String[] statusCodes = DSpaceServicesFactory.getInstance() + .getConfigurationService().getArrayProperty( + "curate.ui.statusmessages"); for (String pair : statusCodes) { String[] parts = pair.split("="); @@ -84,30 +86,34 @@ public class FlowCurationUtils String result = curator.getResult(taskName); FlowResult flowResult = new FlowResult(); //set whether task succeeded or failed - flowResult.setOutcome(success); - if(result==null) + flowResult.setOutcome(success); + if (result == null) + { result = "Nothing to do for this DSpace object."; + } //add in status message - if(success) - { - //@TODO: Ideally, all of this status information would be contained within a translatable I18N Message. - // Unfortunately, there currently is no support for displaying Parameterized Messages in Notices + if (success) + { + // @TODO: Ideally, all of this status information would be contained + // within a translatable I18N Message. Unfortunately, there + // currently is no support for displaying Parameterized Messages in + // Notices // (See FlowResult.getMessage(), sitemap.xmap and NoticeTransformer) flowResult.setHeader(new Message("default", "Task: " + getUITaskName(taskName))); flowResult.setMessage(T_curate_success_notice); - flowResult.setCharacters("STATUS: " + status + ", RESULT: " + result); + flowResult.setCharacters("STATUS: " + status + ", RESULT: " + result); } else { flowResult.setHeader(new Message("default", "Task: " + getUITaskName(taskName))); flowResult.setMessage(T_curate_fail_notice); - flowResult.setCharacters("STATUS: Failure, RESULT: " + result); - + flowResult.setCharacters("STATUS: Failure, RESULT: " + result); + } flowResult.setContinue(true); return flowResult; } - + /** * Build a FlowResult which will provide a Notice to users, notifying them * of whether the Curation task was queued successfully or not @@ -117,64 +123,72 @@ public class FlowCurationUtils * @param queueName the name of the queue * @return FlowResult */ - protected static FlowResult getQueueFlowResult(String taskName, boolean status, - String objId, String queueName) + protected static FlowResult getQueueFlowResult( + String taskName, boolean status, String objId, String queueName) { FlowResult flowResult = new FlowResult(); flowResult.setOutcome(status); - + //add in status message - if(status) + if (status) { - //@TODO: Ideally, all of this status information would be contained within a translatable I18N Message. - // Unfortunately, there currently is no support for displaying Parameterized Messages in Notices + // @TODO: Ideally, all of this status information would be contained + // within a translatable I18N Message. Unfortunately, there + // currently is no support for displaying Parameterized Messages in + // Notices // (See FlowResult.getMessage(), sitemap.xmap and NoticeTransformer) flowResult.setHeader(new Message("default", "Task: " + getUITaskName(taskName))); flowResult.setMessage(T_queue_success_notice); - flowResult.setCharacters("RESULT: Object '" + objId + "' queued in '" + queueName + "' Queue"); + flowResult.setCharacters("RESULT: Object '" + objId + + "' queued in '" + queueName + "' Queue"); } else { - flowResult.setHeader(new Message("default", "Task: " + getUITaskName(taskName))); + flowResult.setHeader(new Message("default", "Task: " + + getUITaskName(taskName))); flowResult.setMessage(T_queue_fail_notice); - flowResult.setCharacters("RESULT: FAILED to queue Object '" + objId + "' in '" + queueName + "' Queue"); + flowResult.setCharacters("RESULT: FAILED to queue Object '" + objId + + "' in '" + queueName + "' Queue"); } flowResult.setContinue(true); return flowResult; } - - + + /** * Retrieve UI "friendly" Task Name for display to user - * + * * @param taskID the short name / identifier for the task * @return the User Friendly name for this task */ protected static String getUITaskName(String taskID) - { - String[] tasks = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("curate.ui.tasknames"); + { + String[] tasks = DSpaceServicesFactory.getInstance() + .getConfigurationService().getArrayProperty("curate.ui.tasknames"); - for (String task : tasks) + for (String task : tasks) + { + //retrieve keyValuePair (format [taskID]=[UI Task Name]) + String[] keyValuePair = task.split("="); + + if (keyValuePair!=null && keyValuePair.length==2) { - //retrieve keyValuePair (format [taskID]=[UI Task Name]) - String[] keyValuePair = task.split("="); - - if(keyValuePair!=null && keyValuePair.length==2) - { - if(taskID.equals(keyValuePair[0].trim())) - return keyValuePair[1]; + if (taskID.equals(keyValuePair[0].trim())) + { + return keyValuePair[1]; } } - //if we are here, the UI friendly task name was not found - // So, we'll just return the TaskID, as it's better than nothing - return taskID; + } + //if we are here, the UI friendly task name was not found + // So, we'll just return the TaskID, as it's better than nothing + return taskID; } - - + + /** * Utility method to process curation tasks * submitted via the DSpace Admin UI Curate Form. - * + * * @param context current DSpace Context * @param request current Cocoon request * @return FlowResult representing the result of request @@ -194,7 +208,7 @@ public class FlowCurationUtils curator.curate(context, objHandle); result = FlowCurationUtils.getRunFlowResult(task, curator, true); } - catch (Exception e) + catch (Exception e) { curator.setResult(task, e.getMessage()); result = FlowCurationUtils.getRunFlowResult(task, curator, false); @@ -204,11 +218,11 @@ public class FlowCurationUtils result.setParameter("identifier", objHandle); return result; } - + /** * Utility method to queue curation tasks * submitted via the DSpace Admin UI Curate Form. - * + * * @param context current DSpace Context * @param request current Cocoon request * @return FlowResult representing the result of request @@ -219,12 +233,12 @@ public class FlowCurationUtils //get input values from Form (see org.dspace.app.xmlui.aspect.administrative.CurateForm) String task = request.getParameter("curate_task"); String objHandle = request.getParameter("identifier"); - + Curator curator = FlowCurationUtils.getCurator(task); - + String taskQueueName = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.ui.queuename"); boolean status = false; - + if (objHandle != null) { try @@ -240,7 +254,7 @@ public class FlowCurationUtils } return FlowCurationUtils.getQueueFlowResult(task, status, objHandle, taskQueueName); } - + /** Utility methods to support curation groups/tasks form fields * * @@ -249,62 +263,62 @@ public class FlowCurationUtils public static final String CURATE_GROUP_NAMES = "ui.taskgroups"; public static final String CURATE_GROUP_PREFIX = "ui.taskgroup"; public static final String UNGROUPED_TASKS = "ungrouped"; - + public static Map allTasks = new LinkedHashMap(); public static Map groupedTasks = new LinkedHashMap(); public static Map groups = new LinkedHashMap(); - + public static void setupCurationTasks() { - try - { - setAllTasks(); - setGroupedTasks(); - setGroups(); - } - catch (Exception we) - { - // noop - } - } - - public static void setAllTasks() throws WingException, UnsupportedEncodingException - { - String[] properties = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("curate." + CURATE_TASK_NAMES); - for (String property : properties) - { - //System.out.println("set all tasks and property = " + property + "\n"); - String[] keyValuePair = property.split("="); - allTasks.put(URLDecoder.decode(keyValuePair[0].trim(), "UTF-8"), - URLDecoder.decode(keyValuePair[1].trim(), "UTF-8")); - } - } - - public static void setGroups() throws WingException, UnsupportedEncodingException - { - String[] properties = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("curate." + CURATE_GROUP_NAMES); - if (properties != null) + try { - for (String property : properties) - { - String[] keyValuePair = property.split("="); - groups.put(URLDecoder.decode(keyValuePair[0].trim(), "UTF-8"), - URLDecoder.decode(keyValuePair[1].trim(), "UTF-8")); - } + setAllTasks(); + setGroupedTasks(); + setGroups(); + } + catch (Exception we) + { + // noop } } - + + public static void setAllTasks() throws WingException, UnsupportedEncodingException + { + String[] properties = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("curate." + CURATE_TASK_NAMES); + for (String property : properties) + { + //System.out.println("set all tasks and property = " + property + "\n"); + String[] keyValuePair = property.split("="); + allTasks.put(URLDecoder.decode(keyValuePair[0].trim(), "UTF-8"), + URLDecoder.decode(keyValuePair[1].trim(), "UTF-8")); + } + } + + public static void setGroups() throws WingException, UnsupportedEncodingException + { + String[] properties = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("curate." + CURATE_GROUP_NAMES); + if (properties != null) + { + for (String property : properties) + { + String[] keyValuePair = property.split("="); + groups.put(URLDecoder.decode(keyValuePair[0].trim(), "UTF-8"), + URLDecoder.decode(keyValuePair[1].trim(), "UTF-8")); + } + } + } + public static void setGroupedTasks() throws WingException, UnsupportedEncodingException { - if (groups.isEmpty()) - { - setGroups(); - } - if (!groups.isEmpty()) - { - Iterator iterator = groups.keySet().iterator(); - while (iterator.hasNext()) - { + if (groups.isEmpty()) + { + setGroups(); + } + if (!groups.isEmpty()) + { + Iterator iterator = groups.keySet().iterator(); + while (iterator.hasNext()) + { String key = iterator.next(); String[] properties = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("curate." + CURATE_GROUP_PREFIX + "." + key); groupedTasks.put(URLDecoder.decode(key, "UTF-8"), properties); @@ -314,58 +328,57 @@ public class FlowCurationUtils public static Select getGroupSelectOptions(Select select) throws WingException { - Iterator iterator = groups.keySet().iterator(); + Iterator iterator = groups.keySet().iterator(); while (iterator.hasNext()) { - String key = iterator.next(); + String key = iterator.next(); select.addOption(key, groups.get(key)); } return select; } - + public static Select getTaskSelectOptions(Select select, String curateGroup) throws WingException { - String key; - String[] values = null; + String key; + String[] values = null; Iterator iterator = null; if (groupedTasks.isEmpty()) { - iterator = allTasks.keySet().iterator(); + iterator = allTasks.keySet().iterator(); while (iterator.hasNext()) { - key = iterator.next(); + key = iterator.next(); select.addOption(key, allTasks.get(key)); } return select; } else { - iterator = groupedTasks.keySet().iterator(); + iterator = groupedTasks.keySet().iterator(); } while (iterator.hasNext()) { - key = iterator.next(); + key = iterator.next(); values = groupedTasks.get(key); if (key.equals(curateGroup)) { - for (String value : values) + for (String value : values) { Iterator innerIterator = allTasks.keySet().iterator(); while (innerIterator.hasNext()) { - String optionValue = innerIterator.next().trim(); - String optionText; - // out.print("Value: " + value + ": OptionValue: " + optionValue + ". Does value.trim().equals(optionValue)? " + value.equals(opti$ - if (optionValue.equals(value.trim())) - { - optionText = (String) allTasks.get(optionValue); + String optionValue = innerIterator.next().trim(); + String optionText; + // out.print("Value: " + value + ": OptionValue: " + optionValue + ". Does value.trim().equals(optionValue)? " + value.equals(opti$ + if (optionValue.equals(value.trim())) + { + optionText = (String) allTasks.get(optionValue); select.addOption(optionValue, optionText); } } } - } + } } return select; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowEPersonUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowEPersonUtils.java index 0ae3afdf2a..ddf4986f3b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowEPersonUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowEPersonUtils.java @@ -39,305 +39,305 @@ import org.dspace.eperson.service.EPersonService; */ public class FlowEPersonUtils { - /** Language Strings */ - private static final Message T_add_eperson_success_notice = - new Message("default","xmlui.administrative.FlowEPersonUtils.add_eperson_success_notice"); - - private static final Message T_edit_eperson_success_notice = - new Message("default","xmlui.administrative.FlowEPersonUtils.edit_eperson_success_notice"); - - private static final Message T_reset_password_success_notice = - new Message("default","xmlui.administrative.FlowEPersonUtils.reset_password_success_notice"); - - private static final Message t_delete_eperson_success_notice = - new Message("default","xmlui.administrative.FlowEPersonUtils.delete_eperson_success_notice"); - - private static final Message t_delete_eperson_failed_notice = - new Message("default","xmlui.administrative.FlowEPersonUtils.delete_eperson_failed_notice"); + /** Language Strings */ + private static final Message T_add_eperson_success_notice = + new Message("default","xmlui.administrative.FlowEPersonUtils.add_eperson_success_notice"); + + private static final Message T_edit_eperson_success_notice = + new Message("default","xmlui.administrative.FlowEPersonUtils.edit_eperson_success_notice"); + + private static final Message T_reset_password_success_notice = + new Message("default","xmlui.administrative.FlowEPersonUtils.reset_password_success_notice"); + + private static final Message t_delete_eperson_success_notice = + new Message("default","xmlui.administrative.FlowEPersonUtils.delete_eperson_success_notice"); + + private static final Message t_delete_eperson_failed_notice = + new Message("default","xmlui.administrative.FlowEPersonUtils.delete_eperson_failed_notice"); - protected static final AccountService accountService = EPersonServiceFactory.getInstance().getAccountService(); - protected static final EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); + protected static final AccountService accountService = EPersonServiceFactory.getInstance().getAccountService(); + protected static final EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); - /** - * Add a new eperson. This method will check that the email address, - * first name, and last name are non empty. Also a check is performed - * to see if the requested email address is already in use by another - * user. - * - * @param context The current DSpace context - * @param request The HTTP request parameters - * @param objectModel Cocoon's object model - * @return A process result's object. + /** + * Add a new eperson. This method will check that the email address, + * first name, and last name are non empty. Also a check is performed + * to see if the requested email address is already in use by another + * user. + * + * @param context The current DSpace context + * @param request The HTTP request parameters + * @param objectModel Cocoon's object model + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processAddEPerson(Context context, Request request, Map objectModel) throws SQLException, AuthorizeException - { - FlowResult result = new FlowResult(); - result.setContinue(false); // default to no continue - - // Get all our request parameters - String email = request.getParameter("email_address").trim(); - String first = request.getParameter("first_name").trim(); - String last = request.getParameter("last_name").trim(); - String phone = request.getParameter("phone").trim(); - boolean login = (request.getParameter("can_log_in") != null) ? true : false; - boolean certificate = (request.getParameter("certificate") != null) ? true : false; - - // If we have errors, the form needs to be resubmitted to fix those problems - if (StringUtils.isEmpty(email)) + */ + public static FlowResult processAddEPerson(Context context, Request request, Map objectModel) throws SQLException, AuthorizeException + { + FlowResult result = new FlowResult(); + result.setContinue(false); // default to no continue + + // Get all our request parameters + String email = request.getParameter("email_address").trim(); + String first = request.getParameter("first_name").trim(); + String last = request.getParameter("last_name").trim(); + String phone = request.getParameter("phone").trim(); + boolean login = (request.getParameter("can_log_in") != null) ? true : false; + boolean certificate = (request.getParameter("certificate") != null) ? true : false; + + // If we have errors, the form needs to be resubmitted to fix those problems + if (StringUtils.isEmpty(email)) { result.addError("email_address"); } - if (StringUtils.isEmpty(first)) + if (StringUtils.isEmpty(first)) { result.addError("first_name"); } - if (StringUtils.isEmpty(last)) + if (StringUtils.isEmpty(last)) { result.addError("last_name"); } - - - // Check if the email address is already being used. - EPerson potentialDupicate = ePersonService.findByEmail(context,email); - if (potentialDupicate != null) - { - // special error that the front end knows about. - result.addError("eperson_email_key"); - } - - // No errors, so we try to create the EPerson from the data provided - if (result.getErrors() == null) - { - EPerson newPerson = AuthenticationUtil.createNewEperson(objectModel,email); - - newPerson.setFirstName(context, first); + + + // Check if the email address is already being used. + EPerson potentialDupicate = ePersonService.findByEmail(context,email); + if (potentialDupicate != null) + { + // special error that the front end knows about. + result.addError("eperson_email_key"); + } + + // No errors, so we try to create the EPerson from the data provided + if (result.getErrors() == null) + { + EPerson newPerson = AuthenticationUtil.createNewEperson(objectModel,email); + + newPerson.setFirstName(context, first); newPerson.setLastName(context, last); ePersonService.setMetadata(context, newPerson, "phone", phone); newPerson.setCanLogIn(login); newPerson.setRequireCertificate(certificate); newPerson.setSelfRegistered(false); - ePersonService.update(context, newPerson); + ePersonService.update(context, newPerson); // success result.setContinue(true); result.setOutcome(true); result.setMessage(T_add_eperson_success_notice); result.setParameter("epersonID", newPerson.getID()); - } - - return result; - } + } + + return result; + } - /** - * Edit an eperson's metadata, the email address, first name, and last name are all - * required. The user's email address can be updated but it must remain unique, if - * the email address already exists then the an error is produced. - * - * @param context The current DSpace context - * @param request The HTTP request parameters - * @param ObjectModel Cocoon's object model - * @param epersonID The unique id of the eperson being edited. - * @return A process result's object. + /** + * Edit an eperson's metadata, the email address, first name, and last name are all + * required. The user's email address can be updated but it must remain unique, if + * the email address already exists then the an error is produced. + * + * @param context The current DSpace context + * @param request The HTTP request parameters + * @param ObjectModel Cocoon's object model + * @param epersonID The unique id of the eperson being edited. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processEditEPerson(Context context, + */ + public static FlowResult processEditEPerson(Context context, Request request, Map ObjectModel, UUID epersonID) throws SQLException, AuthorizeException - { + { - FlowResult result = new FlowResult(); - result.setContinue(false); // default to failure - - // Get all our request parameters - String email = request.getParameter("email_address"); - String first = request.getParameter("first_name"); - String last = request.getParameter("last_name"); - String phone = request.getParameter("phone"); - boolean login = (request.getParameter("can_log_in") != null) ? true : false; - boolean certificate = (request.getParameter("certificate") != null) ? true : false; - - - // If we have errors, the form needs to be resubmitted to fix those problems - if (StringUtils.isEmpty(email)) + FlowResult result = new FlowResult(); + result.setContinue(false); // default to failure + + // Get all our request parameters + String email = request.getParameter("email_address"); + String first = request.getParameter("first_name"); + String last = request.getParameter("last_name"); + String phone = request.getParameter("phone"); + boolean login = (request.getParameter("can_log_in") != null) ? true : false; + boolean certificate = (request.getParameter("certificate") != null) ? true : false; + + + // If we have errors, the form needs to be resubmitted to fix those problems + if (StringUtils.isEmpty(email)) { result.addError("email_address"); } - if (StringUtils.isEmpty(first)) + if (StringUtils.isEmpty(first)) { result.addError("first_name"); } - if (StringUtils.isEmpty(last)) + if (StringUtils.isEmpty(last)) { result.addError("last_name"); } - - - // No errors, so we edit the EPerson with the data provided - if (result.getErrors() == null) - { - // Grab the person in question - EPerson personModified = ePersonService.find(context, epersonID); - - // Make sure the email address we are changing to is unique - String originalEmail = personModified.getEmail(); + + + // No errors, so we edit the EPerson with the data provided + if (result.getErrors() == null) + { + // Grab the person in question + EPerson personModified = ePersonService.find(context, epersonID); + + // Make sure the email address we are changing to is unique + String originalEmail = personModified.getEmail(); if (originalEmail == null || !originalEmail.equals(email)) - { - EPerson potentialDupicate = ePersonService.findByEmail(context,email); - - if (potentialDupicate == null) - { - personModified.setEmail(email); - } - else if (potentialDupicate.equals(personModified)) - { - // set a special field in error so that the transformer can display a pretty error. - result.addError("eperson_email_key"); - return result; - } - } - String originalFirstName = personModified.getFirstName(); + { + EPerson potentialDupicate = ePersonService.findByEmail(context,email); + + if (potentialDupicate == null) + { + personModified.setEmail(email); + } + else if (potentialDupicate.equals(personModified)) + { + // set a special field in error so that the transformer can display a pretty error. + result.addError("eperson_email_key"); + return result; + } + } + String originalFirstName = personModified.getFirstName(); if (originalFirstName == null || !originalFirstName.equals(first)) { - personModified.setFirstName(context, first); - } - String originalLastName = personModified.getLastName(); + personModified.setFirstName(context, first); + } + String originalLastName = personModified.getLastName(); if (originalLastName == null || !originalLastName.equals(last)) { - personModified.setLastName(context, last); - } - String originalPhone = ePersonService.getMetadata(personModified, "phone"); + personModified.setLastName(context, last); + } + String originalPhone = ePersonService.getMetadata(personModified, "phone"); if (originalPhone == null || !originalPhone.equals(phone)) { - ePersonService.setMetadata(context, personModified, "phone", phone); - } - personModified.setCanLogIn(login); - personModified.setRequireCertificate(certificate); - - - ePersonService.update(context, personModified); + ePersonService.setMetadata(context, personModified, "phone", phone); + } + personModified.setCanLogIn(login); + personModified.setRequireCertificate(certificate); + + + ePersonService.update(context, personModified); - result.setContinue(true); - result.setOutcome(true); - // FIXME: rename this message - result.setMessage(T_edit_eperson_success_notice); - } - - // Everything was fine - return result; - } - - /** - * Send the user a forgot password email message. The message will - * contain a token that the user can use to login and pick a new password. - * - * @param context The current DSpace context - * @param epersonID The unique id of the eperson being edited. - * @return A process result's object. + result.setContinue(true); + result.setOutcome(true); + // FIXME: rename this message + result.setMessage(T_edit_eperson_success_notice); + } + + // Everything was fine + return result; + } + + /** + * Send the user a forgot password email message. The message will + * contain a token that the user can use to login and pick a new password. + * + * @param context The current DSpace context + * @param epersonID The unique id of the eperson being edited. + * @return A process result's object. * @throws java.io.IOException passed through. * @throws javax.mail.MessagingException passed through. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processResetPassword(Context context, UUID epersonID) + */ + public static FlowResult processResetPassword(Context context, UUID epersonID) throws IOException, MessagingException, SQLException, AuthorizeException - { - EPerson eperson = ePersonService.find(context, epersonID); - - // Note, this may throw an error is the email is bad. - accountService.sendForgotPasswordInfo(context, eperson.getEmail()); - - FlowResult result = new FlowResult(); - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_reset_password_success_notice); - return result; - } - - - /** - * Log this user in as another user. If the operation failed then the flow result - * will be set to failure with it's message set correctly. Note that after logging out - * the user may not have sufficient privileges to continue. - * - * @param context The current DSpace context. - * @param objectModel Object model to obtain the HTTP request from. - * @param epersonID The epersonID of the person to login as. - * @return The flow result. - * @throws java.sql.SQLException passed through. - */ - public static FlowResult processLoginAs(Context context, Map objectModel, UUID epersonID) throws SQLException - { - FlowResult result = new FlowResult(); - result.setContinue(true); - result.setOutcome(true); - - final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + { + EPerson eperson = ePersonService.find(context, epersonID); - EPerson eperson = ePersonService.find(context,epersonID); + // Note, this may throw an error is the email is bad. + accountService.sendForgotPasswordInfo(context, eperson.getEmail()); + + FlowResult result = new FlowResult(); + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_reset_password_success_notice); + return result; + } + + + /** + * Log this user in as another user. If the operation failed then the flow result + * will be set to failure with it's message set correctly. Note that after logging out + * the user may not have sufficient privileges to continue. + * + * @param context The current DSpace context. + * @param objectModel Object model to obtain the HTTP request from. + * @param epersonID The epersonID of the person to login as. + * @return The flow result. + * @throws java.sql.SQLException passed through. + */ + public static FlowResult processLoginAs(Context context, Map objectModel, UUID epersonID) throws SQLException + { + FlowResult result = new FlowResult(); + result.setContinue(true); + result.setOutcome(true); + + final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + + EPerson eperson = ePersonService.find(context,epersonID); - try { - AuthenticationUtil.loginAs(context, request, eperson); - } - catch (AuthorizeException ae) - { - // give the exception error as a notice. - result.setOutcome(false); - result.setMessage(new Message(null,ae.getMessage())); - } - - return result; - } - - /** - * Delete the epeople specified by the epeopleIDs parameter. This assumes that the - * deletion has been confirmed. - * - * @param context The current DSpace context - * @param epeopleIDs The unique id of the eperson being edited. - * @return A process result's object. + try { + AuthenticationUtil.loginAs(context, request, eperson); + } + catch (AuthorizeException ae) + { + // give the exception error as a notice. + result.setOutcome(false); + result.setMessage(new Message(null,ae.getMessage())); + } + + return result; + } + + /** + * Delete the epeople specified by the epeopleIDs parameter. This assumes that the + * deletion has been confirmed. + * + * @param context The current DSpace context + * @param epeopleIDs The unique id of the eperson being edited. + * @return A process result's object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.eperson.EPersonDeletionException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processDeleteEPeople(Context context, String[] epeopleIDs) + */ + public static FlowResult processDeleteEPeople(Context context, String[] epeopleIDs) throws NumberFormatException, SQLException, AuthorizeException, EPersonDeletionException, IOException { - FlowResult result = new FlowResult(); - - List unableList = new ArrayList(); - for (String id : epeopleIDs) - { - EPerson personDeleted = ePersonService.find(context, UUID.fromString(id)); - ePersonService.delete(context, personDeleted); - } - - if (unableList.size() > 0) - { - result.setOutcome(false); - result.setMessage(t_delete_eperson_failed_notice); - - String characters = null; - for(String unable : unableList ) - { - if (characters == null) + FlowResult result = new FlowResult(); + + List unableList = new ArrayList(); + for (String id : epeopleIDs) + { + EPerson personDeleted = ePersonService.find(context, UUID.fromString(id)); + ePersonService.delete(context, personDeleted); + } + + if (unableList.size() > 0) + { + result.setOutcome(false); + result.setMessage(t_delete_eperson_failed_notice); + + String characters = null; + for(String unable : unableList ) + { + if (characters == null) { characters = unable; } - else + else { characters += ", " + unable; } - } - - result.setCharacters(characters); - } - else - { - result.setOutcome(true); - result.setMessage(t_delete_eperson_success_notice); - } + } + + result.setCharacters(characters); + } + else + { + result.setOutcome(true); + result.setMessage(t_delete_eperson_success_notice); + } - return result; - } + return result; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowGroupUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowGroupUtils.java index ab6e03805b..895b1c6ed4 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowGroupUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowGroupUtils.java @@ -37,162 +37,165 @@ import java.util.*; */ public class FlowGroupUtils { - /** Language Strings */ - private static final Message T_edit_group_success_notice = - new Message("default","xmlui.administrative.FlowGroupUtils.edit_group_success_notice"); - - private static final Message T_delete_group_success_notice = - new Message("default","xmlui.administrative.FlowGroupUtils.delete_group_success_notice"); + /** Language Strings */ + private static final Message T_edit_group_success_notice = + new Message("default","xmlui.administrative.FlowGroupUtils.edit_group_success_notice"); - protected static final EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); - protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + private static final Message T_delete_group_success_notice = + new Message("default","xmlui.administrative.FlowGroupUtils.delete_group_success_notice"); - /** - * Return the current name for the given group ID. - * @param context The current DSpace context. - * @param groupID The group id. - * @return The group's name. + protected static final EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); + protected static final GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected static final CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + + /** + * Return the current name for the given group ID. + * @param context The current DSpace context. + * @param groupID The group id. + * @return The group's name. * @throws java.sql.SQLException passed through. - */ - public static String getName(Context context, UUID groupID) throws SQLException - { - if (groupID == null) + */ + public static String getName(Context context, UUID groupID) + throws SQLException + { + if (groupID == null) { return "New Group"; } - - Group group = groupService.find(context,groupID); - - if (group == null) + + Group group = groupService.find(context,groupID); + + if (group == null) { return "New Group"; } - - return group.getName(); - } - - /** - * Return the list of current epeople ID's that are a member of this group. - * - * @param context The current DSpace context - * @param groupID The group's id. - * @return An array of ids. - * @throws java.sql.SQLException passed through. - */ - public static String[] getEPeopleMembers(Context context, UUID groupID) throws SQLException - { - // New group, just return an empty list - if (groupID == null) - { - return new String[0]; - } - - Group group = groupService.find(context,groupID); - - if (group == null) - { - return new String[0]; - } - - List epeople = group.getMembers(); - - String[] epeopleIDs = new String[epeople.size()]; - for (int i=0; i < epeople.size(); i++) - { - epeopleIDs[i] = String.valueOf(epeople.get(i).getID()); - } - - return epeopleIDs; - } - - /** - * Return the list of current group id's that are a member of this group. - * - * @param context The current DSpace context - * @param groupID The group's id. - * @return An array of ids. - * @throws java.sql.SQLException passed through. - */ - public static String[] getGroupMembers(Context context, UUID groupID) throws SQLException - { - if (groupID == null) - { - return new String[0]; - } - - Group group = groupService.find(context,groupID); - - if (group == null) - { - return new String[0]; - } - - List groups = group.getMemberGroups(); - - String[] groupIDs = new String[groups.size()]; - for (int i=0; i < groups.size(); i++) - { - groupIDs[i] = String.valueOf(groups.get(i).getID()); - } - - return groupIDs; - } - /** - * Add the given id to the list and return a new list. - * - * @param list The current array - * @param id The new element - * @return A new combined array. - */ - public static String[] addMember(String[] list, String id) - { - // FIXME: this is terribly inefficient. - List newList = new ArrayList(Arrays.asList(list)); - newList.add(id); - return newList.toArray(new String[newList.size()]); - } - - /** - * Remove all instances of the given id from the member list. - * - * @param list The current array - * @param id The id to remove - * @return A new combined array. - */ - public static String[] removeMember(String[] list, String id) - { - // FIXME: this is terribly inefficient. - List newList = new ArrayList(Arrays.asList(list)); - newList.remove(id); - return newList.toArray(new String[newList.size()]); - } - - /** - * Save the group. If the name has been changed then it will be updated, if any - * members have been added or removed then they are updated. - * - * If the groupID is -1 then a new group is created. - * - * @param context The current dspace context - * @param groupID The group id, or -1 for a new group. - * @param newName The group's new name. - * @param newEPeopleIDsArray All epeople members - * @param newGroupIDsArray All group members. - * @return A result + return group.getName(); + } + + /** + * Return the list of current epeople ID's that are a member of this group. + * + * @param context The current DSpace context + * @param groupID The group's id. + * @return An array of ids. + * @throws java.sql.SQLException passed through. + */ + public static String[] getEPeopleMembers(Context context, UUID groupID) + throws SQLException + { + // New group, just return an empty list + if (groupID == null) + { + return new String[0]; + } + + Group group = groupService.find(context,groupID); + + if (group == null) + { + return new String[0]; + } + + List epeople = group.getMembers(); + + String[] epeopleIDs = new String[epeople.size()]; + for (int i=0; i < epeople.size(); i++) + { + epeopleIDs[i] = String.valueOf(epeople.get(i).getID()); + } + + return epeopleIDs; + } + + /** + * Return the list of current group id's that are a member of this group. + * + * @param context The current DSpace context + * @param groupID The group's id. + * @return An array of ids. + * @throws java.sql.SQLException passed through. + */ + public static String[] getGroupMembers(Context context, UUID groupID) + throws SQLException + { + if (groupID == null) + { + return new String[0]; + } + + Group group = groupService.find(context,groupID); + + if (group == null) + { + return new String[0]; + } + + List groups = group.getMemberGroups(); + + String[] groupIDs = new String[groups.size()]; + for (int i=0; i < groups.size(); i++) + { + groupIDs[i] = String.valueOf(groups.get(i).getID()); + } + + return groupIDs; + } + + /** + * Add the given id to the list and return a new list. + * + * @param list The current array + * @param id The new element + * @return A new combined array. + */ + public static String[] addMember(String[] list, String id) + { + // FIXME: this is terribly inefficient. + List newList = new ArrayList(Arrays.asList(list)); + newList.add(id); + return newList.toArray(new String[newList.size()]); + } + + /** + * Remove all instances of the given id from the member list. + * + * @param list The current array + * @param id The id to remove + * @return A new combined array. + */ + public static String[] removeMember(String[] list, String id) + { + // FIXME: this is terribly inefficient. + List newList = new ArrayList(Arrays.asList(list)); + newList.remove(id); + return newList.toArray(new String[newList.size()]); + } + + /** + * Save the group. If the name has been changed then it will be updated, if any + * members have been added or removed then they are updated. + * + * If the groupID is -1 then a new group is created. + * + * @param context The current dspace context + * @param groupID The group id, or -1 for a new group. + * @param newName The group's new name. + * @param newEPeopleIDsArray All epeople members + * @param newGroupIDsArray All group members. + * @return A result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.app.xmlui.utils.UIException on bad encoding. - */ - public static FlowResult processSaveGroup(Context context, UUID groupID, String newName, String[] newEPeopleIDsArray, String[] newGroupIDsArray) - throws SQLException, AuthorizeException, UIException - { - FlowResult result = new FlowResult(); - - // Decode the name in case it uses non-ascii characters. - try + */ + public static FlowResult processSaveGroup(Context context, UUID groupID, String newName, String[] newEPeopleIDsArray, String[] newGroupIDsArray) + throws SQLException, AuthorizeException, UIException + { + FlowResult result = new FlowResult(); + + // Decode the name in case it uses non-ascii characters. + try { newName = URLDecoder.decode(newName, Constants.DEFAULT_ENCODING); } @@ -200,345 +203,346 @@ public class FlowGroupUtils { { throw new UIException(uee); } - - Group group = null; - if (groupID == null) - { - // First, check if the name is blank. - if (newName == null || newName.length() == 0) - { - // Group's can not have blank names. - result.setContinue(false); - result.addError("group_name"); - result.setOutcome(false); - result.setMessage(new Message("default","The group name may not be blank.")); - - return result; - } - - // Create a new group, check if the newName is already in use. - Group potentialDuplicate = groupService.findByName(context,newName); - - if (potentialDuplicate == null) - { - // All good, create the new group. - group = groupService.create(context); - groupService.setName(group, newName); - } - else - { - // The name is already in use, return an error. - result.setContinue(false); - result.addError("group_name"); - result.addError("group_name_duplicate"); - result.setOutcome(false); - result.setMessage(new Message("default","The group name is already in use")); - - return result; - } - } - else - { - group = groupService.find(context,groupID); - String name = group.getName(); - - // Only update the name if there has been a change. - if (newName != null && newName.length() > 0 && !name.equals(newName)) - { - // The group name is to be updated, check if the newName is already in use. - Group potentialDuplicate = groupService.findByName(context,newName); - - if (potentialDuplicate == null) - { - // All good, update the name - groupService.setName(group, newName); - } - else - { - // The name is already in use, return an error. - result.setContinue(false); - result.addError("group_name"); - result.addError("group_name_duplicate"); - result.setOutcome(false); - result.setMessage(new Message("default","The group name is already in use")); - - return result; - } - } - } - - // Second, prepare to check members by turning arrays into lists - List newEPeopleIDs = new ArrayList<>(); - for (String epeopleID : newEPeopleIDsArray) - { - newEPeopleIDs.add(UUID.fromString(epeopleID)); - } - List newGroupIDs = new ArrayList<>(); - for (String _groupID : newGroupIDsArray) - { - newGroupIDs.add(UUID.fromString(_groupID)); - } - - - // Third, check if there are any members to remove - // i.e. scan the list on the group against the ids. - for (Iterator it = group.getMembers().iterator(); it.hasNext(); ) - { - EPerson epersonMember = it.next(); - if (!newEPeopleIDs.contains(epersonMember.getID())) - { - // The current eperson is not contained in the new list. - it.remove(); - groupService.removeMember(context, group, epersonMember); - } - else - { - // If they are still in the list then remove them - // from the list of people to add. - newEPeopleIDs.remove((Object)epersonMember.getID()); - } - } - for (Iterator it = group.getMemberGroups().iterator(); it.hasNext(); ) - { - Group groupMember = it.next(); - if (!newGroupIDs.contains(groupMember.getID())) - { - // The current group is not contained in the new list. - it.remove(); - groupService.removeMember(context, group, groupMember); - } - else - { - // If they are still in the list then remove them - // from the list of groups to add. - newGroupIDs.remove((Object)group.getID()); - } - } - - // Third, check if there are any members to add - // i.e. scan the list of ids against the group. - for (UUID epersonID : newEPeopleIDs) - { - EPerson eperson = ePersonService.find(context, epersonID); - - groupService.addMember(context, group, eperson); - } - - for (UUID _groupID : newGroupIDs) - { - Group _group = groupService.find(context, _groupID); - - groupService.addMember(context, group, _group); - } - - // Last, create the result flow - groupService.update(context, group); - // Let's record our group id in case we created a new one. - result.setParameter("groupID", group.getID()); - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_edit_group_success_notice); - - return result; - } - - /** - * Remove the specified groups. It is assumed that the user has already confirmed this selection. - * - * @param context The current DSpace context - * @param groupIDs A list of groups to be removed. - * @return A results object. + Group group = null; + if (groupID == null) + { + // First, check if the name is blank. + if (newName == null || newName.length() == 0) + { + // Group's can not have blank names. + result.setContinue(false); + result.addError("group_name"); + result.setOutcome(false); + result.setMessage(new Message("default","The group name may not be blank.")); + + return result; + } + + // Create a new group, check if the newName is already in use. + Group potentialDuplicate = groupService.findByName(context,newName); + + if (potentialDuplicate == null) + { + // All good, create the new group. + group = groupService.create(context); + groupService.setName(group, newName); + } + else + { + // The name is already in use, return an error. + result.setContinue(false); + result.addError("group_name"); + result.addError("group_name_duplicate"); + result.setOutcome(false); + result.setMessage(new Message("default","The group name is already in use")); + + return result; + } + } + else + { + group = groupService.find(context,groupID); + String name = group.getName(); + + // Only update the name if there has been a change. + if (newName != null && newName.length() > 0 && !name.equals(newName)) + { + // The group name is to be updated, check if the newName is already in use. + Group potentialDuplicate = groupService.findByName(context,newName); + + if (potentialDuplicate == null) + { + // All good, update the name + groupService.setName(group, newName); + } + else + { + // The name is already in use, return an error. + result.setContinue(false); + result.addError("group_name"); + result.addError("group_name_duplicate"); + result.setOutcome(false); + result.setMessage(new Message("default","The group name is already in use")); + + return result; + } + } + } + + // Second, prepare to check members by turning arrays into lists + List newEPeopleIDs = new ArrayList<>(); + for (String epeopleID : newEPeopleIDsArray) + { + newEPeopleIDs.add(UUID.fromString(epeopleID)); + } + List newGroupIDs = new ArrayList<>(); + for (String _groupID : newGroupIDsArray) + { + newGroupIDs.add(UUID.fromString(_groupID)); + } + + + // Third, check if there are any members to remove + // i.e. scan the list on the group against the ids. + for (Iterator it = group.getMembers().iterator(); it.hasNext(); ) + { + EPerson epersonMember = it.next(); + if (!newEPeopleIDs.contains(epersonMember.getID())) + { + // The current eperson is not contained in the new list. + it.remove(); + groupService.removeMember(context, group, epersonMember); + } + else + { + // If they are still in the list then remove them + // from the list of people to add. + newEPeopleIDs.remove((Object)epersonMember.getID()); + } + } + for (Iterator it = group.getMemberGroups().iterator(); it.hasNext(); ) + { + Group groupMember = it.next(); + if (!newGroupIDs.contains(groupMember.getID())) + { + // The current group is not contained in the new list. + it.remove(); + groupService.removeMember(context, group, groupMember); + } + else + { + // If they are still in the list then remove them + // from the list of groups to add. + newGroupIDs.remove((Object)group.getID()); + } + } + + // Third, check if there are any members to add + // i.e. scan the list of ids against the group. + for (UUID epersonID : newEPeopleIDs) + { + EPerson eperson = ePersonService.find(context, epersonID); + + groupService.addMember(context, group, eperson); + } + + for (UUID _groupID : newGroupIDs) + { + Group _group = groupService.find(context, _groupID); + + groupService.addMember(context, group, _group); + } + + // Last, create the result flow + groupService.update(context, group); + + // Let's record our group id in case we created a new one. + result.setParameter("groupID", group.getID()); + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_edit_group_success_notice); + + return result; + } + + /** + * Remove the specified groups. It is assumed that the user has already confirmed this selection. + * + * @param context The current DSpace context + * @param groupIDs A list of groups to be removed. + * @return A results object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processDeleteGroups(Context context, String[] groupIDs) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(true); - - for (String id : groupIDs) - { - Group groupDeleted = groupService.find(context, UUID.fromString(id)); - - // If this group is related to a collection, then un-link it. - UUID collectionId = getCollectionId(context, groupDeleted.getName()); - Role role = getCollectionRole(groupDeleted.getName()); - if (collectionId != null && role != Role.none) - { - Collection collection = collectionService.find(context, collectionId); - - if (collection != null) - { - if (role == Role.Administrators) - { - collectionService.removeAdministrators(context, collection); - collectionService.update(context, collection); - } - else if (role == Role.Submitters) - { - collectionService.removeSubmitters(context, collection); - collectionService.update(context, collection); - } - else if (role == Role.WorkflowStep1) - { - collection.setWorkflowGroup(1, null); - collectionService.update(context, collection); - } - else if (role == Role.WorkflowStep2) - { - collection.setWorkflowGroup(2, null); - collectionService.update(context, collection); - } - else if (role == Role.WorkflowStep3) - { - collection.setWorkflowGroup(3, null); - collectionService.update(context, collection); - } - else if (role == Role.DefaultRead) - { - // Nothing special needs to happen. - } - } - } + */ + public static FlowResult processDeleteGroups(Context context, String[] groupIDs) + throws SQLException, AuthorizeException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(true); - groupService.delete(context, groupDeleted); - } - - result.setOutcome(true); - result.setMessage(T_delete_group_success_notice); - - return result; - } - - /** - * The collection prefix, all groups which are specific to - * a collection start with this. - */ - private static final String COLLECTION_PREFIX = "COLLECTION_"; - - /** - * These are the possible collection suffixes, all groups which are - * specific to a collection will end with one of these. The collection - * id should be in between the prefix and the suffix. - * - * Note: the order of these suffixes are important, see getCollectionRole() - */ - private static final String[] COLLECTION_SUFFIXES = {"_SUBMIT","_ADMIN","_WFSTEP_1","_WORKFLOW_STEP_1","_WFSTEP_2","_WORKFLOW_STEP_2","_WFSTEP_3","_WORKFLOW_STEP_3","_DEFAULT_ITEM_READ"}; + for (String id : groupIDs) + { + Group groupDeleted = groupService.find(context, UUID.fromString(id)); - /** - * Extracts the collection id that may be embedded in the given group name. - * - * @param context session context. - * @param groupName - the name of a group (ie group.getName()) - * @return the integer collection id or -1 if the group is not that of a collection - */ - public static UUID getCollectionId(Context context, String groupName) - { - if (groupName != null && groupName.startsWith(COLLECTION_PREFIX)) - { - for (String suffix : COLLECTION_SUFFIXES) - { - if (groupName.endsWith(suffix)) - { - String idString = groupName.substring(COLLECTION_PREFIX.length()); - idString = idString.substring(0, idString.length() - suffix.length()); + // If this group is related to a collection, then un-link it. + UUID collectionId = getCollectionId(context, groupDeleted.getName()); + Role role = getCollectionRole(groupDeleted.getName()); + if (collectionId != null && role != Role.none) + { + Collection collection = collectionService.find(context, collectionId); - try { - Collection collection = collectionService.findByIdOrLegacyId(context, idString); - if(collection != null) - { - return collection.getID(); - }else{ - return null; - } - } - catch (Exception nfe) - { - // Something went wrong, just ignore the exception and - // continue searching for a collection id - } // try & catch - } // if it ends with a proper suffix. - } // for each possible suffix - } // if it starts with COLLECTION_ - - return null; + if (collection != null) + { + if (role == Role.Administrators) + { + collectionService.removeAdministrators(context, collection); + collectionService.update(context, collection); + } + else if (role == Role.Submitters) + { + collectionService.removeSubmitters(context, collection); + collectionService.update(context, collection); + } + else if (role == Role.WorkflowStep1) + { + collection.setWorkflowGroup(1, null); + collectionService.update(context, collection); + } + else if (role == Role.WorkflowStep2) + { + collection.setWorkflowGroup(2, null); + collectionService.update(context, collection); + } + else if (role == Role.WorkflowStep3) + { + collection.setWorkflowGroup(3, null); + collectionService.update(context, collection); + } + else if (role == Role.DefaultRead) + { + // Nothing special needs to happen. + } + } + } + + groupService.delete(context, groupDeleted); + } + + result.setOutcome(true); + result.setMessage(T_delete_group_success_notice); + + return result; } - - public enum Role {Administrators, Submitters, WorkflowStep1, WorkflowStep2, WorkflowStep3, DefaultRead, none}; - - public static Role getCollectionRole(String groupName) - { - if (groupName != null && groupName.startsWith(COLLECTION_PREFIX)) - { - for (String suffix : COLLECTION_SUFFIXES) - { - if (groupName.endsWith(suffix)) - { - if (COLLECTION_SUFFIXES[0].equals(suffix)) + + /** + * The collection prefix, all groups which are specific to + * a collection start with this. + */ + private static final String COLLECTION_PREFIX = "COLLECTION_"; + + /** + * These are the possible collection suffixes, all groups which are + * specific to a collection will end with one of these. The collection + * id should be in between the prefix and the suffix. + * + * Note: the order of these suffixes are important, see getCollectionRole() + */ + private static final String[] COLLECTION_SUFFIXES = {"_SUBMIT","_ADMIN","_WFSTEP_1","_WORKFLOW_STEP_1","_WFSTEP_2","_WORKFLOW_STEP_2","_WFSTEP_3","_WORKFLOW_STEP_3","_DEFAULT_ITEM_READ"}; + + /** + * Extracts the collection id that may be embedded in the given group name. + * + * @param context session context. + * @param groupName - the name of a group (ie group.getName()) + * @return the integer collection id or -1 if the group is not that of a collection + */ + public static UUID getCollectionId(Context context, String groupName) + { + if (groupName != null && groupName.startsWith(COLLECTION_PREFIX)) + { + for (String suffix : COLLECTION_SUFFIXES) + { + if (groupName.endsWith(suffix)) + { + String idString = groupName.substring(COLLECTION_PREFIX.length()); + idString = idString.substring(0, idString.length() - suffix.length()); + + try { + Collection collection = collectionService.findByIdOrLegacyId(context, idString); + if(collection != null) + { + return collection.getID(); + }else{ + return null; + } + } + catch (Exception nfe) + { + // Something went wrong, just ignore the exception and + // continue searching for a collection id + } // try & catch + } // if it ends with a proper suffix. + } // for each possible suffix + } // if it starts with COLLECTION_ + + return null; + } + + public enum Role {Administrators, Submitters, WorkflowStep1, WorkflowStep2, WorkflowStep3, DefaultRead, none}; + + public static Role getCollectionRole(String groupName) + { + if (groupName != null && groupName.startsWith(COLLECTION_PREFIX)) + { + for (String suffix : COLLECTION_SUFFIXES) + { + if (groupName.endsWith(suffix)) + { + if (COLLECTION_SUFFIXES[0].equals(suffix)) { return Role.Submitters; } - else if (COLLECTION_SUFFIXES[1].equals(suffix)) + else if (COLLECTION_SUFFIXES[1].equals(suffix)) { return Role.Administrators; } - else if (COLLECTION_SUFFIXES[2].equals(suffix)) + else if (COLLECTION_SUFFIXES[2].equals(suffix)) { return Role.WorkflowStep1; } - else if (COLLECTION_SUFFIXES[3].equals(suffix)) + else if (COLLECTION_SUFFIXES[3].equals(suffix)) { return Role.WorkflowStep1; } - else if (COLLECTION_SUFFIXES[4].equals(suffix)) + else if (COLLECTION_SUFFIXES[4].equals(suffix)) { return Role.WorkflowStep2; } - else if (COLLECTION_SUFFIXES[5].equals(suffix)) + else if (COLLECTION_SUFFIXES[5].equals(suffix)) { return Role.WorkflowStep2; } - else if (COLLECTION_SUFFIXES[6].equals(suffix)) + else if (COLLECTION_SUFFIXES[6].equals(suffix)) { return Role.WorkflowStep3; } - else if (COLLECTION_SUFFIXES[7].equals(suffix)) + else if (COLLECTION_SUFFIXES[7].equals(suffix)) { return Role.WorkflowStep3; } - else if (COLLECTION_SUFFIXES[8].equals(suffix)) + else if (COLLECTION_SUFFIXES[8].equals(suffix)) { return Role.DefaultRead; } - - } // if it ends with a proper suffix. - } // for each possible suffix - } // if it starts with COLLECTION_ - - return Role.none; - } + + } // if it ends with a proper suffix. + } // for each possible suffix + } // if it starts with COLLECTION_ + + return Role.none; + } /** * The community prefix: all groups which are specific to * a community start with this. */ private static final String COMMUNITY_PREFIX = "COMMUNITY_"; - + /** * These are the possible community suffixes. All groups which are * specific to a collection will end with one of these. The collection * id should be between the prefix and the suffix. - * + * * Note: the order of these suffixes are important, see getCollectionRole() */ private static final String[] COMMUNITY_SUFFIXES = {"_ADMIN"}; - - + + /** * Extracts the community id that may be embedded in the given group name. - * + * * @param context session context. * @param groupName the name of a group (ie group.getName()) * @return the integer community id or -1 if the group is not that of a community @@ -554,27 +558,27 @@ public class FlowGroupUtils { String idString = groupName.substring(COMMUNITY_PREFIX.length()); idString = idString.substring(0, idString.length() - suffix.length()); - try { - Community community = communityService.findByIdOrLegacyId(context, idString); - if(community != null) - { - return community.getID(); - }else{ - return null; - } - } - catch (Exception nfe) - { - // Something went wrong, just ignore the exception and - // continue searching for a collection id - } // try & catch + try { + Community community = communityService.findByIdOrLegacyId(context, idString); + if(community != null) + { + return community.getID(); + }else{ + return null; + } + } + catch (Exception nfe) + { + // Something went wrong, just ignore the exception and + // continue searching for a collection id + } // try & catch } // if it ends with a proper suffix. } // for each possible suffix } // if it starts with COLLECTION_ - + return null; } - + public static Role getCommunityRole(String groupName) { if (groupName != null && groupName.startsWith(COMMUNITY_PREFIX)) @@ -619,12 +623,11 @@ public class FlowGroupUtils { { return Role.DefaultRead; } - + } // if it ends with a proper suffix. } // for each possible suffix } // if it starts with COMMUNITY_ - + return Role.none; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowItemUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowItemUtils.java index 5151a175c2..af048c80c1 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowItemUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowItemUtils.java @@ -38,302 +38,313 @@ import javax.servlet.http.HttpServletRequest; /** * Utility methods to processes actions on Groups. These methods are used * exclusively from the administrative flow scripts. - * + * * @author Jay Paz * @author Scott Phillips */ -public class FlowItemUtils +public class FlowItemUtils { - /** Language Strings */ - private static final Message T_metadata_updated = new Message("default","The Item's metadata was successfully updated."); - private static final Message T_metadata_added = new Message("default","New metadata was added."); - private static final Message T_item_withdrawn = new Message("default","The item has been withdrawn."); - private static final Message T_item_public = new Message("default","The item is now public."); - private static final Message T_item_private = new Message("default","The item is now private."); - private static final Message T_item_reinstated = new Message("default","The item has been reinstated."); - private static final Message T_item_moved = new Message("default","The item has been moved."); - private static final Message T_item_move_destination_not_found = new Message("default","The selected destination collection could not be found."); - private static final Message T_bitstream_added = new Message("default","The new bitstream was successfully uploaded."); - private static final Message T_bitstream_failed = new Message("default","Error while uploading file."); - private static final Message T_bitstream_updated = new Message("default","The bitstream has been updated."); - private static final Message T_bitstream_delete = new Message("default","The selected bitstreams have been deleted."); - private static final Message T_bitstream_order = new Message("default","The bitstream order has been successfully altered."); + /** Language Strings */ + private static final Message T_metadata_updated = new Message("default", "The Item's metadata was successfully updated."); + private static final Message T_metadata_added = new Message("default", "New metadata was added."); + private static final Message T_item_withdrawn = new Message("default", "The item has been withdrawn."); + private static final Message T_item_public = new Message("default", "The item is now public."); + private static final Message T_item_private = new Message("default", "The item is now private."); + private static final Message T_item_reinstated = new Message("default", "The item has been reinstated."); + private static final Message T_item_moved = new Message("default", "The item has been moved."); + private static final Message T_item_move_destination_not_found = new Message("default", "The selected destination collection could not be found."); + private static final Message T_bitstream_added = new Message("default", "The new bitstream was successfully uploaded."); + private static final Message T_bitstream_failed = new Message("default", "Error while uploading file."); + private static final Message T_bitstream_updated = new Message("default", "The bitstream has been updated."); + private static final Message T_bitstream_delete = new Message("default", "The selected bitstreams have been deleted."); + private static final Message T_bitstream_order = new Message("default", "The bitstream order has been successfully altered."); - protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - protected static final BundleService bundleService = ContentServiceFactory.getInstance().getBundleService(); - protected static final BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); - protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected static final MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); + protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + protected static final BundleService bundleService = ContentServiceFactory.getInstance().getBundleService(); + protected static final BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); + protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected static final MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); - protected static final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); + protected static final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); - protected static final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); + protected static final HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); - - /** - * Resolve the given identifier to an item. The identifier may be either an - * internal ID or a handle. If an item is found then the result the internal - * ID of the item will be placed in the result "itemID" parameter. - * - * If the identifier was unable to be resolved to an item then the "identifier" - * field is placed in error. - * - * @param context The current DSpace context. - * @param identifier An Internal ID or a handle - * @return A flow result + + /** + * Resolve the given identifier to an item. The identifier may be either an + * internal ID or a handle. If an item is found then the result the internal + * ID of the item will be placed in the result "itemID" parameter. + * + * If the identifier was unable to be resolved to an item then the "identifier" + * field is placed in error. + * + * @param context The current DSpace context. + * @param identifier An Internal ID or a handle + * @return A flow result * @throws java.sql.SQLException passed through. - */ - public static FlowResult resolveItemIdentifier(Context context, String identifier) throws SQLException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - // Check whether it's a handle or internal id (by check ing if it has a slash inthe string) - if (identifier.contains("/")) - { - DSpaceObject dso = handleService.resolveToObject(context, identifier); - - if (dso != null && dso.getType() == Constants.ITEM) - { - result.setParameter("itemID", dso.getID()); - result.setParameter("type", Constants.ITEM); - result.setContinue(true); - return result; - } - } - else - { - - Item item = null; - try { - item = itemService.find(context, UUID.fromString(identifier)); - } catch (NumberFormatException e) { - // ignoring the exception - } + */ + public static FlowResult resolveItemIdentifier(Context context, String identifier) throws SQLException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - if (item != null) - { - result.setParameter("itemID", item.getID()); - result.setParameter("type", Constants.ITEM); - result.setContinue(true); - return result; - } - } + // Check whether it's a handle or internal id (by check ing if it has a slash inthe string) + if (identifier.contains("/")) + { + DSpaceObject dso = handleService.resolveToObject(context, identifier); - result.addError("identifier"); - return result; - } - - /** - * Process the request parameters to update the item's metadata and remove any selected bitstreams. - * - * Each metadata entry will have three fields "name_X", "value_X", and "language_X" where X is an - * integer that relates all three of the fields together. The name parameter stores the metadata name - * that is used by the entry (i.e schema_element_qualifier). The value and language parameters are user - * inputed fields. If the optional parameter "remove_X" is given then the metadata value is removed. - * - * To support AJAX operations on this page an additional parameter is considered, the "scope". The scope - * is the set of metadata entries that are being updated during this request. It the metadata name, - * schema_element_qualifier, only fields that have this name are considered! If all fields are to be - * considered then scope should be set to "*". - * - * When creating an AJAX query include all the name_X, value_X, language_X, and remove_X for the fields - * in the set, and then set the scope parameter to be the metadata field. - * - * @param context The current DSpace context - * @param itemID internal item id - * @param request the Cocoon request - * @return A flow result + if (dso != null && dso.getType() == Constants.ITEM) + { + result.setParameter("itemID", dso.getID()); + result.setParameter("type", Constants.ITEM); + result.setContinue(true); + return result; + } + } + else + { + Item item = null; + try + { + item = itemService.find(context, UUID.fromString(identifier)); + } + catch (NumberFormatException e) + { + // ignoring the exception + } + + if (item != null) + { + result.setParameter("itemID", item.getID()); + result.setParameter("type", Constants.ITEM); + result.setContinue(true); + return result; + } + } + + result.addError("identifier"); + return result; + } + + + /** + * Process the request parameters to update the item's metadata and remove any selected bitstreams. + * + * Each metadata entry will have three fields "name_X", "value_X", and "language_X" where X is an + * integer that relates all three of the fields together. The name parameter stores the metadata name + * that is used by the entry (i.e schema_element_qualifier). The value and language parameters are user + * inputed fields. If the optional parameter "remove_X" is given then the metadata value is removed. + * + * To support AJAX operations on this page an additional parameter is considered, the "scope". The scope + * is the set of metadata entries that are being updated during this request. It the metadata name, + * schema_element_qualifier, only fields that have this name are considered! If all fields are to be + * considered then scope should be set to "*". + * + * When creating an AJAX query include all the name_X, value_X, language_X, and remove_X for the fields + * in the set, and then set the scope parameter to be the metadata field. + * + * @param context The current DSpace context + * @param itemID internal item id + * @param request the Cocoon request + * @return A flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processEditItem(Context context, UUID itemID, Request request) - throws SQLException, AuthorizeException, UIException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); + */ + public static FlowResult processEditItem(Context context, UUID itemID, Request request) + throws SQLException, AuthorizeException, UIException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - Item item = itemService.find(context, itemID); - - - // STEP 1: - // Clear all metadata within the scope - // Only metadata values within this scope will be considered. This - // is so ajax request can operate on only a subset of the values. - String scope = request.getParameter("scope"); - if ("*".equals(scope)) - { - itemService.clearMetadata(context, item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); - } - else - { - String[] parts = parseName(scope); - itemService.clearMetadata(context, item, parts[0],parts[1],parts[2],Item.ANY); - } - - // STEP 2: - // First determine all the metadata fields that are within - // the scope parameter - ArrayList indexes = new ArrayList(); - Enumeration parameters = request.getParameterNames(); - while(parameters.hasMoreElements()) - { + Item item = itemService.find(context, itemID); - // Only consider the name_ fields - String parameterName = (String) parameters.nextElement(); - if (parameterName.startsWith("name_")) - { - // Check if the name is within the scope - String parameterValue = request.getParameter(parameterName); - if ("*".equals(scope) || scope.equals(parameterValue)) - { - // Extract the index from the name. - String indexString = parameterName.substring("name_".length()); - Integer index = Integer.valueOf(indexString); - indexes.add(index); - } - } - } - - // STEP 3: - // Iterate over all the indexes within the scope and add them back in. - for (Integer index=1; index <= indexes.size(); ++index) - { - String name = request.getParameter("name_"+index); - String value = request.getParameter("value_"+index); - String authority = request.getParameter("value_"+index+"_authority"); - String confidence = request.getParameter("value_"+index+"_confidence"); - String lang = request.getParameter("language_"+index); - String remove = request.getParameter("remove_"+index); - - // the user selected the remove checkbox. - if (remove != null) - { - continue; - } - - // get the field's name broken up - String[] parts = parseName(name); - - // probe for a confidence value - int iconf = Choices.CF_UNSET; - if (confidence != null && confidence.length() > 0) - { - iconf = Choices.getConfidenceValue(confidence); - } - // upgrade to a minimum of NOVALUE if there IS an authority key - if (authority != null && authority.length() > 0 && iconf == Choices.CF_UNSET) - { - iconf = Choices.CF_NOVALUE; - } - itemService.addMetadata(context, item, parts[0], parts[1], parts[2], lang, - value, authority, iconf); - } - - itemService.update(context, item); - - result.setContinue(true); - - result.setOutcome(true); - result.setMessage(T_metadata_updated); - - return result; - } - - /** - * Process the request parameters to add a new metadata entry for the item. - * - * @param context The current DSpace context - * @param itemID internal item id - * @param request the Cocoon request - * @return A flow result + // STEP 1: + // Clear all metadata within the scope + // Only metadata values within this scope will be considered. This + // is so ajax request can operate on only a subset of the values. + String scope = request.getParameter("scope"); + if ("*".equals(scope)) + { + itemService.clearMetadata( + context, item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); + } + else + { + String[] parts = parseName(scope); + itemService.clearMetadata( + context, item, parts[0], parts[1], parts[2], Item.ANY); + } + + // STEP 2: + // First determine all the metadata fields that are within + // the scope parameter + ArrayList indexes = new ArrayList(); + Enumeration parameters = request.getParameterNames(); + while (parameters.hasMoreElements()) + { + + // Only consider the name_ fields + String parameterName = (String) parameters.nextElement(); + if (parameterName.startsWith("name_")) + { + // Check if the name is within the scope + String parameterValue = request.getParameter(parameterName); + if ("*".equals(scope) || scope.equals(parameterValue)) + { + // Extract the index from the name. + String indexString = parameterName.substring("name_".length()); + Integer index = Integer.valueOf(indexString); + indexes.add(index); + } + } + } + + // STEP 3: + // Iterate over all the indexes within the scope and add them back in. + for (Integer index=1; index <= indexes.size(); ++index) + { + String name = request.getParameter("name_" + index); + String value = request.getParameter("value_" + index); + String authority = request.getParameter("value_" + index + "_authority"); + String confidence = request.getParameter("value_" + index + "_confidence"); + String lang = request.getParameter("language_" + index); + String remove = request.getParameter("remove_" + index); + + // the user selected the remove checkbox. + if (remove != null) + { + continue; + } + + // get the field's name broken up + String[] parts = parseName(name); + + // probe for a confidence value + int iconf = Choices.CF_UNSET; + if (confidence != null && confidence.length() > 0) + { + iconf = Choices.getConfidenceValue(confidence); + } + // upgrade to a minimum of NOVALUE if there IS an authority key + if (authority != null && authority.length() > 0 && + iconf == Choices.CF_UNSET) + { + iconf = Choices.CF_NOVALUE; + } + itemService.addMetadata(context, item, parts[0], parts[1], parts[2], + lang, value, authority, iconf); + } + + itemService.update(context, item); + + result.setContinue(true); + + result.setOutcome(true); + result.setMessage(T_metadata_updated); + + return result; + } + + + /** + * Process the request parameters to add a new metadata entry for the item. + * + * @param context The current DSpace context + * @param itemID internal item id + * @param request the Cocoon request + * @return A flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processAddMetadata(Context context, UUID itemID, Request request) + */ + public static FlowResult processAddMetadata(Context context, UUID itemID, Request request) throws SQLException, AuthorizeException, UIException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); + { + FlowResult result = new FlowResult(); + result.setContinue(false); - Item item = itemService.find(context, itemID); - - - String fieldID = request.getParameter("field"); - String value = request.getParameter("value"); - String language = request.getParameter("language"); - - MetadataField field = metadataFieldService.find(context,Integer.valueOf(fieldID)); - - itemService.addMetadata(context, item, field.getMetadataSchema().getName(), field.getElement(), field.getQualifier(), language, value); - - itemService.update(context, item); - - result.setContinue(true); - - result.setOutcome(true); - result.setMessage(T_metadata_added); - - return result; - } + Item item = itemService.find(context, itemID); - /** - * Withdraw the specified item, this method assumes that the action has been confirmed. - * - * @param context The DSpace context - * @param itemID The id of the to-be-withdrawn item. - * @return A result object + String fieldID = request.getParameter("field"); + String value = request.getParameter("value"); + String language = request.getParameter("language"); + + MetadataField field = metadataFieldService.find(context,Integer.valueOf(fieldID)); + + itemService.addMetadata( + context, item, field.getMetadataSchema().getName(), + field.getElement(), field.getQualifier(), language, value); + + itemService.update(context, item); + + result.setContinue(true); + + result.setOutcome(true); + result.setMessage(T_metadata_added); + + return result; + } + + + /** + * Withdraw the specified item, this method assumes that the action has been confirmed. + * + * @param context The DSpace context + * @param itemID The id of the to-be-withdrawn item. + * @return A result object * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processWithdrawItem(Context context, UUID itemID) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - Item item = itemService.find(context, itemID); - itemService.withdraw(context, item); - - result.setContinue(true); + */ + public static FlowResult processWithdrawItem(Context context, UUID itemID) + throws SQLException, AuthorizeException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(false); + + Item item = itemService.find(context, itemID); + itemService.withdraw(context, item); + + result.setContinue(true); result.setOutcome(true); result.setMessage(T_item_withdrawn); - - return result; - } - - /** - * Reinstate the specified item, this method assumes that the action has been confirmed. - * - * @param context The DSpace context - * @param itemID The id of the to-be-reinstated item. - * @return A result object + + return result; + } + + + /** + * Reinstate the specified item, this method assumes that the action has been confirmed. + * + * @param context The DSpace context + * @param itemID The id of the to-be-reinstated item. + * @return A result object * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processReinstateItem(Context context, UUID itemID) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - Item item = itemService.find(context, itemID); - itemService.reinstate(context, item); + */ + public static FlowResult processReinstateItem(Context context, UUID itemID) + throws SQLException, AuthorizeException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - result.setContinue(true); + Item item = itemService.find(context, itemID); + itemService.reinstate(context, item); + + result.setContinue(true); result.setOutcome(true); result.setMessage(T_item_reinstated); - - return result; - } + + return result; + } /** * Make the specified item Private, this method assumes that the action has been confirmed. @@ -345,7 +356,8 @@ public class FlowItemUtils * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. */ - public static FlowResult processPrivateItem(Context context, UUID itemID) throws SQLException, AuthorizeException, IOException + public static FlowResult processPrivateItem(Context context, UUID itemID) + throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); result.setContinue(false); @@ -371,7 +383,8 @@ public class FlowItemUtils * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. */ - public static FlowResult processPublicItem(Context context, UUID itemID) throws SQLException, AuthorizeException, IOException + public static FlowResult processPublicItem(Context context, UUID itemID) + throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); result.setContinue(false); @@ -400,377 +413,394 @@ public class FlowItemUtils * @throws java.io.IOException passed through. */ public static FlowResult processMoveItem(Context context, UUID itemID, UUID collectionID, boolean inherit) - throws SQLException, AuthorizeException, IOException + throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); result.setContinue(false); Item item = itemService.find(context, itemID); - if(authorizeService.isAdmin(context, item)) + if (authorizeService.isAdmin(context, item)) { - //Add an action giving this user *explicit* admin permissions on the item itself. - //This ensures that the user will be able to call itemService.update(context, item) even if he/she - // moves it to a Collection that he/she doesn't administer. - if (itemService.canEdit(context, item)) - { - authorizeService.authorizeAction(context, item, Constants.WRITE); - } + //Add an action giving this user *explicit* admin permissions on the item itself. + //This ensures that the user will be able to call itemService.update(context, item) even if he/she + // moves it to a Collection that he/she doesn't administer. + if (itemService.canEdit(context, item)) + { + authorizeService.authorizeAction(context, item, Constants.WRITE); + } - Collection destination = collectionService.find(context, collectionID); - if (destination == null) - { - result.setOutcome(false); - result.setContinue(false); - result.setMessage(T_item_move_destination_not_found); - return result; - } + Collection destination = collectionService.find(context, collectionID); + if (destination == null) + { + result.setOutcome(false); + result.setContinue(false); + result.setMessage(T_item_move_destination_not_found); + return result; + } - Collection owningCollection = item.getOwningCollection(); - if (destination.equals(owningCollection)) - { - // nothing to do - result.setOutcome(false); - result.setContinue(false); - return result; - } + Collection owningCollection = item.getOwningCollection(); + if (destination.equals(owningCollection)) + { + // nothing to do + result.setOutcome(false); + result.setContinue(false); + return result; + } - // note: an item.move() method exists, but does not handle several cases: - // - no preexisting owning collection (first arg is null) - // - item already in collection, but not an owning collection - // (works, but puts item in collection twice) + // note: an item.move() method exists, but does not handle several cases: + // - no preexisting owning collection (first arg is null) + // - item already in collection, but not an owning collection + // (works, but puts item in collection twice) - // Don't re-add the item to a collection it's already in. - boolean alreadyInCollection = false; - for (Collection collection : item.getCollections()) - { - if (collection.equals(destination)) - { - alreadyInCollection = true; - break; - } - } + // Don't re-add the item to a collection it's already in. + boolean alreadyInCollection = false; + for (Collection collection : item.getCollections()) + { + if (collection.equals(destination)) + { + alreadyInCollection = true; + break; + } + } - // Remove item from its owning collection and add to the destination - if (!alreadyInCollection) - { - collectionService.addItem(context, destination, item); - } + // Remove item from its owning collection and add to the destination + if (!alreadyInCollection) + { + collectionService.addItem(context, destination, item); + } - if (owningCollection != null) - { - collectionService.removeItem(context, owningCollection, item); - } + if (owningCollection != null) + { + collectionService.removeItem(context, owningCollection, item); + } - item.setOwningCollection(destination); + item.setOwningCollection(destination); - // Inherit policies of destination collection if required - if (inherit) - { - itemService.inheritCollectionDefaultPolicies(context, item, destination); - } + // Inherit policies of destination collection if required + if (inherit) + { + itemService.inheritCollectionDefaultPolicies(context, item, destination); + } - itemService.update(context, item); + itemService.update(context, item); - result.setOutcome(true); - result.setContinue(true); - result.setMessage(T_item_moved); + result.setOutcome(true); + result.setContinue(true); + result.setMessage(T_item_moved); } return result; } - /** - * Permanently delete the specified item, this method assumes that - * the action has been confirmed. - * - * @param context The DSpace context - * @param itemID The id of the to-be-deleted item. - * @return A result object + + /** + * Permanently delete the specified item, this method assumes that + * the action has been confirmed. + * + * @param context The DSpace context + * @param itemID The id of the to-be-deleted item. + * @return A result object * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processDeleteItem(Context context, UUID itemID) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - Item item = itemService.find(context, itemID); - itemService.delete(context, item); + */ + public static FlowResult processDeleteItem(Context context, UUID itemID) + throws SQLException, AuthorizeException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(false); + + Item item = itemService.find(context, itemID); + itemService.delete(context, item); result.setContinue(true); - - return result; - } - /** - * Add a new bitstream to the item. The bundle, bitstream (aka file), and description - * will be used to create a new bitstream. If the format needs to be adjusted then they - * will need to access the edit bitstream form after it has been uploaded. - * - * @param context The DSpace content - * @param itemID The item to add a new bitstream too - * @param request The request. - * @return A flow result + return result; + } + + + /** + * Add a new bitstream to the item. The bundle, bitstream (aka file), and description + * will be used to create a new bitstream. If the format needs to be adjusted then they + * will need to access the edit bitstream form after it has been uploaded. + * + * @param context The DSpace content + * @param itemID The item to add a new bitstream too + * @param request The request. + * @return A flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processAddBitstream(Context context, UUID itemID, Request request) throws SQLException, AuthorizeException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - // Upload a new file - Item item = itemService.find(context, itemID); - - - Object object = request.get("file"); - Part filePart = null; - if (object instanceof Part) + */ + public static FlowResult processAddBitstream(Context context, UUID itemID, Request request) + throws SQLException, AuthorizeException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(false); + + // Upload a new file + Item item = itemService.find(context, itemID); + + + Object object = request.get("file"); + Part filePart = null; + if (object instanceof Part) + { + filePart = (Part) object; + } + + if (filePart != null && filePart.getSize() > 0) + { + InputStream is = filePart.getInputStream(); + + String bundleName = request.getParameter("bundle"); + + Bitstream bitstream; + List bundles = itemService.getBundles(item, bundleName); + if (bundles.size() < 1) + { + // set bundle's name to ORIGINAL + bitstream = itemService.createSingleBitstream(context, is, item, bundleName); + + // set the permission as defined in the owning collection + Collection owningCollection = item.getOwningCollection(); + if (owningCollection != null) { - filePart = (Part) object; + Bundle bnd = bitstream.getBundles().get(0); + bundleService.inheritCollectionDefaultPolicies(context, bnd, owningCollection); } + } + else + { + // we have a bundle already, just add bitstream + bitstream = bitstreamService.create(context, bundles.get(0), is); + } - if (filePart != null && filePart.getSize() > 0) - { - InputStream is = filePart.getInputStream(); + // Strip all but the last filename. It would be nice + // to know which OS the file came from. + String name = filePart.getUploadName(); - String bundleName = request.getParameter("bundle"); - - Bitstream bitstream; - List bundles = itemService.getBundles(item, bundleName); - if (bundles.size() < 1) - { - // set bundle's name to ORIGINAL - bitstream = itemService.createSingleBitstream(context, is, item, bundleName); - - // set the permission as defined in the owning collection - Collection owningCollection = item.getOwningCollection(); - if (owningCollection != null) - { - Bundle bnd = bitstream.getBundles().get(0); - bundleService.inheritCollectionDefaultPolicies(context, bnd, owningCollection); - } - } - else - { - // we have a bundle already, just add bitstream - bitstream = bitstreamService.create(context, bundles.get(0), is); - } + while (name.indexOf('/') > -1) + { + name = name.substring(name.indexOf('/') + 1); + } - // Strip all but the last filename. It would be nice - // to know which OS the file came from. - String name = filePart.getUploadName(); + while (name.indexOf('\\') > -1) + { + name = name.substring(name.indexOf('\\') + 1); + } - while (name.indexOf('/') > -1) - { - name = name.substring(name.indexOf('/') + 1); - } + bitstream.setName(context, name); + bitstream.setSource(context, filePart.getUploadName()); + bitstream.setDescription(context, request.getParameter("description")); - while (name.indexOf('\\') > -1) - { - name = name.substring(name.indexOf('\\') + 1); - } + // Identify the format + BitstreamFormat format = bitstreamFormatService.guessFormat(context, bitstream); + bitstreamService.setFormat(context, bitstream, format); - bitstream.setName(context, name); - bitstream.setSource(context, filePart.getUploadName()); - bitstream.setDescription(context, request.getParameter("description")); - - // Identify the format - BitstreamFormat format = bitstreamFormatService.guessFormat(context, bitstream); - bitstreamService.setFormat(context, bitstream, format); - - // Update to DB - bitstreamService.update(context, bitstream); - itemService.update(context, item); + // Update to DB + bitstreamService.update(context, bitstream); + itemService.update(context, item); processAccessFields(context, request, item.getOwningCollection(), bitstream); - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_bitstream_added); - } - else - { - result.setContinue(false); - result.setOutcome(false); - result.setMessage(T_bitstream_failed); - } - return result; - } - private static void processAccessFields(Context context, HttpServletRequest request, Collection collection, Bitstream b) throws SQLException, AuthorizeException { + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_bitstream_added); + } + else + { + result.setContinue(false); + result.setOutcome(false); + result.setMessage(T_bitstream_failed); + } + return result; + } + + private static void processAccessFields(Context context, HttpServletRequest request, Collection collection, Bitstream b) + throws SQLException, AuthorizeException + { // if it is a simple form we should create the policy for Anonymous // if Anonymous does not have right on this collection, create policies for any other groups with // DEFAULT_ITEM_READ specified. Date startDate = null; - try { - startDate = DateUtils.parseDate(request.getParameter("embargo_until_date"), new String[]{"yyyy-MM-dd", "yyyy-MM", "yyyy"}); - } catch (Exception e) { + try + { + startDate = DateUtils.parseDate( + request.getParameter("embargo_until_date"), + new String[]{"yyyy-MM-dd", "yyyy-MM", "yyyy"}); + } + catch (Exception e) + { //Ignore, start date is already null } String reason = request.getParameter("reason"); - authorizeService.generateAutomaticPolicies(context, startDate, reason, b, collection); + authorizeService.generateAutomaticPolicies(context, startDate, reason, + b, collection); } - - - /** - * Update a bitstream's metadata. - * - * @param context The DSpace content - * @param itemID The item to which the bitstream belongs - * @param bitstreamID The bitstream being updated. + + + /** + * Update a bitstream's metadata. + * + * @param context The DSpace content + * @param itemID The item to which the bitstream belongs + * @param bitstreamID The bitstream being updated. * @param bitstreamName the bitstream's name. * @param primary "yes" or "no": is bitstream primary? - * @param description The new description of the bitstream - * @param formatID The new format ID of the bitstream - * @param userFormat Any user supplied formats. + * @param description The new description of the bitstream + * @param formatID The new format ID of the bitstream + * @param userFormat Any user supplied formats. * @param request user request. - * @return A flow result object. + * @return A flow result object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processEditBitstream(Context context, UUID itemID, UUID bitstreamID, String bitstreamName, - String primary, String description, int formatID, String userFormat, Request request) - throws SQLException, AuthorizeException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - Bitstream bitstream = bitstreamService.find(context, bitstreamID); - BitstreamFormat currentFormat = bitstream.getFormat(context); + */ + public static FlowResult processEditBitstream(Context context, UUID itemID, + UUID bitstreamID, String bitstreamName, String primary, + String description, int formatID, String userFormat, Request request) + throws SQLException, AuthorizeException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - //Step 1: - // Update the bitstream's description and name - if (description != null) - { - bitstream.setDescription(context, description); - } + Bitstream bitstream = bitstreamService.find(context, bitstreamID); + BitstreamFormat currentFormat = bitstream.getFormat(context); + + //Step 1: + // Update the bitstream's description and name + if (description != null) + { + bitstream.setDescription(context, description); + } if (bitstreamName != null) { bitstream.setName(context, bitstreamName); } - - //Step 2: - // Check if the primary bitstream status has changed - List bundles = bitstream.getBundles(); - if (bundles != null && bundles.size() > 0) - { - Bundle bundle = bundles.get(0); - if (bundle.getPrimaryBitstream() != null && bundle.getPrimaryBitstream().toString().equals(String.valueOf(bitstreamID))) - { - // currently the bitstream is primary - if ("no".equals(primary)) - { - // However the user has removed this bitstream as a primary bitstream. - bundle.setPrimaryBitstreamID(null); - bundleService.update(context, bundle); - } - } - else - { - // currently the bitstream is non-primary - if ("yes".equals(primary)) - { - // However the user has set this bitstream as primary. - bundle.setPrimaryBitstreamID(bitstream); - bundleService.update(context, bundle);; - } - } - } - //Step 2: - // Update the bitstream's format - if (formatID > 0) - { - if (currentFormat == null || currentFormat.getID() != formatID) - { - BitstreamFormat newFormat = bitstreamFormatService.find(context, formatID); - if (newFormat != null) - { - bitstreamService.setFormat(context, bitstream, newFormat); - } - } - } - else - { - if (userFormat != null && userFormat.length() > 0) - { - bitstreamService.setUserFormatDescription(context, bitstream, userFormat); - } - } - - //Step 3: - // Save our changes - bitstreamService.update(context, bitstream); + //Step 2: + // Check if the primary bitstream status has changed + List bundles = bitstream.getBundles(); + if (bundles != null && bundles.size() > 0) + { + Bundle bundle = bundles.get(0); + if (bundle.getPrimaryBitstream() != null && bundle.getPrimaryBitstream().toString().equals(String.valueOf(bitstreamID))) + { + // currently the bitstream is primary + if ("no".equals(primary)) + { + // However the user has removed this bitstream as a primary bitstream. + bundle.setPrimaryBitstreamID(null); + bundleService.update(context, bundle); + } + } + else + { + // currently the bitstream is non-primary + if ("yes".equals(primary)) + { + // However the user has set this bitstream as primary. + bundle.setPrimaryBitstreamID(bitstream); + bundleService.update(context, bundle);; + } + } + } + + //Step 2: + // Update the bitstream's format + if (formatID > 0) + { + if (currentFormat == null || currentFormat.getID() != formatID) + { + BitstreamFormat newFormat = bitstreamFormatService.find(context, formatID); + if (newFormat != null) + { + bitstreamService.setFormat(context, bitstream, newFormat); + } + } + } + else + { + if (userFormat != null && userFormat.length() > 0) + { + bitstreamService.setUserFormatDescription(context, bitstream, userFormat); + } + } + + //Step 3: + // Save our changes + bitstreamService.update(context, bitstream); result.setContinue(true); result.setOutcome(true); result.setMessage(T_bitstream_updated); - return result; - } - - /** - * Delete the given bitstreams from the bundle and item. If there are no more bitstreams - * left in a bundle then also remove it. - * - * @param context Current dspace content - * @param itemID The item id from which to remove bitstreams - * @param bitstreamIDs A bundleID slash bitstreamID pair of bitstreams to be removed. - * @return A flow result + return result; + } + + + /** + * Delete the given bitstreams from the bundle and item. If there are no more bitstreams + * left in a bundle then also remove it. + * + * @param context Current dspace content + * @param itemID The item id from which to remove bitstreams + * @param bitstreamIDs A bundleID slash bitstreamID pair of bitstreams to be removed. + * @return A flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. * @throws org.dspace.app.xmlui.utils.UIException if bitstreamIDs cannot be parsed. - */ - public static FlowResult processDeleteBitstreams(Context context, UUID itemID, String[] bitstreamIDs) - throws SQLException, AuthorizeException, IOException, UIException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - Item item = itemService.find(context, itemID); - - for (String id : bitstreamIDs) - { - String[] parts = id.split("/"); - - if (parts.length != 2) + */ + public static FlowResult processDeleteBitstreams(Context context, UUID itemID, String[] bitstreamIDs) + throws SQLException, AuthorizeException, IOException, UIException + { + FlowResult result = new FlowResult(); + result.setContinue(false); + + Item item = itemService.find(context, itemID); + + for (String id : bitstreamIDs) + { + String[] parts = id.split("/"); + + if (parts.length != 2) { - throw new UIException("Unable to parse id into bundle and bitstream id: "+id); + throw new UIException("Unable to parse id into bundle and bitstream id: "+id); } - - UUID bundleID = UUID.fromString(parts[0]); - UUID bitstreamID = UUID.fromString(parts[1]); - - Bundle bundle = bundleService.find(context, bundleID); - Bitstream bitstream = bitstreamService.find(context,bitstreamID); - - bundleService.removeBitstream(context, bundle, bitstream); - - if (bundle.getBitstreams().size() == 0) - { - itemService.removeBundle(context, item, bundle); - } - } - - itemService.update(context, item); - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_bitstream_delete); - - return result; - } + UUID bundleID = UUID.fromString(parts[0]); + UUID bitstreamID = UUID.fromString(parts[1]); - public static FlowResult processReorderBitstream(Context context, UUID itemID, Request request) throws SQLException, AuthorizeException { + Bundle bundle = bundleService.find(context, bundleID); + Bitstream bitstream = bitstreamService.find(context,bitstreamID); + + bundleService.removeBitstream(context, bundle, bitstream); + + if (bundle.getBitstreams().size() == 0) + { + itemService.removeBundle(context, item, bundle); + } + } + + itemService.update(context, item); + + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_bitstream_delete); + + return result; + } + + + public static FlowResult processReorderBitstream(Context context, UUID itemID, Request request) + throws SQLException, AuthorizeException + { String submitButton = Util.getSubmitButton(request, "submit_update_order"); FlowResult result = new FlowResult(); result.setContinue(false); @@ -778,13 +808,15 @@ public class FlowItemUtils Item item = itemService.find(context, itemID); List bundles = item.getBundles(); - for (Bundle bundle : bundles) { + for (Bundle bundle : bundles) + { List bitstreams = bundle.getBitstreams(); UUID[] newBitstreamOrder = new UUID[bitstreams.size()]; - if (submitButton.equals("submit_update_order")) { + if (submitButton.equals("submit_update_order")) + { for (Bitstream bitstream : bitstreams) { - //The order is determined by javascript + //The order is determined by javascript //For each of our bitstream retrieve the order value int order = Util.getIntParameter(request, "order_" + bitstream.getID()); //-1 the order since the order needed to start from one @@ -792,21 +824,26 @@ public class FlowItemUtils //Place the bitstream identifier in the correct order newBitstreamOrder[order] = bitstream.getID(); } - }else{ + } + else + { //Javascript isn't operational retrieve the value from the hidden field //Retrieve the button key String inputKey = submitButton.replace("submit_order_", "") + "_value"; - if(inputKey.startsWith(bundle.getID() + "_")){ + if (inputKey.startsWith(bundle.getID() + "_")) + { String[] vals = request.getParameter(inputKey).split(","); for (int i = 0; i < vals.length; i++) { String val = vals[i]; newBitstreamOrder[i] = UUID.fromString(val); } - }else{ + } + else + { newBitstreamOrder = null; } } - if(newBitstreamOrder != null){ + if (newBitstreamOrder != null){ //Set the new order in our bundle ! bundleService.setOrder(context, bundle, newBitstreamOrder); bundleService.update(context, bundle); @@ -820,6 +857,7 @@ public class FlowItemUtils return result; } + /** * processCurateDSO * @@ -834,26 +872,27 @@ public class FlowItemUtils * @throws java.sql.SQLException passed through. */ public static FlowResult processCurateItem(Context context, UUID itemID, Request request) - throws AuthorizeException, IOException, SQLException, Exception - { - String task = request.getParameter("curate_task"); - Curator curator = FlowCurationUtils.getCurator(task); - try - { - Item item = itemService.find(context, itemID); - if (item != null) - { - //Call curate(context,ID) to ensure a Task Performer (Eperson) is set in Curator - curator.curate(context, item.getHandle()); - } - return FlowCurationUtils.getRunFlowResult(task, curator, true); - } - catch (Exception e) - { - curator.setResult(task, e.getMessage()); - return FlowCurationUtils.getRunFlowResult(task, curator, false); - } - } + throws AuthorizeException, IOException, SQLException, Exception + { + String task = request.getParameter("curate_task"); + Curator curator = FlowCurationUtils.getCurator(task); + try + { + Item item = itemService.find(context, itemID); + if (item != null) + { + // Call curate(context,ID) to ensure a Task Performer (Eperson) is set in Curator + curator.curate(context, item.getHandle()); + } + return FlowCurationUtils.getRunFlowResult(task, curator, true); + } + catch (Exception e) + { + curator.setResult(task, e.getMessage()); + return FlowCurationUtils.getRunFlowResult(task, curator, false); + } + } + /** * queues curation tasks. @@ -868,53 +907,59 @@ public class FlowItemUtils */ public static FlowResult processQueueItem(Context context, UUID itemID, Request request) throws AuthorizeException, IOException, SQLException, Exception - { - String task = request.getParameter("curate_task"); - Curator curator = FlowCurationUtils.getCurator(task); - String objId = String.valueOf(itemID); - String taskQueueName = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.ui.queuename"); - boolean status = false; - Item item = itemService.find(context, itemID); - if (item != null) - { - objId = item.getHandle(); - try - { - curator.queue(context, objId, taskQueueName); - status = true; - } - catch (IOException ioe) - { - // no-op (the Curator should have already logged any error that occurred) - } - } - return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); - } + { + String task = request.getParameter("curate_task"); + Curator curator = FlowCurationUtils.getCurator(task); + String objId = String.valueOf(itemID); + String taskQueueName = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("curate.ui.queuename"); + boolean status = false; + Item item = itemService.find(context, itemID); + if (item != null) + { + objId = item.getHandle(); + try + { + curator.queue(context, objId, taskQueueName); + status = true; + } + catch (IOException ioe) + { + // no-op (the Curator should have already logged any error that occurred) + } + } + return FlowCurationUtils.getQueueFlowResult(task, status, objId, taskQueueName); + } - /** - * Parse the given name into three parts, divided by an _. Each part should represent the - * schema, element, and qualifier. You are guaranteed that if no qualifier was supplied the - * third entry is null. - * - * @param name The name to be parsed. - * @return An array of name parts. - */ - private static String[] parseName(String name) throws UIException - { - String[] parts = new String[3]; - - String[] split = name.split("_"); - if (split.length == 2) { - parts[0] = split[0]; - parts[1] = split[1]; - parts[2] = null; - } else if (split.length == 3) { - parts[0] = split[0]; - parts[1] = split[1]; - parts[2] = split[2]; - } else { - throw new UIException("Unable to parse metedata field name: "+name); - } - return parts; - } + /** + * Parse the given name into three parts, divided by an _. Each part should represent the + * schema, element, and qualifier. You are guaranteed that if no qualifier was supplied the + * third entry is null. + * + * @param name The name to be parsed. + * @return An array of name parts. + */ + private static String[] parseName(String name) + throws UIException + { + String[] parts = new String[3]; + + String[] split = name.split("_"); + if (split.length == 2) + { + parts[0] = split[0]; + parts[1] = split[1]; + parts[2] = null; + } + else if (split.length == 3) + { + parts[0] = split[0]; + parts[1] = split[1]; + parts[2] = split[2]; + } + else + { + throw new UIException("Unable to parse metedata field name: "+name); + } + return parts; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowMapperUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowMapperUtils.java index 5b0d81c6ba..5a1be11ae0 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowMapperUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowMapperUtils.java @@ -28,40 +28,39 @@ import org.dspace.core.Context; * * @author Scott Phillips */ -public class FlowMapperUtils +public class FlowMapperUtils { - /** Language Strings */ - private static final Message T_map_items = new Message("default","xmlui.administrative.FlowMapperUtils.map_items"); - private static final Message T_unmaped_items = new Message("default","xmlui.administrative.FlowMapperUtils.unmaped_items"); + /** Language Strings */ + private static final Message T_map_items = new Message("default","xmlui.administrative.FlowMapperUtils.map_items"); + private static final Message T_unmaped_items = new Message("default","xmlui.administrative.FlowMapperUtils.unmaped_items"); - protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected static final AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected static final CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected static final ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - - /** - * Map the given items into this collection - * - * @param context The current DSpace content - * @param collectionID The collection to map items into. - * @param itemIDs The items to map. - * @return Flow result + /** + * Map the given items into this collection + * + * @param context The current DSpace content + * @param collectionID The collection to map items into. + * @param itemIDs The items to map. + * @return Flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processMapItems(Context context, UUID collectionID, String[] itemIDs) - throws SQLException, AuthorizeException, UIException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); + */ + public static FlowResult processMapItems(Context context, UUID collectionID, String[] itemIDs) + throws SQLException, AuthorizeException, UIException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - Collection toCollection = collectionService.find(context,collectionID); + Collection toCollection = collectionService.find(context,collectionID); - for (String itemID : itemIDs) + for (String itemID : itemIDs) { Item item = itemService.find(context, UUID.fromString(itemID)); @@ -74,36 +73,36 @@ public class FlowMapperUtils } } } - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_map_items); - - return result; - } - - /** - * Unmap the given items from this collection - * - * @param context The DSpace context - * @param collectionID The collection to unmap these items from. - * @param itemIDs The items to be unmapped. - * @return A flow result + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_map_items); + + return result; + } + + /** + * Unmap the given items from this collection + * + * @param context The DSpace context + * @param collectionID The collection to unmap these items from. + * @param itemIDs The items to be unmapped. + * @return A flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processUnmapItems(Context context, UUID collectionID, String[] itemIDs) - throws SQLException, AuthorizeException, UIException, IOException - { - FlowResult result = new FlowResult(); - result.setContinue(false); + */ + public static FlowResult processUnmapItems(Context context, UUID collectionID, String[] itemIDs) + throws SQLException, AuthorizeException, UIException, IOException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - Collection toCollection = collectionService.find(context,collectionID); - - for (String itemID : itemIDs) + Collection toCollection = collectionService.find(context,collectionID); + + for (String itemID : itemIDs) { Item item = itemService.find(context, UUID.fromString(itemID)); @@ -117,11 +116,10 @@ public class FlowMapperUtils } } - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_unmaped_items); - - return result; - } - + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_unmaped_items); + + return result; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowRegistryUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowRegistryUtils.java index 51577242d9..c34b6226a3 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowRegistryUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowRegistryUtils.java @@ -33,54 +33,53 @@ import java.util.List; /** * */ -public class FlowRegistryUtils +public class FlowRegistryUtils { - /** Language Strings */ - private static final Message T_add_metadata_schema_success_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.add_metadata_schema_success_notice"); - private static final Message T_delete_metadata_schema_success_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.delete_metadata_schema_success_notice"); - private static final Message T_add_metadata_field_success_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.add_metadata_field_success_notice"); - private static final Message T_edit_metadata_field_success_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.edit_metadata_field_success_notice"); - private static final Message T_move_metadata_field_sucess_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.move_metadata_field_success_notice"); - private static final Message T_delete_metadata_field_success_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.delete_metadata_field_success_notice"); - private static final Message T_edit_bitstream_format_success_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.edit_bitstream_format_success_notice"); - private static final Message T_delete_bitstream_format_success_notice = - new Message("default","xmlui.administrative.FlowRegistryUtils.delete_bitstream_format_success_notice"); + /** Language Strings */ + private static final Message T_add_metadata_schema_success_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.add_metadata_schema_success_notice"); + private static final Message T_delete_metadata_schema_success_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.delete_metadata_schema_success_notice"); + private static final Message T_add_metadata_field_success_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.add_metadata_field_success_notice"); + private static final Message T_edit_metadata_field_success_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.edit_metadata_field_success_notice"); + private static final Message T_move_metadata_field_sucess_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.move_metadata_field_success_notice"); + private static final Message T_delete_metadata_field_success_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.delete_metadata_field_success_notice"); + private static final Message T_edit_bitstream_format_success_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.edit_bitstream_format_success_notice"); + private static final Message T_delete_bitstream_format_success_notice = + new Message("default","xmlui.administrative.FlowRegistryUtils.delete_bitstream_format_success_notice"); - protected static final MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); - protected static final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); - protected static final MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); + protected static final MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); + protected static final BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); + protected static final MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); - - - /** - * Add a new metadata schema. The ID of the new schema will be added - * as the "schemaID" parameter on the results object. - * - * @param context The DSpace context - * @param namespace The new schema's namespace - * @param name The new schema's name. - * @return A flow result + + /** + * Add a new metadata schema. The ID of the new schema will be added + * as the "schemaID" parameter on the results object. + * + * @param context The DSpace context + * @param namespace The new schema's namespace + * @param name The new schema's name. + * @return A flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.content.NonUniqueMetadataException passed through. * @throws org.dspace.app.xmlui.utils.UIException on unsupported encoding. - */ - public static FlowResult processAddMetadataSchema(Context context, String namespace, String name) - throws SQLException, AuthorizeException, NonUniqueMetadataException, UIException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - // Decode the namespace and name - try + */ + public static FlowResult processAddMetadataSchema(Context context, String namespace, String name) + throws SQLException, AuthorizeException, NonUniqueMetadataException, UIException + { + FlowResult result = new FlowResult(); + result.setContinue(false); + + // Decode the namespace and name + try { namespace = URLDecoder.decode(namespace, Constants.DEFAULT_ENCODING); name = URLDecoder.decode(name,Constants.DEFAULT_ENCODING); @@ -89,100 +88,99 @@ public class FlowRegistryUtils { throw new UIException(uee); } - - if (namespace == null || namespace.length() <= 0) + + if (namespace == null || namespace.length() <= 0) { result.addError("namespace"); } - if (name == null || - name.length() <= 0 || - name.indexOf('.') != -1 || - name.indexOf('_') != -1 || - name.indexOf(' ') != -1) + if (name == null || + name.length() <= 0 || + name.indexOf('.') != -1 || + name.indexOf('_') != -1 || + name.indexOf(' ') != -1) { // The name must not be empty nor contain dot, underscore or spaces. result.addError("name"); } - - - if (result.getErrors() == null) - { - MetadataSchema schema = metadataSchemaService.create(context, name, namespace); - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_add_metadata_schema_success_notice); - result.setParameter("schemaID", schema.getID()); - } - - return result; - } - - /** - * Delete the given schemas. - * - * @param context The DSpace context - * @param schemaIDs A list of schema IDs to be deleted. - * @return A flow result + if (result.getErrors() == null) + { + MetadataSchema schema = metadataSchemaService.create(context, name, namespace); + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_add_metadata_schema_success_notice); + result.setParameter("schemaID", schema.getID()); + } + + return result; + } + + /** + * Delete the given schemas. + * + * @param context The DSpace context + * @param schemaIDs A list of schema IDs to be deleted. + * @return A flow result * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.content.NonUniqueMetadataException passed through. - */ - public static FlowResult processDeleteMetadataSchemas(Context context, String[] schemaIDs) - throws SQLException, AuthorizeException, NonUniqueMetadataException - { - FlowResult result = new FlowResult(); - - int count = 0; - for (String id : schemaIDs) - { - MetadataSchema schema = metadataSchemaService.find(context, Integer.valueOf(id)); - - // First remove and fields in the schema - List fields = metadataFieldService.findAllInSchema(context, schema); - for (MetadataField field : fields) + */ + public static FlowResult processDeleteMetadataSchemas(Context context, String[] schemaIDs) + throws SQLException, AuthorizeException, NonUniqueMetadataException + { + FlowResult result = new FlowResult(); + + int count = 0; + for (String id : schemaIDs) + { + MetadataSchema schema = metadataSchemaService.find(context, Integer.valueOf(id)); + + // First remove and fields in the schema + List fields = metadataFieldService.findAllInSchema(context, schema); + for (MetadataField field : fields) { - metadataFieldService.delete(context, field); + metadataFieldService.delete(context, field); } - - // Once all the fields are gone, then delete the schema. - metadataSchemaService.delete(context, schema); - count++; - } - - if (count > 0) - { - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_delete_metadata_schema_success_notice); - } - - return result; - } - - /** - * Add a new metadata field. The newly created field's ID will be added as - * the "fieldID" parameter on the results object. - * - * @param context The DSpace context - * @param schemaID The id of the schema where this new field should be added. - * @param element The field's element. - * @param qualifier The field's qualifier. - * @param note A scope not about the field. - * @return A results object + + // Once all the fields are gone, then delete the schema. + metadataSchemaService.delete(context, schema); + count++; + } + + if (count > 0) + { + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_delete_metadata_schema_success_notice); + } + + return result; + } + + /** + * Add a new metadata field. The newly created field's ID will be added as + * the "fieldID" parameter on the results object. + * + * @param context The DSpace context + * @param schemaID The id of the schema where this new field should be added. + * @param element The field's element. + * @param qualifier The field's qualifier. + * @param note A scope not about the field. + * @return A results object * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.sql.SQLException passed through. * @throws org.dspace.app.xmlui.utils.UIException on unsupported encoding. - */ - public static FlowResult processAddMetadataField(Context context, int schemaID, String element, String qualifier, String note) - throws IOException, AuthorizeException, SQLException, UIException - { - FlowResult result = new FlowResult(); - result.setContinue(false); + */ + public static FlowResult processAddMetadataField(Context context, int schemaID, String element, String qualifier, String note) + throws IOException, AuthorizeException, SQLException, UIException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - // Decode the element, qualifier, and note. - try + // Decode the element, qualifier, and note. + try { element = URLDecoder.decode(element, Constants.DEFAULT_ENCODING); qualifier = URLDecoder.decode(qualifier,Constants.DEFAULT_ENCODING); @@ -192,62 +190,61 @@ public class FlowRegistryUtils { throw new UIException(uee); } - - // Check if the field name is good. - result.setErrors(checkMetadataFieldName(element, qualifier)); - - // Make sure qualifier is null if blank. - if ("".equals(qualifier)) + + // Check if the field name is good. + result.setErrors(checkMetadataFieldName(element, qualifier)); + + // Make sure qualifier is null if blank. + if ("".equals(qualifier)) { qualifier = null; } - - if (result.getErrors() == null) - { - try - { - MetadataSchema schema = metadataSchemaService.find(context, schemaID); - MetadataField field = metadataFieldService.create(context, schema, element, qualifier, note); + if (result.getErrors() == null) + { + try + { + MetadataSchema schema = metadataSchemaService.find(context, schemaID); + MetadataField field = metadataFieldService.create(context, schema, element, qualifier, note); - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_add_metadata_field_success_notice); - result.setParameter("fieldID", field.getID()); - } - catch (NonUniqueMetadataException nume) - { - result.addError("duplicate_field"); - } - - } - - return result; - } - - /** - * Edit a metadata field. - * - * @param context The DSpace context. - * @param schemaID The ID of the schema for this field. - * @param fieldID The id of this field. - * @param element A new element value - * @param qualifier A new qualifier value - * @param note A new note value. - * @return A results object. + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_add_metadata_field_success_notice); + result.setParameter("fieldID", field.getID()); + } + catch (NonUniqueMetadataException nume) + { + result.addError("duplicate_field"); + } + + } + + return result; + } + + /** + * Edit a metadata field. + * + * @param context The DSpace context. + * @param schemaID The ID of the schema for this field. + * @param fieldID The id of this field. + * @param element A new element value + * @param qualifier A new qualifier value + * @param note A new note value. + * @return A results object. * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.sql.SQLException passed through. * @throws org.dspace.app.xmlui.utils.UIException on unsupported encoding. - */ - public static FlowResult processEditMetadataField(Context context, int schemaID, int fieldID, String element, String qualifier, String note) - throws IOException, AuthorizeException, SQLException, UIException - { - FlowResult result = new FlowResult(); - result.setContinue(false); + */ + public static FlowResult processEditMetadataField(Context context, int schemaID, int fieldID, String element, String qualifier, String note) + throws IOException, AuthorizeException, SQLException, UIException + { + FlowResult result = new FlowResult(); + result.setContinue(false); - // Decode the element, qualifier, and note. - try + // Decode the element, qualifier, and note. + try { element = URLDecoder.decode(element, Constants.DEFAULT_ENCODING); qualifier = URLDecoder.decode(qualifier,Constants.DEFAULT_ENCODING); @@ -257,197 +254,198 @@ public class FlowRegistryUtils { throw new UIException(uee); } - - // Check if the field name is good. - result.setErrors(checkMetadataFieldName(element, qualifier)); - - // Make sure qualifier is null if blank. - if ("".equals(qualifier)) + + // Check if the field name is good. + result.setErrors(checkMetadataFieldName(element, qualifier)); + + // Make sure qualifier is null if blank. + if ("".equals(qualifier)) { qualifier = null; } - - // Check to make sure the field is unique, sometimes the NonUniqueMetadataException is not thrown. - MetadataField possibleDuplicate = metadataFieldService.findByElement(context, metadataSchemaService.find(context, schemaID), element, qualifier); - if (possibleDuplicate != null && possibleDuplicate.getID() != fieldID) + + // Check to make sure the field is unique, sometimes the NonUniqueMetadataException is not thrown. + MetadataField possibleDuplicate = metadataFieldService.findByElement(context, metadataSchemaService.find(context, schemaID), element, qualifier); + if (possibleDuplicate != null && possibleDuplicate.getID() != fieldID) { result.addError("duplicate_field"); } - - if (result.getErrors() == null) - { - try - { - // Update the metadata for a DC type - MetadataField field = metadataFieldService.find(context, fieldID); - field.setElement(element); - field.setQualifier(qualifier); - field.setScopeNote(note); - metadataFieldService.update(context, field); - - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_edit_metadata_field_success_notice); - } - catch (NonUniqueMetadataException nume) - { - // This shouldn't ever occure. - result.addError("duplicate_field"); - } - } - - return result; - } - - /** - * Simple method to check the a metadata field's name: element and qualifier. - * - * @param element The field's element. - * @param qualifier The field's qualifier - * @return A list of errors found, null if none are found. - */ - private static List checkMetadataFieldName(String element, String qualifier) - { - List errors = new ArrayList(); - - - // Is the element empty? - if (element == null || element.length() <= 0) - { - element = ""; // so that the rest of the checks don't fail. - errors.add("element_empty"); - } - - // Is there a bad character in the element? - if (element.indexOf('.') != -1 || - element.indexOf('_') != -1 || - element.indexOf(' ') != -1) + + if (result.getErrors() == null) + { + try + { + // Update the metadata for a DC type + MetadataField field = metadataFieldService.find(context, fieldID); + field.setElement(element); + field.setQualifier(qualifier); + field.setScopeNote(note); + metadataFieldService.update(context, field); + + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_edit_metadata_field_success_notice); + } + catch (NonUniqueMetadataException nume) + { + // This shouldn't ever occure. + result.addError("duplicate_field"); + } + } + + return result; + } + + /** + * Simple method to check the a metadata field's name: element and qualifier. + * + * @param element The field's element. + * @param qualifier The field's qualifier + * @return A list of errors found, null if none are found. + */ + private static List checkMetadataFieldName(String element, String qualifier) + { + List errors = new ArrayList(); + + + // Is the element empty? + if (element == null || element.length() <= 0) + { + element = ""; // so that the rest of the checks don't fail. + errors.add("element_empty"); + } + + // Is there a bad character in the element? + if (element.indexOf('.') != -1 || + element.indexOf('_') != -1 || + element.indexOf(' ') != -1) { errors.add("element_badchar"); } - - // Is the element too long? - if (element.length() > 64) + + // Is the element too long? + if (element.length() > 64) { errors.add("element_tolong"); } - - // The qualifier can be empty. - if (qualifier != null && qualifier.length() > 0) - { - if (qualifier.length() > 64) + + // The qualifier can be empty. + if (qualifier != null && qualifier.length() > 0) + { + if (qualifier.length() > 64) { errors.add("qualifier_tolong"); } - - if (qualifier.indexOf('.') != -1 || - qualifier.indexOf('_') != -1 || - qualifier.indexOf(' ') != -1) + + if (qualifier.indexOf('.') != -1 || + qualifier.indexOf('_') != -1 || + qualifier.indexOf(' ') != -1) { errors.add("qualifier_badchar"); } - } - - // If there were no errors then just return null. - if (errors.size() == 0) + } + + // If there were no errors then just return null. + if (errors.size() == 0) { return null; } - - return errors; - } - - /** - * Move the specified metadata fields to the target schema. - * - * @param context The DSpace context - * @param schemaID The target schema ID - * @param fieldIDs The fields to be moved. - * @return A results object. + + return errors; + } + + /** + * Move the specified metadata fields to the target schema. + * + * @param context The DSpace context + * @param schemaID The target schema ID + * @param fieldIDs The fields to be moved. + * @return A results object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws org.dspace.content.NonUniqueMetadataException passed through. * @throws java.io.IOException passed through. - */ - public static FlowResult processMoveMetadataField(Context context, int schemaID, String[] fieldIDs) - throws NumberFormatException, SQLException, AuthorizeException, NonUniqueMetadataException, IOException - { - FlowResult result = new FlowResult(); - - int count = 0; - for (String id : fieldIDs) - { - MetadataField field = metadataFieldService.find(context, Integer.valueOf(id)); - field.setMetadataSchema(metadataSchemaService.find(context, schemaID)); - metadataFieldService.update(context, field); - count++; - } - - if (count > 0) - { - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_move_metadata_field_sucess_notice); - } - - return result; - } - - - /** - * Delete the specified metadata fields. - * - * @param context The DSpace context - * @param fieldIDs The fields to be deleted. - * @return A results object - * @throws java.sql.SQLException passed through. - * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processDeleteMetadataField(Context context, String[] fieldIDs) - throws NumberFormatException, SQLException, AuthorizeException - { + */ + public static FlowResult processMoveMetadataField(Context context, int schemaID, String[] fieldIDs) + throws NumberFormatException, SQLException, AuthorizeException, NonUniqueMetadataException, IOException + { FlowResult result = new FlowResult(); - - int count = 0; - for (String id : fieldIDs) - { - MetadataField field = metadataFieldService.find(context, Integer.valueOf(id)); - metadataFieldService.delete(context, field); - count++; - } - - if (count > 0) - { - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_delete_metadata_field_success_notice); - } - - return result; - } - - - /** - * Edit a bitstream format. If the formatID is -1 then a new format is created. - * The formatID of the new format is added as a parameter to the results object. - * - * FIXME: the reason we accept a request object is so that we can use the - * RequestUtils.getFieldvalues() to get the multivalue field values. - * - * @param context The dspace context - * @param formatID The id of the format being updated. - * @param request The request object, for all the field entries. - * @return A results object + + int count = 0; + for (String id : fieldIDs) + { + MetadataField field = metadataFieldService.find(context, Integer.valueOf(id)); + field.setMetadataSchema(metadataSchemaService.find(context, schemaID)); + metadataFieldService.update(context, field); + count++; + } + + if (count > 0) + { + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_move_metadata_field_sucess_notice); + } + + return result; + } + + + /** + * Delete the specified metadata fields. + * + * @param context The DSpace context + * @param fieldIDs The fields to be deleted. + * @return A results object * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processEditBitstreamFormat(Context context, int formatID, Request request) throws SQLException, AuthorizeException - { - FlowResult result = new FlowResult(); - result.setContinue(false); - - // Get the values + */ + public static FlowResult processDeleteMetadataField(Context context, String[] fieldIDs) + throws NumberFormatException, SQLException, AuthorizeException + { + FlowResult result = new FlowResult(); + + int count = 0; + for (String id : fieldIDs) + { + MetadataField field = metadataFieldService.find(context, Integer.valueOf(id)); + metadataFieldService.delete(context, field); + count++; + } + + if (count > 0) + { + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_delete_metadata_field_success_notice); + } + + return result; + } + + + /** + * Edit a bitstream format. If the formatID is -1 then a new format is created. + * The formatID of the new format is added as a parameter to the results object. + * + * FIXME: the reason we accept a request object is so that we can use the + * RequestUtils.getFieldvalues() to get the multivalue field values. + * + * @param context The dspace context + * @param formatID The id of the format being updated. + * @param request The request object, for all the field entries. + * @return A results object + * @throws java.sql.SQLException passed through. + * @throws org.dspace.authorize.AuthorizeException passed through. + */ + public static FlowResult processEditBitstreamFormat(Context context, int formatID, Request request) + throws SQLException, AuthorizeException + { + FlowResult result = new FlowResult(); + result.setContinue(false); + + // Get the values String mimeType = request.getParameter("mimetype"); String shortDescription = request.getParameter("short_description"); String description = request.getParameter("description"); @@ -458,92 +456,91 @@ public class FlowRegistryUtils // The format must at least have a name. if (formatID != 1 && (shortDescription == null || shortDescription.length() == 0)) { - result.addError("short_description"); - return result; + result.addError("short_description"); + return result; } - + // Remove leading periods from file extensions. for (int i = 0; i < extensionsList.size(); i++) { - if (extensionsList.get(i).startsWith(".")) + if (extensionsList.get(i).startsWith(".")) { - extensionsList.set(i, extensionsList.get(i).substring(1)); + extensionsList.set(i, extensionsList.get(i).substring(1)); } } - - + + // Get or create the format BitstreamFormat format; - if (formatID >= 0) + if (formatID >= 0) { format = bitstreamFormatService.find(context, formatID); } - else + else { format = bitstreamFormatService.create(context); } - - // Update values - format.setMIMEType(mimeType); - if (formatID != 1) // don't change the unknow format. + + // Update values + format.setMIMEType(mimeType); + if (formatID != 1) // don't change the unknow format. { format.setShortDescription(context, shortDescription); } - format.setDescription(description); - format.setSupportLevel(Integer.valueOf(supportLevel)); - if (internal == null) + format.setDescription(description); + format.setSupportLevel(Integer.valueOf(supportLevel)); + if (internal == null) { format.setInternal(false); } - else + else { format.setInternal(true); } - format.setExtensions(extensionsList); + format.setExtensions(extensionsList); - - // Commit the change - bitstreamFormatService.update(context, format); - // Return status + // Commit the change + bitstreamFormatService.update(context, format); + + // Return status result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_edit_bitstream_format_success_notice); - result.setParameter("formatID",format.getID()); - - return result; - } - - /** - * Delete the specified bitstream formats. - * - * @param context The DSpace context - * @param formatIDs The formats-to-be-deleted. - * @return A results object. + result.setOutcome(true); + result.setMessage(T_edit_bitstream_format_success_notice); + result.setParameter("formatID",format.getID()); + + return result; + } + + /** + * Delete the specified bitstream formats. + * + * @param context The DSpace context + * @param formatIDs The formats-to-be-deleted. + * @return A results object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ - public static FlowResult processDeleteBitstreamFormats(Context context, String[] formatIDs) - throws NumberFormatException, SQLException, AuthorizeException - { + */ + public static FlowResult processDeleteBitstreamFormats(Context context, String[] formatIDs) + throws NumberFormatException, SQLException, AuthorizeException + { FlowResult result = new FlowResult(); - - int count = 0; - for (String id : formatIDs) - { - BitstreamFormat format = bitstreamFormatService.find(context,Integer.valueOf(id)); - bitstreamFormatService.delete(context, format); - count++; - } - - if (count > 0) - { - result.setContinue(true); - result.setOutcome(true); - result.setMessage(T_delete_bitstream_format_success_notice); - } - - return result; - } - + + int count = 0; + for (String id : formatIDs) + { + BitstreamFormat format = bitstreamFormatService.find(context, Integer.valueOf(id)); + bitstreamFormatService.delete(context, format); + count++; + } + + if (count > 0) + { + result.setContinue(true); + result.setOutcome(true); + result.setMessage(T_delete_bitstream_format_success_notice); + } + + return result; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowResult.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowResult.java index 632224068d..6b1f3674c9 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowResult.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/FlowResult.java @@ -19,284 +19,284 @@ import org.dspace.app.xmlui.wing.Message; * in this administrative section. Typically, some method performs an operation * and returns an object of type FlowResult, then the flow script can inspect * the results object to determine what the next course of action is. - * + * *

    Basically, this results object stores all the errors and continuation states * that need to be represented. There are four types of information stored: - * + * *

    1) Continuation, this is a simple boolean variable that indicates whether * the required operation is complete and the user may continue on to the next step. - * + * *

    2) Notice information, this is a simple encoding of a notice message to be displayed * to the user on their next step. There are four parts: outcome, header, message, and * characters. See each field for more description on each part. Note: either a message * or characters are required. - * + * *

    3) Errors, this is a list of errors that were encountered during processing. - * Typically, it just consists of a list of errored fields. However occasionally there + * Typically, it just consists of a list of errored fields. However occasionally there * may be other specialized errors listed. - * + * *

    4) Parameters, this is a map of attached parameters that may be relevant to the * result. This should be used for things such as generated id's when objects are newly * created. - * + * * @author Scott Phillips */ public class FlowResult { - /** - * Determine whether the operation has been completed enough that the user - * may successfully continue on to the next step. - */ - private boolean continuep; - - /** - * Notice parameters: - * - * Outcome: The outcome of the notice, may be either success, failure, or neutral. - * - * Header: The notice's label, an i18n dictionary key. - * - * message: The main body of the notice, an i18n dictionary key. - * - * characters: Supplemental information for the notice, plain text. This is - * typically used for exceptions. - * - */ - private enum Outcome{ SUCCESS, FAILURE, NEUTRAL}; - private Outcome outcome = Outcome.NEUTRAL; - private Message header; - private Message message; - private String characters; - - /** - * A list of errors encountered while processing this operation. - */ - private List errors; - - /** - * Any parameters that may be attached to this result. - */ - private Map parameters; - - /** - * Set the continuation parameter determining if the - * user should progress to the next step in the flow. + /** + * Determine whether the operation has been completed enough that the user + * may successfully continue on to the next step. + */ + private boolean continuep; + + /** + * Notice parameters: + * + * Outcome: The outcome of the notice, may be either success, failure, or neutral. + * + * Header: The notice's label, an i18n dictionary key. + * + * message: The main body of the notice, an i18n dictionary key. + * + * characters: Supplemental information for the notice, plain text. This is + * typically used for exceptions. + * + */ + private enum Outcome{ SUCCESS, FAILURE, NEUTRAL}; + private Outcome outcome = Outcome.NEUTRAL; + private Message header; + private Message message; + private String characters; + + /** + * A list of errors encountered while processing this operation. + */ + private List errors; + + /** + * Any parameters that may be attached to this result. + */ + private Map parameters; + + /** + * Set the continuation parameter determining if the + * user should progress to the next step in the flow. * @param continuep true if should continue. - */ - public void setContinue(boolean continuep) - { - this.continuep = continuep; - } - - /** - * Determine if the user should progress to the - * next step in the flow. - * - * @return the continuation parameter - */ - public boolean getContinue() - { - return this.continuep; - } - - - - /** - * Set the notice outcome to either success or failure. Note, - * the default outcome is neutral, once an outcome is set the - * neutral outcome can never be attained again. - * - * @param success True for success, false for failure. - */ - public void setOutcome(boolean success) - { - if (success) + */ + public void setContinue(boolean continuep) + { + this.continuep = continuep; + } + + /** + * Determine if the user should progress to the + * next step in the flow. + * + * @return the continuation parameter + */ + public boolean getContinue() + { + return this.continuep; + } + + + + /** + * Set the notice outcome to either success or failure. Note, + * the default outcome is neutral, once an outcome is set the + * neutral outcome can never be attained again. + * + * @param success True for success, false for failure. + */ + public void setOutcome(boolean success) + { + if (success) { outcome = Outcome.SUCCESS; } - else + else { outcome = Outcome.FAILURE; } - } - - /** - * Get the notice outcome in string form, either success - * or failure. If the outcome is neutral then null is returned. + } + + /** + * Get the notice outcome in string form, either success + * or failure. If the outcome is neutral then null is returned. * @return the outcome. - */ - public String getOutcome() - { - if (outcome == Outcome.SUCCESS) - { - return "success"; - } - else if (outcome == Outcome.FAILURE) - { - return "failure"; - } - return null; - } - - /** - * Set the notice header. - * - * This must be an i18n dictionary key + */ + public String getOutcome() + { + if (outcome == Outcome.SUCCESS) + { + return "success"; + } + else if (outcome == Outcome.FAILURE) + { + return "failure"; + } + return null; + } + + /** + * Set the notice header. + * + * This must be an i18n dictionary key * @param header the header. - */ - public void setHeader(Message header) - { - this.header = header; - } - - /** - * Return the notice header. + */ + public void setHeader(Message header) + { + this.header = header; + } + + /** + * Return the notice header. * @return the header. - */ - public String getHeader() - { - if (this.header != null) + */ + public String getHeader() + { + if (this.header != null) { return this.header.getKey(); } - return null; - } - - /** - * Set the notice message. - * - * This must be an i18n dictionary key. + return null; + } + + /** + * Set the notice message. + * + * This must be an i18n dictionary key. * @param message the message. - */ - public void setMessage(Message message) - { - this.message = message; - } - - /** - * return the notice message. + */ + public void setMessage(Message message) + { + this.message = message; + } + + /** + * return the notice message. * @return the notice. - */ - public String getMessage() - { - if (this.message != null) + */ + public String getMessage() + { + if (this.message != null) { return this.message.getKey(); } - return null; - } - - /** - * Set the notice characters. + return null; + } + + /** + * Set the notice characters. * @param characters the notice. - */ - public void setCharacters(String characters) - { - this.characters = characters; - } - - /** - * Return the notice characters + */ + public void setCharacters(String characters) + { + this.characters = characters; + } + + /** + * Return the notice characters * @return the notice. - */ - public String getCharacters() - { - return this.characters; - } - - /** - * Set the results errors, note this will remove any previous errors. - * - * @param errors New error list. - */ - public void setErrors(List errors) - { - this.errors = errors; - } - - /** - * Add a new single error to the error list. - * - * @param newError New error. - */ - public void addError(String newError) - { - if (this.errors == null) + */ + public String getCharacters() + { + return this.characters; + } + + /** + * Set the results errors, note this will remove any previous errors. + * + * @param errors New error list. + */ + public void setErrors(List errors) + { + this.errors = errors; + } + + /** + * Add a new single error to the error list. + * + * @param newError New error. + */ + public void addError(String newError) + { + if (this.errors == null) { this.errors = new ArrayList<>(); } - - this.errors.add(newError); - } - - /** - * Return the current list of errors. + + this.errors.add(newError); + } + + /** + * Return the current list of errors. * @return a list of errors. - */ - public List getErrors() - { - return this.errors; - } - - /** - * Return the list of errors in string form, i.e. a comma-separated list - * of errors. If there are no errors then null is returned. + */ + public List getErrors() + { + return this.errors; + } + + /** + * Return the list of errors in string form, i.e. a comma-separated list + * of errors. If there are no errors then null is returned. * @return a list of errors. - */ - public String getErrorString() - { - if (errors == null || errors.isEmpty()) + */ + public String getErrorString() + { + if (errors == null || errors.isEmpty()) { return null; } - - String errorString = null; - for (String error : errors) - { - if (errorString == null) + + String errorString = null; + for (String error : errors) + { + if (errorString == null) { errorString = error; } - else + else { errorString += "," + error; } - } - return errorString; - } - - - /** - * Attach a new parameter to this result object with the specified - * name and value. - * - * @param name The parameter's name - * @param value The parameter's value. - */ - public void setParameter(String name, Object value) - { - if (this.parameters == null) + } + return errorString; + } + + + /** + * Attach a new parameter to this result object with the specified + * name and value. + * + * @param name The parameter's name + * @param value The parameter's value. + */ + public void setParameter(String name, Object value) + { + if (this.parameters == null) { this.parameters = new HashMap<>(); } - - this.parameters.put(name, value); - } - - /** - * Find the attached parameter with the given name. If no parameter is - * found for the specified name then null is returned. - * - * @param name The parameter's name. - * @return The parameter's value. - */ - public Object getParameter(String name) - { - if (this.parameters == null) + + this.parameters.put(name, value); + } + + /** + * Find the attached parameter with the given name. If no parameter is + * found for the specified name then null is returned. + * + * @param name The parameter's name. + * @return The parameter's value. + */ + public Object getParameter(String name) + { + if (this.parameters == null) { return null; } - - return this.parameters.get(name); - } + + return this.parameters.get(name); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ItemExport.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ItemExport.java index 2f2ad9f820..87f77172a6 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ItemExport.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/ItemExport.java @@ -49,272 +49,321 @@ import org.dspace.eperson.service.GroupService; import org.xml.sax.SAXException; /** - * + * * Create the ability to view currently available export archives for download. - * + * * @author Jay Paz */ public class ItemExport extends AbstractDSpaceTransformer implements - CacheableProcessingComponent { - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + CacheableProcessingComponent { + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_main_head = message("xmlui.administrative.ItemExport.head"); + private static final Message T_main_head = message("xmlui.administrative.ItemExport.head"); - private static final Message T_export_bad_item_id = message("xmlui.administrative.ItemExport.item.id.error"); + private static final Message T_export_bad_item_id = message("xmlui.administrative.ItemExport.item.id.error"); - private static final Message T_export_bad_col_id = message("xmlui.administrative.ItemExport.collection.id.error"); + private static final Message T_export_bad_col_id = message("xmlui.administrative.ItemExport.collection.id.error"); - private static final Message T_export_bad_community_id = message("xmlui.administrative.ItemExport.community.id.error"); + private static final Message T_export_bad_community_id = message("xmlui.administrative.ItemExport.community.id.error"); - private static final Message T_export_item_not_found = message("xmlui.administrative.ItemExport.item.not.found"); + private static final Message T_export_item_not_found = message("xmlui.administrative.ItemExport.item.not.found"); - private static final Message T_export_col_not_found = message("xmlui.administrative.ItemExport.collection.not.found"); + private static final Message T_export_col_not_found = message("xmlui.administrative.ItemExport.collection.not.found"); - private static final Message T_export_community_not_found = message("xmlui.administrative.ItemExport.community.not.found"); + private static final Message T_export_community_not_found = message("xmlui.administrative.ItemExport.community.not.found"); - private static final Message T_item_export_success = message("xmlui.administrative.ItemExport.item.success"); + private static final Message T_item_export_success = message("xmlui.administrative.ItemExport.item.success"); - private static final Message T_col_export_success = message("xmlui.administrative.ItemExport.collection.success"); + private static final Message T_col_export_success = message("xmlui.administrative.ItemExport.collection.success"); - private static final Message T_community_export_success = message("xmlui.administrative.ItemExport.community.success"); + private static final Message T_community_export_success = message("xmlui.administrative.ItemExport.community.success"); - private static final Message T_avail_head = message("xmlui.administrative.ItemExport.available.head"); + private static final Message T_avail_head = message("xmlui.administrative.ItemExport.available.head"); - /** The Cocoon request */ - Request request; + /** The Cocoon request */ + Request request; - /** The Cocoon response */ - Response response; + /** The Cocoon response */ + Response response; - java.util.List errors; + java.util.List errors; - java.util.List availableExports; + java.util.List availableExports; - Message message; + Message message; - /** Cached validity object */ - private SourceValidity validity; + /** Cached validity object */ + private SourceValidity validity; - protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - protected ItemExportService itemExportService = ItemExportServiceFactory.getInstance().getItemExportService(); + protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + protected ItemExportService itemExportService = ItemExportServiceFactory.getInstance().getItemExportService(); - protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - @Override - public void setup(SourceResolver resolver, Map objectModel, String src, - Parameters parameters) throws ProcessingException, SAXException, - IOException { - super.setup(resolver, objectModel, src, parameters); - this.objectModel = objectModel; - this.request = ObjectModelHelper.getRequest(objectModel); - this.response = ObjectModelHelper.getResponse(objectModel); + @Override + public void setup(SourceResolver resolver, Map objectModel, String src, + Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver, objectModel, src, parameters); + this.objectModel = objectModel; + this.request = ObjectModelHelper.getRequest(objectModel); + this.response = ObjectModelHelper.getResponse(objectModel); - errors = new ArrayList(); - if (request.getParameter("itemID") != null) { - Item item = null; - try { - item = itemService.find(context, UUID.fromString(request - .getParameter("itemID"))); - } catch (Exception e) { - errors.add(T_export_bad_item_id); - } + errors = new ArrayList(); + if (request.getParameter("itemID") != null) + { + Item item = null; + try + { + item = itemService.find(context, UUID.fromString( + request.getParameter("itemID"))); + } + catch (Exception e) + { + errors.add(T_export_bad_item_id); + } - if (item == null) { - errors.add(T_export_item_not_found); - } else { - try { - itemExportService - .createDownloadableExport(item, context, false); - } catch (Exception e) { - errors.add(message(e.getMessage())); - } - } - if (errors.size() <= 0) + if (item == null) + { + errors.add(T_export_item_not_found); + } + else + { + try + { + itemExportService + .createDownloadableExport(item, context, false); + } + catch (Exception e) + { + errors.add(message(e.getMessage())); + } + } + if (errors.size() <= 0) { message = T_item_export_success; } - } else if (request.getParameter("collectionID") != null) { - Collection col = null; - try { - col = collectionService.find(context, UUID.fromString(request - .getParameter("collectionID"))); - } catch (Exception e) { - errors.add(T_export_bad_col_id); - } + } + else if (request.getParameter("collectionID") != null) + { + Collection col = null; + try + { + col = collectionService.find(context, UUID.fromString(request + .getParameter("collectionID"))); + } + catch (Exception e) + { + errors.add(T_export_bad_col_id); + } - if (col == null) { - errors.add(T_export_col_not_found); - } else { - try { - itemExportService - .createDownloadableExport(col, context, false); - } catch (Exception e) { - errors.add(message(e.getMessage())); - } - } - if (errors.size() <= 0) + if (col == null) + { + errors.add(T_export_col_not_found); + } + else + { + try + { + itemExportService + .createDownloadableExport(col, context, false); + } + catch (Exception e) + { + errors.add(message(e.getMessage())); + } + } + if (errors.size() <= 0) { message = T_col_export_success; } - } else if (request.getParameter("communityID") != null) { - Community com = null; - try { - com = communityService.find(context, UUID.fromString(request - .getParameter("communityID"))); - } catch (Exception e) { - errors.add(T_export_bad_community_id); - } + } else if (request.getParameter("communityID") != null) { + Community com = null; + try { + com = communityService.find(context, UUID.fromString(request + .getParameter("communityID"))); + } catch (Exception e) { + errors.add(T_export_bad_community_id); + } - if (com == null) { - errors.add(T_export_community_not_found); - } else { - try { - itemExportService - .createDownloadableExport(com, context, false); - } catch (Exception e) { - errors.add(message(e.getMessage())); - } - } - if (errors.size() <= 0) + if (com == null) + { + errors.add(T_export_community_not_found); + } + else + { + try + { + itemExportService + .createDownloadableExport(com, context, false); + } catch (Exception e) { + errors.add(message(e.getMessage())); + } + } + if (errors.size() <= 0) { message = T_community_export_success; } - } - - try { - availableExports = itemExportService - .getExportsAvailable(context.getCurrentUser()); - } catch (Exception e) { - // nothing to do - } - } + } - /** - * Generate the unique cache key. - * - * @return The generated key hashes the src - */ - public Serializable getKey() { - Request request = ObjectModelHelper.getRequest(objectModel); + try + { + availableExports = itemExportService + .getExportsAvailable(context.getCurrentUser()); + } + catch (Exception e) + { + // nothing to do + } + } - // Special case, don't cache anything if the user is logging - // in. The problem occures because of timming, this cache key - // is generated before we know whether the operation has - // succeeded or failed. So we don't know whether to cache this - // under the user's specific cache or under the anonymous user. - if (request.getParameter("login_email") != null - || request.getParameter("login_password") != null - || request.getParameter("login_realm") != null) { - return "0"; - } + /** + * Generate the unique cache key. + * + * @return The generated key hashes the src + */ + public Serializable getKey() { + Request request = ObjectModelHelper.getRequest(objectModel); - StringBuilder key = new StringBuilder(); - if (context.getCurrentUser() != null) { - key.append(context.getCurrentUser().getEmail()); - if (availableExports != null && availableExports.size() > 0) { - for (String fileName : availableExports) { - key.append(":").append(fileName); - } - } + // Special case, don't cache anything if the user is logging + // in. The problem occures because of timming, this cache key + // is generated before we know whether the operation has + // succeeded or failed. So we don't know whether to cache this + // under the user's specific cache or under the anonymous user. + if (request.getParameter("login_email") != null || + request.getParameter("login_password") != null || + request.getParameter("login_realm") != null) + { + return "0"; + } - if (request.getQueryString() != null) { - key.append(request.getQueryString()); - } - } + StringBuilder key = new StringBuilder(); + if (context.getCurrentUser() != null) + { + key.append(context.getCurrentUser().getEmail()); + if (availableExports != null && availableExports.size() > 0) + { + for (String fileName : availableExports) + { + key.append(":").append(fileName); + } + } + + if (request.getQueryString() != null) + { + key.append(request.getQueryString()); + } + } else { key.append("anonymous"); } - return HashUtil.hash(key.toString()); - } + return HashUtil.hash(key.toString()); + } - /** - * Generate the validity object. - * - * @return The generated validity object or null if the - * component is currently not cacheable. - */ - public SourceValidity getValidity() { - if (this.validity == null) { - // Only use the DSpaceValidity object is someone is logged in. - if (context.getCurrentUser() != null) { - try { - DSpaceValidity validity = new DSpaceValidity(); + /** + * Generate the validity object. + * + * @return The generated validity object or null if the + * component is currently not cacheable. + */ + public SourceValidity getValidity() + { + if (this.validity == null) + { + // Only use the DSpaceValidity object is someone is logged in. + if (context.getCurrentUser() != null) + { + try + { + DSpaceValidity validity = new DSpaceValidity(); - validity.add(context, eperson); + validity.add(context, eperson); - java.util.List groups = groupService.allMemberGroups(context, eperson); - for (Group group : groups) { - validity.add(context, group); - } + java.util.List groups = groupService.allMemberGroups(context, eperson); + for (Group group : groups) + { + validity.add(context, group); + } - this.validity = validity.complete(); - } catch (SQLException sqle) { - // Just ignore it and return invalid. - } - } else { - this.validity = NOPValidity.SHARED_INSTANCE; - } - } - return this.validity; - } + this.validity = validity.complete(); + } + catch (SQLException sqle) + { + // Just ignore it and return invalid. + } + } + else + { + this.validity = NOPValidity.SHARED_INSTANCE; + } + } + return this.validity; + } - /** - * Add Page metadata. - */ - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException { - pageMeta.addMetadata("title").addContent(T_main_head); + /** + * Add Page metadata. + */ + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + pageMeta.addMetadata("title").addContent(T_main_head); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_main_head); - } + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_main_head); + } - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException { - Division main = body.addDivision("export_main"); - main.setHead(T_main_head); + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + Division main = body.addDivision("export_main"); + main.setHead(T_main_head); - if (message != null) { - main.addDivision("success", "success").addPara(message); - } + if (message != null) + { + main.addDivision("success", "success").addPara(message); + } - if (errors.size() > 0) { - Division errors = main.addDivision("export-errors", "error"); - for (Message error : this.errors) { - errors.addPara(error); - } - } + if (errors.size() > 0) + { + Division errors = main.addDivision("export-errors", "error"); + for (Message error : this.errors) + { + errors.addPara(error); + } + } - if (availableExports != null && availableExports.size() > 0) { - Division avail = main.addDivision("available-exports", - "available-exports"); - avail.setHead(T_avail_head); + if (availableExports != null && availableExports.size() > 0) + { + Division avail = main.addDivision("available-exports", + "available-exports"); + avail.setHead(T_avail_head); - List fileList = avail.addList("available-files", List.TYPE_ORDERED); - for (String fileName : availableExports) { - fileList.addItem().addXref( - this.contextPath + "/exportdownload/" + fileName, - fileName); - } - } - } - - /** - * recycle - */ - public void recycle() { - this.validity = null; - this.errors = null; - this.message = null; - this.availableExports = null; - this.response = null; - this.request = null; - super.recycle(); - } + List fileList = avail.addList("available-files", List.TYPE_ORDERED); + for (String fileName : availableExports) + { + fileList.addItem().addXref( + this.contextPath + "/exportdownload/" + fileName, fileName); + } + } + } + /** + * recycle + */ + public void recycle() { + this.validity = null; + this.errors = null; + this.message = null; + this.availableExports = null; + this.response = null; + this.request = null; + super.recycle(); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/Navigation.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/Navigation.java index f7f266cfd8..492623bcc6 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/Navigation.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/Navigation.java @@ -49,10 +49,10 @@ import org.dspace.eperson.service.GroupService; import org.xml.sax.SAXException; /** - * - * Create the navigation options for everything in the administrative aspects. This includes + * + * Create the navigation options for everything in the administrative aspects. This includes * Epeople, group, item, access control, and registry management. - * + * * @author Scott Phillips * @author Afonso Araujo Neto (internationalization) * @author Alexey Maslov @@ -60,68 +60,68 @@ import org.xml.sax.SAXException; */ public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent { - private static final Message T_context_head = message("xmlui.administrative.Navigation.context_head"); - private static final Message T_context_edit_item = message("xmlui.administrative.Navigation.context_edit_item"); - private static final Message T_context_edit_collection = message("xmlui.administrative.Navigation.context_edit_collection"); - private static final Message T_context_item_mapper = message("xmlui.administrative.Navigation.context_item_mapper"); - private static final Message T_context_edit_community = message("xmlui.administrative.Navigation.context_edit_community"); - private static final Message T_context_create_collection = message("xmlui.administrative.Navigation.context_create_collection"); - private static final Message T_context_create_subcommunity = message("xmlui.administrative.Navigation.context_create_subcommunity"); - private static final Message T_context_create_community = message("xmlui.administrative.Navigation.context_create_community"); - private static final Message T_context_export_metadata = message("xmlui.administrative.Navigation.context_export_metadata"); - private static final Message T_administrative_batch_import = message("xmlui.administrative.Navigation.administrative_batch_import"); - private static final Message T_administrative_import_metadata = message("xmlui.administrative.Navigation.administrative_import_metadata"); - private static final Message T_administrative_head = message("xmlui.administrative.Navigation.administrative_head"); - private static final Message T_administrative_access_control = message("xmlui.administrative.Navigation.administrative_access_control"); - private static final Message T_administrative_people = message("xmlui.administrative.Navigation.administrative_people"); - private static final Message T_administrative_groups = message("xmlui.administrative.Navigation.administrative_groups"); - private static final Message T_administrative_authorizations = message("xmlui.administrative.Navigation.administrative_authorizations"); - private static final Message T_administrative_registries = message("xmlui.administrative.Navigation.administrative_registries"); - private static final Message T_administrative_metadata = message("xmlui.administrative.Navigation.administrative_metadata"); - private static final Message T_administrative_format = message("xmlui.administrative.Navigation.administrative_format"); - private static final Message T_administrative_content = message("xmlui.administrative.Navigation.administrative_content"); - private static final Message T_administrative_items = message("xmlui.administrative.Navigation.administrative_items"); - private static final Message T_administrative_withdrawn = message("xmlui.administrative.Navigation.administrative_withdrawn"); - private static final Message T_administrative_private = message("xmlui.administrative.Navigation.administrative_private"); - private static final Message T_administrative_control_panel = message("xmlui.administrative.Navigation.administrative_control_panel"); - private static final Message T_administrative_curation = message("xmlui.administrative.Navigation.administrative_curation"); - - private static final Message T_statistics = message("xmlui.administrative.Navigation.statistics"); + private static final Message T_context_head = message("xmlui.administrative.Navigation.context_head"); + private static final Message T_context_edit_item = message("xmlui.administrative.Navigation.context_edit_item"); + private static final Message T_context_edit_collection = message("xmlui.administrative.Navigation.context_edit_collection"); + private static final Message T_context_item_mapper = message("xmlui.administrative.Navigation.context_item_mapper"); + private static final Message T_context_edit_community = message("xmlui.administrative.Navigation.context_edit_community"); + private static final Message T_context_create_collection = message("xmlui.administrative.Navigation.context_create_collection"); + private static final Message T_context_create_subcommunity = message("xmlui.administrative.Navigation.context_create_subcommunity"); + private static final Message T_context_create_community = message("xmlui.administrative.Navigation.context_create_community"); + private static final Message T_context_export_metadata = message("xmlui.administrative.Navigation.context_export_metadata"); + private static final Message T_administrative_batch_import = message("xmlui.administrative.Navigation.administrative_batch_import"); + private static final Message T_administrative_import_metadata = message("xmlui.administrative.Navigation.administrative_import_metadata"); + private static final Message T_administrative_head = message("xmlui.administrative.Navigation.administrative_head"); + private static final Message T_administrative_access_control = message("xmlui.administrative.Navigation.administrative_access_control"); + private static final Message T_administrative_people = message("xmlui.administrative.Navigation.administrative_people"); + private static final Message T_administrative_groups = message("xmlui.administrative.Navigation.administrative_groups"); + private static final Message T_administrative_authorizations = message("xmlui.administrative.Navigation.administrative_authorizations"); + private static final Message T_administrative_registries = message("xmlui.administrative.Navigation.administrative_registries"); + private static final Message T_administrative_metadata = message("xmlui.administrative.Navigation.administrative_metadata"); + private static final Message T_administrative_format = message("xmlui.administrative.Navigation.administrative_format"); + private static final Message T_administrative_content = message("xmlui.administrative.Navigation.administrative_content"); + private static final Message T_administrative_items = message("xmlui.administrative.Navigation.administrative_items"); + private static final Message T_administrative_withdrawn = message("xmlui.administrative.Navigation.administrative_withdrawn"); + private static final Message T_administrative_private = message("xmlui.administrative.Navigation.administrative_private"); + private static final Message T_administrative_control_panel = message("xmlui.administrative.Navigation.administrative_control_panel"); + private static final Message T_administrative_curation = message("xmlui.administrative.Navigation.administrative_curation"); - private static final Message T_context_export_item = message("xmlui.administrative.Navigation.context_export_item"); - private static final Message T_context_export_collection = message("xmlui.administrative.Navigation.context_export_collection"); - private static final Message T_context_export_community = message("xmlui.administrative.Navigation.context_export_community"); - private static final Message T_account_export = message("xmlui.administrative.Navigation.account_export"); + private static final Message T_statistics = message("xmlui.administrative.Navigation.statistics"); - private static final Message T_my_account = message("xmlui.EPerson.Navigation.my_account"); + private static final Message T_context_export_item = message("xmlui.administrative.Navigation.context_export_item"); + private static final Message T_context_export_collection = message("xmlui.administrative.Navigation.context_export_collection"); + private static final Message T_context_export_community = message("xmlui.administrative.Navigation.context_export_community"); + private static final Message T_account_export = message("xmlui.administrative.Navigation.account_export"); + + private static final Message T_my_account = message("xmlui.EPerson.Navigation.my_account"); /** Cached validity object */ - private SourceValidity validity; - - /** exports available for download */ - java.util.List availableExports = null; + private SourceValidity validity; + + /** exports available for download */ + java.util.List availableExports = null; protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - + protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); protected ItemExportService itemExportService = ItemExportServiceFactory.getInstance().getItemExportService(); - /** + /** * Generate the unique cache key. * * @return The generated key hashes the src */ - public Serializable getKey() + public Serializable getKey() { Request request = ObjectModelHelper.getRequest(objectModel); - - // Special case, don't cache anything if the user is logging + + // Special case, don't cache anything if the user is logging // in. The problem occures because of timming, this cache key - // is generated before we know whether the operation has - // succeeded or failed. So we don't know whether to cache this + // is generated before we know whether the operation has + // succeeded or failed. So we don't know whether to cache this // under the user's specific cache or under the anonymous user. if (request.getParameter("login_email") != null || request.getParameter("login_password") != null || @@ -135,7 +135,8 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr return HashUtil.hash("anonymous"); } - if (availableExports != null && availableExports.size()>0) { + if (availableExports != null && availableExports.size()>0) + { StringBuilder key = new StringBuilder(context.getCurrentUser().getEmail()); for(String fileName : availableExports){ key.append(":").append(fileName); @@ -146,49 +147,51 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr return HashUtil.hash(context.getCurrentUser().getEmail()); } - + /** * Generate the validity object. * * @return The generated validity object or null if the * component is currently not cacheable. */ - public SourceValidity getValidity() + public SourceValidity getValidity() { - if (this.validity == null) - { - // Only use the DSpaceValidity object is someone is logged in. - if (context.getCurrentUser() != null) - { - try { - DSpaceValidity validity = new DSpaceValidity(); - - validity.add(context, eperson); - - java.util.List groups = groupService.allMemberGroups(context, eperson); - for (Group group : groups) - { - validity.add(context, group); - } - - this.validity = validity.complete(); - } - catch (SQLException sqle) - { - // Just ignore it and return invalid. - } - } - else - { - this.validity = NOPValidity.SHARED_INSTANCE; - } - } - return this.validity; + if (this.validity == null) + { + // Only use the DSpaceValidity object is someone is logged in. + if (context.getCurrentUser() != null) + { + try { + DSpaceValidity validity = new DSpaceValidity(); + + validity.add(context, eperson); + + java.util.List groups = groupService.allMemberGroups(context, eperson); + for (Group group : groups) + { + validity.add(context, group); + } + + this.validity = validity.complete(); + } + catch (SQLException sqle) + { + // Just ignore it and return invalid. + } + } + else + { + this.validity = NOPValidity.SHARED_INSTANCE; + } + } + return this.validity; } - - - public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) throws ProcessingException, SAXException, IOException { - super.setup(resolver, objectModel, src, parameters); + + + public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver, objectModel, src, parameters); availableExports = null; if (context.getCurrentUser() != null) { @@ -202,24 +205,24 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr } } } - - - - - public void addOptions(Options options) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + + + public void addOptions(Options options) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - /* Create skeleton menu structure to ensure consistent order between aspects, - * even if they are never used - */ + /* Create skeleton menu structure to ensure consistent order between aspects, + * even if they are never used + */ options.addList("browse"); List account = options.addList("account"); List context = options.addList("context"); List admin = options.addList("administrative"); - account.setHead(T_my_account); - + account.setHead(T_my_account); + // My Account options - if(availableExports!=null && availableExports.size()>0){ + if (availableExports!=null && availableExports.size()>0) + { account.addItem().addXref(contextPath+"/admin/export", T_account_export); } @@ -228,70 +231,70 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr // Context Administrative options DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - if (dso instanceof Item) - { - Item item = (Item) dso; - if (itemService.canEdit(this.context, item)) - { - context.setHead(T_context_head); - context.addItem().addXref(contextPath+"/admin/item?itemID="+item.getID(), T_context_edit_item); - if (authorizeService.isAdmin(this.context, dso)) - { - context.addItem().addXref(contextPath+"/admin/export?itemID="+item.getID(), T_context_export_item ); - context.addItem().addXref(contextPath+ "/csv/handle/"+dso.getHandle(),T_context_export_metadata ); - } + if (dso instanceof Item) + { + Item item = (Item) dso; + if (itemService.canEdit(this.context, item)) + { + context.setHead(T_context_head); + context.addItem().addXref(contextPath+"/admin/item?itemID="+item.getID(), T_context_edit_item); + if (authorizeService.isAdmin(this.context, dso)) + { + context.addItem().addXref(contextPath+"/admin/export?itemID="+item.getID(), T_context_export_item ); + context.addItem().addXref(contextPath+ "/csv/handle/"+dso.getHandle(),T_context_export_metadata ); } - } - else if (dso instanceof Collection) - { - Collection collection = (Collection) dso; - - // can they admin this collection? + } + } + else if (dso instanceof Collection) + { + Collection collection = (Collection) dso; + + // can they admin this collection? if (collectionService.canEditBoolean(this.context, collection, true)) { - context.setHead(T_context_head); - context.addItemXref(contextPath+"/admin/collection?collectionID=" + collection.getID(), T_context_edit_collection); - context.addItemXref(contextPath+"/admin/mapper?collectionID="+collection.getID(), T_context_item_mapper); - if (authorizeService.isAdmin(this.context, dso)) + context.setHead(T_context_head); + context.addItemXref(contextPath+"/admin/collection?collectionID=" + collection.getID(), T_context_edit_collection); + context.addItemXref(contextPath+"/admin/mapper?collectionID="+collection.getID(), T_context_item_mapper); + if (authorizeService.isAdmin(this.context, dso)) { context.addItem().addXref(contextPath+"/admin/export?collectionID="+collection.getID(), T_context_export_collection ); context.addItem().addXref(contextPath+ "/csv/handle/"+dso.getHandle(),T_context_export_metadata ); } } - } - else if (dso instanceof Community) - { - Community community = (Community) dso; - - // can they admin this collection? + } + else if (dso instanceof Community) + { + Community community = (Community) dso; + + // can they admin this collection? if (communityService.canEditBoolean(this.context, community)) { - context.setHead(T_context_head); - context.addItemXref(contextPath+"/admin/community?communityID=" + community.getID(), T_context_edit_community); - if (authorizeService.isAdmin(this.context, dso)) + context.setHead(T_context_head); + context.addItemXref(contextPath+"/admin/community?communityID=" + community.getID(), T_context_edit_community); + if (authorizeService.isAdmin(this.context, dso)) { context.addItem().addXref(contextPath + "/admin/export?communityID=" + community.getID(), T_context_export_community); } context.addItem().addXref(contextPath+ "/csv/handle/"+dso.getHandle(),T_context_export_metadata ); } - + // can they add to this community? if (authorizeService.authorizeActionBoolean(this.context, community, Constants.ADD)) { - context.setHead(T_context_head); - context.addItemXref(contextPath+"/admin/collection?createNew&communityID=" + community.getID(), T_context_create_collection); - context.addItemXref(contextPath+"/admin/community?createNew&communityID=" + community.getID(), T_context_create_subcommunity); + context.setHead(T_context_head); + context.addItemXref(contextPath+"/admin/collection?createNew&communityID=" + community.getID(), T_context_create_collection); + context.addItemXref(contextPath+"/admin/community?createNew&communityID=" + community.getID(), T_context_create_subcommunity); } - } - - if (isSystemAdmin && ("community-list".equals(this.sitemapURI) || "".equals(this.sitemapURI))) - { + } + + if (isSystemAdmin && ("community-list".equals(this.sitemapURI) || "".equals(this.sitemapURI))) + { // Only System administrators can create top-level communities context.setHead(T_context_head); context.addItemXref(contextPath+"/admin/community?createNew", T_context_create_community); - } - - + } + + // System Administrator options! if (isSystemAdmin) { @@ -326,67 +329,68 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr admin.addItemXref(contextPath+ "/admin/curate", T_administrative_curation); } } - - - public int addContextualOptions(List context) throws SQLException, WingException + + + public int addContextualOptions(List context) + throws SQLException, WingException { - // How many options were added. - int options = 0; - - DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - - if (dso instanceof Item) - { - Item item = (Item) dso; - if (itemService.canEdit(this.context, item)) - { - context.addItem().addXref(contextPath+"/admin/item?itemID="+item.getID(), T_context_edit_item); - options++; - } - } - else if (dso instanceof Collection) - { - Collection collection = (Collection) dso; - - - // can they admin this collection? + // How many options were added. + int options = 0; + + DSpaceObject dso = HandleUtil.obtainHandle(objectModel); + + if (dso instanceof Item) + { + Item item = (Item) dso; + if (itemService.canEdit(this.context, item)) + { + context.addItem().addXref(contextPath+"/admin/item?itemID="+item.getID(), T_context_edit_item); + options++; + } + } + else if (dso instanceof Collection) + { + Collection collection = (Collection) dso; + + + // can they admin this collection? if (authorizeService.authorizeActionBoolean(this.context, collection, Constants.ADMIN)) - { - context.addItemXref(contextPath+"/admin/collection?collectionID=" + collection.getID(), T_context_edit_collection); - context.addItemXref(contextPath+"/admin/mapper?collectionID="+collection.getID(), T_context_item_mapper); - options++; + { + context.addItemXref(contextPath+"/admin/collection?collectionID=" + collection.getID(), T_context_edit_collection); + context.addItemXref(contextPath+"/admin/mapper?collectionID="+collection.getID(), T_context_item_mapper); + options++; } - } - else if (dso instanceof Community) - { - Community community = (Community) dso; - - // can they admin this collection? + } + else if (dso instanceof Community) + { + Community community = (Community) dso; + + // can they admin this collection? if (communityService.canEditBoolean(this.context, community)) - { - context.addItemXref(contextPath+"/admin/community?communityID=" + community.getID(), T_context_edit_community); - options++; + { + context.addItemXref(contextPath+"/admin/community?communityID=" + community.getID(), T_context_edit_community); + options++; } - + // can they add to this community? if (authorizeService.authorizeActionBoolean(this.context, community, Constants.ADD)) - { - context.addItemXref(contextPath+"/admin/collection?createNew&communityID=" + community.getID(), T_context_create_collection); - context.addItemXref(contextPath+"/admin/community?createNew&communityID=" + community.getID(), T_context_create_subcommunity); - options++; + { + context.addItemXref(contextPath+"/admin/collection?createNew&communityID=" + community.getID(), T_context_create_collection); + context.addItemXref(contextPath+"/admin/community?createNew&communityID=" + community.getID(), T_context_create_subcommunity); + options++; } - } - - if (("community-list".equals(this.sitemapURI) || "".equals(this.sitemapURI)) && authorizeService.isAdmin(this.context)) - { + } + + if (("community-list".equals(this.sitemapURI) || "".equals(this.sitemapURI)) && authorizeService.isAdmin(this.context)) + { context.addItemXref(contextPath+"/admin/community?createNew", T_context_create_community); options++; - } - - return options; + } + + return options; } - - + + /** * recycle */ @@ -396,5 +400,4 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr this.availableExports = null; super.recycle(); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/NotAuthorized.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/NotAuthorized.java index fbd506436a..fdde40aafd 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/NotAuthorized.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/NotAuthorized.java @@ -20,58 +20,59 @@ import org.dspace.app.xmlui.wing.element.Para; /** * Display a generic error message saying the user can * not perform the requested action. - * + * * @author Scott Phillips */ -public class NotAuthorized extends AbstractDSpaceTransformer -{ - - private static final Message T_title = - message("xmlui.administrative.NotAuthorized.title"); - - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); +public class NotAuthorized extends AbstractDSpaceTransformer +{ - private static final Message T_trail = - message("xmlui.administrative.NotAuthorized.trail"); - - private static final Message T_head = - message("xmlui.administrative.NotAuthorized.head"); - - private static final Message T_para1a = - message("xmlui.administrative.NotAuthorized.para1a"); + private static final Message T_title = + message("xmlui.administrative.NotAuthorized.title"); - private static final Message T_para1b = - message("xmlui.administrative.NotAuthorized.para1b"); - - private static final Message T_para1c = - message("xmlui.administrative.NotAuthorized.para1c"); - - private static final Message T_para2 = - message("xmlui.administrative.NotAuthorized.para2"); - - - public void addPageMeta(PageMeta pageMeta) throws WingException + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + + private static final Message T_trail = + message("xmlui.administrative.NotAuthorized.trail"); + + private static final Message T_head = + message("xmlui.administrative.NotAuthorized.head"); + + private static final Message T_para1a = + message("xmlui.administrative.NotAuthorized.para1a"); + + private static final Message T_para1b = + message("xmlui.administrative.NotAuthorized.para1b"); + + private static final Message T_para1c = + message("xmlui.administrative.NotAuthorized.para1c"); + + private static final Message T_para2 = + message("xmlui.administrative.NotAuthorized.para2"); + + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_trail); } - - public void addBody(Body body) throws WingException, SQLException - { - String loginURL = contextPath+"/login"; - String feedbackURL = contextPath+"/feedback"; - - Division main = body.addDivision("not-authorized","primary administrative"); - main.setHead(T_head); - Para para1 = main.addPara(); - para1.addContent(T_para1a); - para1.addXref(feedbackURL,T_para1b); - para1.addContent(T_para1c); - main.addPara().addXref(loginURL,T_para2); - - } - + public void addBody(Body body) + throws WingException, SQLException + { + String loginURL = contextPath+"/login"; + String feedbackURL = contextPath+"/feedback"; + + Division main = body.addDivision("not-authorized", + "primary administrative"); + main.setHead(T_head); + Para para1 = main.addPara(); + para1.addContent(T_para1a); + para1.addXref(feedbackURL,T_para1b); + para1.addContent(T_para1c); + + main.addPara().addXref(loginURL,T_para2); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/PrivateItems.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/PrivateItems.java index 334a5baca5..2957060b8c 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/PrivateItems.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/PrivateItems.java @@ -547,7 +547,9 @@ public class PrivateItems extends AbstractDSpaceTransformer implements * * @return * @throws SQLException + * An exception that provides information on a database access error or other errors. * @throws UIException + * Error generated by XMLUI. */ private BrowseParams getUserParams() throws SQLException, UIException { @@ -674,7 +676,9 @@ public class PrivateItems extends AbstractDSpaceTransformer implements * * @return * @throws SQLException + * An exception that provides information on a database access error or other errors. * @throws UIException + * Error generated by XMLUI. */ private BrowseInfo getBrowseInfo() throws SQLException, UIException { @@ -781,4 +785,4 @@ public class PrivateItems extends AbstractDSpaceTransformer implements return trailMessage; } -} \ No newline at end of file +} diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/SystemwideAlerts.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/SystemwideAlerts.java index b6b904f7d5..8a843e04fd 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/SystemwideAlerts.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/SystemwideAlerts.java @@ -21,47 +21,47 @@ import org.dspace.app.xmlui.wing.element.PageMeta; /** * This class maintains any system-wide alerts. If any alerts are activated then * they are added to the page's metadata for display by the theme. - * + * * This class also creates an interface for the alert system to be maintained. - * + * * @author Scott Phillips */ public class SystemwideAlerts extends AbstractDSpaceTransformer implements CacheableProcessingComponent { - /** Language Strings */ - private static final Message T_COUNTDOWN = message("xmlui.administrative.SystemwideAlerts.countdown"); + /** Language Strings */ + private static final Message T_COUNTDOWN = message("xmlui.administrative.SystemwideAlerts.countdown"); - /** Possible user restricted states */ - public static final int STATE_ALL_SESSIONS = 1; - public static final int STATE_CURRENT_SESSIONS = 2; - public static final int STATE_ONLY_ADMINISTRATIVE_SESSIONS = 3; - - - // Is an alert activated? - private static boolean active; - - // The alert's message - private static String message; - - // If a count down time is present, what time are we counting down too? - private static long countDownToo; - - // Can users use the website? - private static int restrictsessions = STATE_ALL_SESSIONS; - - /** + /** Possible user restricted states */ + public static final int STATE_ALL_SESSIONS = 1; + public static final int STATE_CURRENT_SESSIONS = 2; + public static final int STATE_ONLY_ADMINISTRATIVE_SESSIONS = 3; + + + // Is an alert activated? + private static boolean active; + + // The alert's message + private static String message; + + // If a count down time is present, what time are we counting down too? + private static long countDownToo; + + // Can users use the website? + private static int restrictsessions = STATE_ALL_SESSIONS; + + /** * Generate the unique caching key. * @return the key. */ @Override public Serializable getKey() { - if (active) + if (active) { // Don't cache any alert messages return null; } - else + else { return "1"; } @@ -74,144 +74,145 @@ public class SystemwideAlerts extends AbstractDSpaceTransformer implements Cache @Override public SourceValidity getValidity() { - if (active) + if (active) { return null; } - else + else { return NOPValidity.SHARED_INSTANCE; } } - + /** * If an alert is activated then add a count down message. * @throws org.dspace.app.xmlui.wing.WingException passed through. */ @Override - public void addPageMeta(PageMeta pageMeta) throws WingException + public void addPageMeta(PageMeta pageMeta) throws WingException { - - if (active) - { - Metadata alert = pageMeta.addMetadata("alert","message"); - - long time = countDownToo - System.currentTimeMillis(); - if (time > 0) - { - // from milliseconds to minutes - time = time / (60*1000); - - alert.addContent(T_COUNTDOWN.parameterize(time)); - } - alert.addContent(message); - } + if (active) + { + Metadata alert = pageMeta.addMetadata("alert","message"); + + long time = countDownToo - System.currentTimeMillis(); + if (time > 0) + { + // from milliseconds to minutes + time = time / (60*1000); + + alert.addContent(T_COUNTDOWN.parameterize(time)); + } + + alert.addContent(message); + } } - /** - * Check whether an alert is active. + /** + * Check whether an alert is active. * @return true if active. - */ - public static boolean isAlertActive() - { - return SystemwideAlerts.active; - } - - /** - * Activate the current alert. - */ - public static void activateAlert() - { - SystemwideAlerts.active = true; - } - - /** - * Deactivate the current alert. - */ - public static void deactivateAlert() - { - SystemwideAlerts.active = false; - } - - /** - * Set the current alert's message. - * @param message The new message - */ - public static void setMessage(String message) - { - SystemwideAlerts.message = message; - } - - /** - * @return the current alert's message - */ - public static String getMessage() - { - return SystemwideAlerts.message; - } + */ + public static boolean isAlertActive() + { + return SystemwideAlerts.active; + } - /** - * Get the time, in millieseconds, when the countdown timer is scheduled to end. + /** + * Activate the current alert. + */ + public static void activateAlert() + { + SystemwideAlerts.active = true; + } + + /** + * Deactivate the current alert. + */ + public static void deactivateAlert() + { + SystemwideAlerts.active = false; + } + + /** + * Set the current alert's message. + * @param message The new message + */ + public static void setMessage(String message) + { + SystemwideAlerts.message = message; + } + + /** + * @return the current alert's message + */ + public static String getMessage() + { + return SystemwideAlerts.message; + } + + /** + * Get the time, in millieseconds, when the countdown timer is scheduled to end. * @return countdown end time. - */ - public static long getCountDownToo() - { - return SystemwideAlerts.countDownToo; - } - - /** - * Set the time, in millieseconds, to which the countdown timer should end. - * - * Note, that once the countdown has expired, the alert is - * still active. However the countdown will disappear. - * @param countDownTo countdown end time. - */ - public static void setCountDownToo(long countDownTo) - { - SystemwideAlerts.countDownToo = countDownTo; - } + */ + public static long getCountDownToo() + { + return SystemwideAlerts.countDownToo; + } - // Can users login or continue to use the system? - public static int getRestrictSessions() - { - return SystemwideAlerts.restrictsessions; - } - - // Set the ability to restrict use of the system - public static void setRestrictSessions(int restrictsessions) - { - if (restrictsessions == STATE_ALL_SESSIONS || - restrictsessions == STATE_CURRENT_SESSIONS || - restrictsessions == STATE_ONLY_ADMINISTRATIVE_SESSIONS) + /** + * Set the time, in millieseconds, to which the countdown timer should end. + * + * Note, that once the countdown has expired, the alert is + * still active. However the countdown will disappear. + * @param countDownTo countdown end time. + */ + public static void setCountDownToo(long countDownTo) + { + SystemwideAlerts.countDownToo = countDownTo; + } + + // Can users login or continue to use the system? + public static int getRestrictSessions() + { + return SystemwideAlerts.restrictsessions; + } + + // Set the ability to restrict use of the system + public static void setRestrictSessions(int restrictsessions) + { + if (restrictsessions == STATE_ALL_SESSIONS || + restrictsessions == STATE_CURRENT_SESSIONS || + restrictsessions == STATE_ONLY_ADMINISTRATIVE_SESSIONS) { SystemwideAlerts.restrictsessions = restrictsessions; } - } - - - /** - * Are users able to start a new session, will return false if there is - * a current alert activated and sessions are restricted. - * - * @return if false do not allow user to start a new session, otherwise no restriction. - */ - public static boolean canUserStartSession() - { - return !SystemwideAlerts.active || - (restrictsessions != STATE_ONLY_ADMINISTRATIVE_SESSIONS && - restrictsessions != STATE_CURRENT_SESSIONS); } - - /** - * Are users able to maintain a session, will return false if there is - * a current alert activated and sessions are restricted. - * - * @return if false do not allow user to maintain their current session - * or start a new session, otherwise no restriction. - */ - public static boolean canUserMaintainSession() - { - return !SystemwideAlerts.active || restrictsessions != STATE_ONLY_ADMINISTRATIVE_SESSIONS; + + + /** + * Are users able to start a new session, will return false if there is + * a current alert activated and sessions are restricted. + * + * @return if false do not allow user to start a new session, otherwise no restriction. + */ + public static boolean canUserStartSession() + { + return !SystemwideAlerts.active || + (restrictsessions != STATE_ONLY_ADMINISTRATIVE_SESSIONS && + restrictsessions != STATE_CURRENT_SESSIONS); + } + + /** + * Are users able to maintain a session, will return false if there is + * a current alert activated and sessions are restricted. + + * @return if false do not allow user to maintain their current session + * or start a new session, otherwise no restriction. + */ + public static boolean canUserMaintainSession() + { + return !SystemwideAlerts.active || + restrictsessions != STATE_ONLY_ADMINISTRATIVE_SESSIONS; } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/WithdrawnItems.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/WithdrawnItems.java index 7cc530dfe7..88db2fd59e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/WithdrawnItems.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/WithdrawnItems.java @@ -546,6 +546,7 @@ public class WithdrawnItems extends AbstractDSpaceTransformer implements * * @return * @throws SQLException + * An exception that provides information on a database access error or other errors. * @throws UIException */ private BrowseParams getUserParams() throws SQLException, UIException @@ -673,7 +674,9 @@ public class WithdrawnItems extends AbstractDSpaceTransformer implements * * @return * @throws SQLException + * An exception that provides information on a database access error or other errors. * @throws UIException + * Error generated by XMLUI. */ private BrowseInfo getBrowseInfo() throws SQLException, UIException { diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/DeletePoliciesConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/DeletePoliciesConfirm.java index 0895a5d420..534c32acdc 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/DeletePoliciesConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/DeletePoliciesConfirm.java @@ -26,40 +26,41 @@ import org.dspace.authorize.service.ResourcePolicyService; /** * @author Alexey Maslov */ -public class DeletePoliciesConfirm extends AbstractDSpaceTransformer -{ - /** Language Strings */ - private static final Message T_dspace_home = +public class DeletePoliciesConfirm extends AbstractDSpaceTransformer +{ + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_title = - message("xmlui.administrative.authorization.DeletePoliciesConfirm.title"); - private static final Message T_trail = - message("xmlui.administrative.authorization.DeletePoliciesConfirm.trail"); - private static final Message T_authorize_trail = - message("xmlui.administrative.authorization.general.authorize_trail"); - private static final Message T_policyList_trail = - message("xmlui.administrative.authorization.general.policyList_trail"); - - private static final Message T_confirm_head = - message("xmlui.administrative.authorization.DeletePoliciesConfirm.confirm_head"); - private static final Message T_confirm_para = - message("xmlui.administrative.authorization.DeletePoliciesConfirm.confirm_para"); - - private static final Message T_head_id = - message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_id"); - private static final Message T_head_action = - message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_action"); - private static final Message T_head_group = - message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_group"); - - private static final Message T_submit_confirm = - message("xmlui.general.delete"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); + private static final Message T_title = + message("xmlui.administrative.authorization.DeletePoliciesConfirm.title"); + private static final Message T_trail = + message("xmlui.administrative.authorization.DeletePoliciesConfirm.trail"); + private static final Message T_authorize_trail = + message("xmlui.administrative.authorization.general.authorize_trail"); + private static final Message T_policyList_trail = + message("xmlui.administrative.authorization.general.policyList_trail"); - protected ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException + private static final Message T_confirm_head = + message("xmlui.administrative.authorization.DeletePoliciesConfirm.confirm_head"); + private static final Message T_confirm_para = + message("xmlui.administrative.authorization.DeletePoliciesConfirm.confirm_para"); + + private static final Message T_head_id = + message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_id"); + private static final Message T_head_action = + message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_action"); + private static final Message T_head_group = + message("xmlui.administrative.authorization.DeletePoliciesConfirm.head_group"); + + private static final Message T_submit_confirm = + message("xmlui.general.delete"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); + + protected ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); @@ -67,48 +68,51 @@ public class DeletePoliciesConfirm extends AbstractDSpaceTransformer pageMeta.addTrail().addContent(T_policyList_trail); pageMeta.addTrail().addContent(T_trail); } - - public void addBody(Body body) throws WingException, SQLException - { - // Get all our parameters - String idsString = parameters.getParameter("policyIDs", null); - - ArrayList policies = new ArrayList(); - for (String id : idsString.split(",")) - { - ResourcePolicy policy = resourcePolicyService.find(context,Integer.valueOf(id)); - policies.add(policy); - } - - // DIVISION: policies-confirm-delete - Division deleted = body.addInteractiveDivision("policies-confirm-delete",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization"); - deleted.setHead(T_confirm_head); - deleted.addPara(T_confirm_para); - - Table table = deleted.addTable("policies-confirm-delete",policies.size() + 1, 4); + + public void addBody(Body body) + throws WingException, SQLException + { + // Get all our parameters + String idsString = parameters.getParameter("policyIDs", null); + + ArrayList policies = new ArrayList(); + for (String id : idsString.split(",")) + { + ResourcePolicy policy = resourcePolicyService.find(context,Integer.valueOf(id)); + policies.add(policy); + } + + // DIVISION: policies-confirm-delete + Division deleted = body.addInteractiveDivision("policies-confirm-delete", + contextPath + "/admin/authorize", Division.METHOD_POST, + "primary administrative authorization"); + deleted.setHead(T_confirm_head); + deleted.addPara(T_confirm_para); + + Table table = deleted.addTable("policies-confirm-delete",policies.size() + 1, 4); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_head_id); header.addCell().addContent(T_head_action); header.addCell().addContent(T_head_group); - - for (ResourcePolicy policy : policies) - { - Row row = table.addRow(); - row.addCell().addContent(policy.getID()); - row.addCell().addContent(resourcePolicyService.getActionText(policy)); - if (policy.getGroup() != null) + + for (ResourcePolicy policy : policies) + { + Row row = table.addRow(); + row.addCell().addContent(policy.getID()); + row.addCell().addContent(resourcePolicyService.getActionText(policy)); + if (policy.getGroup() != null) { row.addCell().addContent(policy.getGroup().getName()); } - else + else { row.addCell().addContent("..."); } - } - Para buttons = deleted.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_confirm); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - deleted.addHidden("administrative-continue").setValue(knot.getId()); + } + Para buttons = deleted.addPara(); + buttons.addButton("submit_confirm").setValue(T_submit_confirm); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + deleted.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditContainerPolicies.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditContainerPolicies.java index 219eb23585..682f92b712 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditContainerPolicies.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditContainerPolicies.java @@ -38,39 +38,39 @@ import org.dspace.eperson.Group; /** * @author Alexey Maslov */ -public class EditContainerPolicies extends AbstractDSpaceTransformer -{ - private static final Message T_title = - message("xmlui.administrative.authorization.EditContainerPolicies.title"); - private static final Message T_policyList_trail = - message("xmlui.administrative.authorization.general.policyList_trail"); - private static final Message T_authorize_trail = - message("xmlui.administrative.authorization.general.authorize_trail"); - - private static final Message T_main_head_collection = - message("xmlui.administrative.authorization.EditContainerPolicies.main_head_collection"); - private static final Message T_main_head_community = - message("xmlui.administrative.authorization.EditContainerPolicies.main_head_community"); - - private static final Message T_add_link = - message("xmlui.administrative.authorization.EditContainerPolicies.main_add_link"); - - private static final Message T_head_id = - message("xmlui.administrative.authorization.EditContainerPolicies.head_id"); - private static final Message T_head_action = - message("xmlui.administrative.authorization.EditContainerPolicies.head_action"); - private static final Message T_head_group = - message("xmlui.administrative.authorization.EditContainerPolicies.head_group"); - private static final Message T_group_edit = - message("xmlui.administrative.authorization.EditContainerPolicies.group_edit"); - - private static final Message T_submit_delete = - message("xmlui.administrative.authorization.EditContainerPolicies.submit_delete"); - private static final Message T_submit_return = - message("xmlui.general.return"); - - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); +public class EditContainerPolicies extends AbstractDSpaceTransformer +{ + private static final Message T_title = + message("xmlui.administrative.authorization.EditContainerPolicies.title"); + private static final Message T_policyList_trail = + message("xmlui.administrative.authorization.general.policyList_trail"); + private static final Message T_authorize_trail = + message("xmlui.administrative.authorization.general.authorize_trail"); + + private static final Message T_main_head_collection = + message("xmlui.administrative.authorization.EditContainerPolicies.main_head_collection"); + private static final Message T_main_head_community = + message("xmlui.administrative.authorization.EditContainerPolicies.main_head_community"); + + private static final Message T_add_link = + message("xmlui.administrative.authorization.EditContainerPolicies.main_add_link"); + + private static final Message T_head_id = + message("xmlui.administrative.authorization.EditContainerPolicies.head_id"); + private static final Message T_head_action = + message("xmlui.administrative.authorization.EditContainerPolicies.head_action"); + private static final Message T_head_group = + message("xmlui.administrative.authorization.EditContainerPolicies.head_group"); + private static final Message T_group_edit = + message("xmlui.administrative.authorization.EditContainerPolicies.group_edit"); + + private static final Message T_submit_delete = + message("xmlui.administrative.authorization.EditContainerPolicies.submit_delete"); + private static final Message T_submit_return = + message("xmlui.general.return"); + + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); @@ -78,46 +78,47 @@ public class EditContainerPolicies extends AbstractDSpaceTransformer protected ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail); pageMeta.addTrail().addContent(T_policyList_trail); - + } - - public void addBody(Body body) throws WingException, SQLException - { - /* Get and setup our parameters */ + + public void addBody(Body body) + throws WingException, SQLException + { + /* Get and setup our parameters */ int containerType = parameters.getParameterAsInteger("containerType",-1); UUID containerID = UUID.fromString(parameters.getParameter("containerID", null)); int highlightID = parameters.getParameterAsInteger("highlightID",-1); String baseURL = contextPath+"/admin/epeople?administrative-continue="+knot.getId(); - + ArrayList policies; // DIVISION: edit-container-policies Division main = body.addInteractiveDivision("edit-container-policies",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization"); - - if (containerType == Constants.COLLECTION) - { - Collection col = collectionService.find(context, containerID); - main.setHead(T_main_head_collection.parameterize(collectionService.getMetadata(col, "name"),col.getHandle(),col.getID())); - policies = (ArrayList) authorizeService.getPolicies(context, col); - } - else - { - Community com = communityService.find(context, containerID); - main.setHead(T_main_head_community.parameterize(communityService.getMetadata(com, "name"), com.getHandle(), com.getID())); - policies = (ArrayList) authorizeService.getPolicies(context, com); - } - - /* Adding a new policy link */ - main.addPara().addXref(baseURL + "&submit_add", T_add_link); - - Table table = main.addTable("container-policy-list",policies.size() + 1, 4); + + if (containerType == Constants.COLLECTION) + { + Collection col = collectionService.find(context, containerID); + main.setHead(T_main_head_collection.parameterize(collectionService.getMetadata(col, "name"),col.getHandle(),col.getID())); + policies = (ArrayList) authorizeService.getPolicies(context, col); + } + else + { + Community com = communityService.find(context, containerID); + main.setHead(T_main_head_community.parameterize(communityService.getMetadata(com, "name"), com.getHandle(), com.getID())); + policies = (ArrayList) authorizeService.getPolicies(context, com); + } + + /* Adding a new policy link */ + main.addPara().addXref(baseURL + "&submit_add", T_add_link); + + Table table = main.addTable("container-policy-list",policies.size() + 1, 4); Row header = table.addRow(Row.ROLE_HEADER); header.addCell(); header.addCell().addContent(T_head_id); @@ -147,7 +148,8 @@ public class EditContainerPolicies extends AbstractDSpaceTransformer row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID(), String.valueOf(policy.getID())); row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID(), resourcePolicyService.getActionText(policy)); - if (policyGroup != null) { + if (policyGroup != null) + { Cell groupCell = row.addCell(); groupCell.addContent(policyGroup.getName()); Highlight groupHigh = groupCell.addHighlight("fade"); @@ -155,16 +157,17 @@ public class EditContainerPolicies extends AbstractDSpaceTransformer groupHigh.addXref(baseURL + "&submit_edit_group&group_id=" + policyGroup.getID(), T_group_edit); groupHigh.addContent("]"); } - else { + else + { row.addCell().addContent("..."); } } } - - Para buttons = main.addPara(); - buttons.addButton("submit_delete").setValue(T_submit_delete); - buttons.addButton("submit_return").setValue(T_submit_return); - - main.addHidden("administrative-continue").setValue(knot.getId()); + + Para buttons = main.addPara(); + buttons.addButton("submit_delete").setValue(T_submit_delete); + buttons.addButton("submit_return").setValue(T_submit_return); + + main.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditItemPolicies.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditItemPolicies.java index 79bfbdd7a7..755df49cdc 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditItemPolicies.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/authorization/EditItemPolicies.java @@ -40,98 +40,105 @@ import org.dspace.eperson.Group; /** * @author Alexey Maslov */ -public class EditItemPolicies extends AbstractDSpaceTransformer -{ - private static final Message T_title = - message("xmlui.administrative.authorization.EditItemPolicies.title"); - private static final Message T_policyList_trail = - message("xmlui.administrative.authorization.general.policyList_trail"); - private static final Message T_authorize_trail = - message("xmlui.administrative.authorization.general.authorize_trail"); - - private static final Message T_main_head = - message("xmlui.administrative.authorization.EditItemPolicies.main_head"); - private static final Message T_main_para1 = - message("xmlui.administrative.authorization.EditItemPolicies.main_para1"); - private static final Message T_main_para2 = - message("xmlui.administrative.authorization.EditItemPolicies.main_para2"); - - private static final Message T_subhead_item = - message("xmlui.administrative.authorization.EditItemPolicies.subhead_item"); - private static final Message T_subhead_bundle = - message("xmlui.administrative.authorization.EditItemPolicies.subhead_bundle"); - private static final Message T_subhead_bitstream = - message("xmlui.administrative.authorization.EditItemPolicies.subhead_bitstream"); - - private static final Message T_add_itemPolicy_link = - message("xmlui.administrative.authorization.EditItemPolicies.add_itemPolicy_link"); - private static final Message T_add_bundlePolicy_link = - message("xmlui.administrative.authorization.EditItemPolicies.add_bundlePolicy_link"); - private static final Message T_add_bitstreamPolicy_link = - message("xmlui.administrative.authorization.EditItemPolicies.add_bitstreamPolicy_link"); - - private static final Message T_head_id = - message("xmlui.administrative.authorization.EditContainerPolicies.head_id"); - private static final Message T_head_action = - message("xmlui.administrative.authorization.EditContainerPolicies.head_action"); - private static final Message T_head_group = - message("xmlui.administrative.authorization.EditContainerPolicies.head_group"); +public class EditItemPolicies extends AbstractDSpaceTransformer +{ + private static final Message T_title = + message("xmlui.administrative.authorization.EditItemPolicies.title"); + private static final Message T_policyList_trail = + message("xmlui.administrative.authorization.general.policyList_trail"); + private static final Message T_authorize_trail = + message("xmlui.administrative.authorization.general.authorize_trail"); + + private static final Message T_main_head = + message("xmlui.administrative.authorization.EditItemPolicies.main_head"); + private static final Message T_main_para1 = + message("xmlui.administrative.authorization.EditItemPolicies.main_para1"); + private static final Message T_main_para2 = + message("xmlui.administrative.authorization.EditItemPolicies.main_para2"); + + private static final Message T_subhead_item = + message("xmlui.administrative.authorization.EditItemPolicies.subhead_item"); + private static final Message T_subhead_bundle = + message("xmlui.administrative.authorization.EditItemPolicies.subhead_bundle"); + private static final Message T_subhead_bitstream = + message("xmlui.administrative.authorization.EditItemPolicies.subhead_bitstream"); + + private static final Message T_add_itemPolicy_link = + message("xmlui.administrative.authorization.EditItemPolicies.add_itemPolicy_link"); + private static final Message T_add_bundlePolicy_link = + message("xmlui.administrative.authorization.EditItemPolicies.add_bundlePolicy_link"); + private static final Message T_add_bitstreamPolicy_link = + message("xmlui.administrative.authorization.EditItemPolicies.add_bitstreamPolicy_link"); + + private static final Message T_head_id = + message("xmlui.administrative.authorization.EditContainerPolicies.head_id"); + private static final Message T_head_action = + message("xmlui.administrative.authorization.EditContainerPolicies.head_action"); + private static final Message T_head_group = + message("xmlui.administrative.authorization.EditContainerPolicies.head_group"); private static final Message T_head_name = - message("xmlui.administrative.authorization.EditContainerPolicies.head_name"); + message("xmlui.administrative.authorization.EditContainerPolicies.head_name"); private static final Message T_head_start_date = - message("xmlui.administrative.authorization.EditContainerPolicies.head_start_date"); + message("xmlui.administrative.authorization.EditContainerPolicies.head_start_date"); private static final Message T_head_end_date = - message("xmlui.administrative.authorization.EditContainerPolicies.head_end_date"); - - private static final Message T_group_edit = - message("xmlui.administrative.authorization.EditContainerPolicies.group_edit"); - - private static final Message T_submit_delete = - message("xmlui.administrative.authorization.EditContainerPolicies.submit_delete"); - private static final Message T_submit_return = - message("xmlui.general.return"); - - private static final Message T_no_policies = - message("xmlui.administrative.authorization.EditContainerPolicies.no_policies"); - - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - + message("xmlui.administrative.authorization.EditContainerPolicies.head_end_date"); - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService(); + private static final Message T_group_edit = + message("xmlui.administrative.authorization.EditContainerPolicies.group_edit"); - - - public void addPageMeta(PageMeta pageMeta) throws WingException + private static final Message T_submit_delete = + message("xmlui.administrative.authorization.EditContainerPolicies.submit_delete"); + private static final Message T_submit_return = + message("xmlui.general.return"); + + private static final Message T_no_policies = + message("xmlui.administrative.authorization.EditContainerPolicies.no_policies"); + + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + + + protected ItemService itemService = + ContentServiceFactory.getInstance().getItemService(); + protected AuthorizeService authorizeService = + AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected ResourcePolicyService resourcePolicyService = + AuthorizeServiceFactory.getInstance().getResourcePolicyService(); + + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/authorize", T_authorize_trail); pageMeta.addTrail().addContent(T_policyList_trail); } - - public void addBody(Body body) throws WingException, SQLException - { - /* Get and setup our parameters */ + + public void addBody(Body body) + throws WingException, SQLException + { + /* Get and setup our parameters */ UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); int highlightID = parameters.getParameterAsInteger("highlightID",-1); String baseURL = contextPath+"/admin/epeople?administrative-continue="+knot.getId(); - /* First, set up our various data structures */ - Item item = itemService.find(context, itemID); - List bundles = item.getBundles(); + /* First, set up our various data structures */ + Item item = itemService.find(context, itemID); + List bundles = item.getBundles(); - ArrayList itemPolicies = (ArrayList) authorizeService.getPolicies(context, item); - - // DIVISION: main - Division main = body.addInteractiveDivision("edit-item-policies",contextPath+"/admin/authorize",Division.METHOD_POST,"primary administrative authorization"); - main.setHead(T_main_head.parameterize(item.getHandle(),item.getID())); - main.addPara().addHighlight("italic").addContent(T_main_para1); - main.addPara().addHighlight("italic").addContent(T_main_para2); - - Table table = main.addTable("policies-confirm-delete",itemPolicies.size() + 3, 8); + ArrayList itemPolicies = + (ArrayList) authorizeService.getPolicies(context, item); + + // DIVISION: main + Division main = body.addInteractiveDivision( + "edit-item-policies", contextPath + "/admin/authorize", + Division.METHOD_POST, "primary administrative authorization"); + main.setHead(T_main_head.parameterize(item.getHandle(),item.getID())); + main.addPara().addHighlight("italic").addContent(T_main_para1); + main.addPara().addHighlight("italic").addContent(T_main_para2); + + Table table = main.addTable("policies-confirm-delete",itemPolicies.size() + 3, 8); Row header = table.addRow(Row.ROLE_HEADER); header.addCell(); header.addCell().addContent(T_head_id); @@ -147,121 +154,136 @@ public class EditItemPolicies extends AbstractDSpaceTransformer Row subheader = table.addRow(null,Row.ROLE_HEADER,"subheader"); subheader.addCell(1, 7).addHighlight("bold").addContent(T_subhead_item); subheader.addCell().addHighlight("bold").addXref(baseURL + "&submit_add_item", T_add_itemPolicy_link); - + this.rowBuilder(baseURL, table, itemPolicies, item.getID(), Constants.ITEM, highlightID); - - // Next, one by one, we get the bundles - for (Bundle bundle : bundles) { - subheader = table.addRow(null,Row.ROLE_HEADER,"subheader"); - subheader.addCell(null, null, 1, 7, "indent").addHighlight("bold").addContent(T_subhead_bundle.parameterize(bundle.getName(),bundle.getID())); - subheader.addCell().addHighlight("bold").addXref(baseURL + "&submit_add_bundle_" + bundle.getID(), T_add_bundlePolicy_link); - ArrayList bundlePolicies = (ArrayList) authorizeService.getPolicies(context, bundle); - this.rowBuilder(baseURL, table, bundlePolicies, bundle.getID(), Constants.BUNDLE, highlightID); - - // And eventually to the bundle's bitstreams - List bitstreams = bundle.getBitstreams(); - for (Bitstream bitstream : bitstreams) { - subheader = table.addRow(null,Row.ROLE_HEADER,"subheader"); - subheader.addCell(null, null, 1, 7, "doubleIndent").addContent(T_subhead_bitstream.parameterize(bitstream.getName(),bitstream.getID())); - subheader.addCell().addXref(baseURL + "&submit_add_bitstream_" + bitstream.getID(), T_add_bitstreamPolicy_link); + // Next, one by one, we get the bundles + for (Bundle bundle : bundles) + { + subheader = table.addRow(null,Row.ROLE_HEADER,"subheader"); + subheader.addCell(null, null, 1, 7, "indent").addHighlight("bold").addContent(T_subhead_bundle.parameterize(bundle.getName(),bundle.getID())); + subheader.addCell().addHighlight("bold").addXref(baseURL + "&submit_add_bundle_" + bundle.getID(), T_add_bundlePolicy_link); - ArrayList bitstreamPolicies = (ArrayList) authorizeService.getPolicies(context, bitstream); - this.rowBuilder(baseURL, table, bitstreamPolicies, bitstream.getID(), Constants.BITSTREAM, highlightID); - } - } - - Para buttons = main.addPara(); - buttons.addButton("submit_delete").setValue(T_submit_delete); - buttons.addButton("submit_return").setValue(T_submit_return); - - - main.addHidden("administrative-continue").setValue(knot.getId()); + ArrayList bundlePolicies = (ArrayList) authorizeService.getPolicies(context, bundle); + this.rowBuilder(baseURL, table, bundlePolicies, bundle.getID(), Constants.BUNDLE, highlightID); + + // And eventually to the bundle's bitstreams + List bitstreams = bundle.getBitstreams(); + for (Bitstream bitstream : bitstreams) + { + subheader = table.addRow(null,Row.ROLE_HEADER,"subheader"); + subheader.addCell(null, null, 1, 7, "doubleIndent").addContent(T_subhead_bitstream.parameterize(bitstream.getName(),bitstream.getID())); + subheader.addCell().addXref(baseURL + "&submit_add_bitstream_" + bitstream.getID(), T_add_bitstreamPolicy_link); + + ArrayList bitstreamPolicies = (ArrayList) authorizeService.getPolicies(context, bitstream); + this.rowBuilder(baseURL, table, bitstreamPolicies, bitstream.getID(), Constants.BITSTREAM, highlightID); + } + } + + Para buttons = main.addPara(); + buttons.addButton("submit_delete").setValue(T_submit_delete); + buttons.addButton("submit_return").setValue(T_submit_return); + + + main.addHidden("administrative-continue").setValue(knot.getId()); } - - - private void rowBuilder(String baseURL, Table table, java.util.List policies, UUID objectID, int objectType, int highlightID) throws WingException, SQLException - { - // If the list of policies is empty, say so - if (policies == null || policies.size() == 0) { - table.addRow().addCell(1, 8).addHighlight("italic").addContent(T_no_policies); - } - // Otherwise, iterate over the given policies, creating a new table row for each one - else { - for (ResourcePolicy policy : policies) - { - Row row; - if (policy.getID() == highlightID) + + + private void rowBuilder(String baseURL, Table table, java.util.List policies, UUID objectID, int objectType, int highlightID) + throws WingException, SQLException + { + // If the list of policies is empty, say so + if (policies == null || policies.size() == 0) + { + table.addRow().addCell(1, 8).addHighlight("italic").addContent(T_no_policies); + } + // Otherwise, iterate over the given policies, creating a new table row for each one + else + { + for (ResourcePolicy policy : policies) + { + Row row; + if (policy.getID() == highlightID) { row = table.addRow(null, null, "highlight"); } - else + else { row = table.addRow(); } - - Cell cell; - if (objectType == Constants.BUNDLE) + + Cell cell; + if (objectType == Constants.BUNDLE) { cell = row.addCell(null, null, "indent"); } - else if (objectType == Constants.BITSTREAM) + else if (objectType == Constants.BITSTREAM) { cell = row.addCell(null, null, "doubleIndent"); } - else + else { cell = row.addCell(); } - - - CheckBox select = cell.addCheckBox("select_policy"); - - select.setLabel(String.valueOf(policy.getID())); - select.addOption(String.valueOf(policy.getID())); - - // Accounting for the funky case of an empty policy - Group policyGroup = policy.getGroup(); - - row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID() + - "&object_id=" + objectID + "&object_type=" + objectType, String.valueOf(policy.getID())); + + + CheckBox select = cell.addCheckBox("select_policy"); + + select.setLabel(String.valueOf(policy.getID())); + select.addOption(String.valueOf(policy.getID())); + + // Accounting for the funky case of an empty policy + Group policyGroup = policy.getGroup(); + + row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + + policy.getID() + "&object_id=" + objectID + "&object_type=" + + objectType, String.valueOf(policy.getID())); // name String name = ""; - if(policy.getRpName() != null) + if (policy.getRpName() != null) name=policy.getRpName(); row.addCell().addContent(name); - row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + policy.getID() + - "&object_id=" + objectID + "&object_type=" + objectType, resourcePolicyService.getActionText(policy)); - if (policyGroup != null) { - Cell groupCell = row.addCell(1,2); - groupCell.addContent(policyGroup.getName()); - Highlight groupHigh = groupCell.addHighlight("fade"); - groupHigh.addContent(" ["); - groupHigh.addXref(baseURL + "&submit_edit_group&group_id=" + policyGroup.getID(), T_group_edit); - groupHigh.addContent("]"); - } - else { - row.addCell(1,2).addContent("..."); - } + row.addCell().addXref(baseURL + "&submit_edit&policy_id=" + + policy.getID() + "&object_id=" + objectID + "&object_type=" + + objectType, resourcePolicyService.getActionText(policy)); + if (policyGroup != null) + { + Cell groupCell = row.addCell(1,2); + groupCell.addContent(policyGroup.getName()); + Highlight groupHigh = groupCell.addHighlight("fade"); + groupHigh.addContent(" ["); + groupHigh.addXref(baseURL + "&submit_edit_group&group_id=" + + policyGroup.getID(), T_group_edit); + groupHigh.addContent("]"); + } + else + { + row.addCell(1,2).addContent("..."); + } // startDate - if(policy.getStartDate()!=null){ - row.addCell().addContent(DateFormatUtils.format(policy.getStartDate(), "yyyy-MM-dd")); + if (policy.getStartDate() != null) + { + row.addCell().addContent(DateFormatUtils.format( + policy.getStartDate(), "yyyy-MM-dd")); } - else{ + else + { row.addCell().addContent(""); } // endDate - if(policy.getEndDate()!=null){ + if (policy.getEndDate() != null) + { row.addCell().addContent(DateFormatUtils.format(policy.getEndDate(), "yyyy-MM-dd")); } - else{ + else + { row.addCell().addContent(""); } } - } - } + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/AssignCollectionRoles.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/AssignCollectionRoles.java index e5bcf16206..17b82782b9 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/AssignCollectionRoles.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/AssignCollectionRoles.java @@ -42,123 +42,125 @@ import java.util.UUID; * group, workflows, collection admin, and default read. * @author Alexey Maslov */ -public class AssignCollectionRoles extends AbstractDSpaceTransformer +public class AssignCollectionRoles extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - - private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); - private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); - private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); - private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); - private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); - - private static final Message T_submit_return = message("xmlui.general.return"); - - private static final Message T_title = message("xmlui.administrative.collection.AssignCollectionRoles.title"); - private static final Message T_trail = message("xmlui.administrative.collection.AssignCollectionRoles.trail"); + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_main_head = message("xmlui.administrative.collection.AssignCollectionRoles.main_head"); - private static final Message T_no_role = message("xmlui.administrative.collection.AssignCollectionRoles.no_role"); - - private static final Message T_create = message("xmlui.administrative.collection.AssignCollectionRoles.create"); - private static final Message T_delete = message("xmlui.general.delete"); - private static final Message T_restrict = message("xmlui.administrative.collection.AssignCollectionRoles.restrict"); + private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); + private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); + private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); + private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); + private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); - private static final Message T_help_admins = message("xmlui.administrative.collection.AssignCollectionRoles.help_admins"); - private static final Message T_help_wf_step1 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step1"); - private static final Message T_help_wf_step2 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step2"); - private static final Message T_help_wf_step3 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step3"); - private static final Message T_help_submitters = message("xmlui.administrative.collection.AssignCollectionRoles.help_submitters"); - private static final Message T_help_default_read = message("xmlui.administrative.collection.AssignCollectionRoles.help_default_read"); + private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_default_read_custom = message("xmlui.administrative.collection.AssignCollectionRoles.default_read_custom"); - private static final Message T_default_read_anonymous = message("xmlui.administrative.collection.AssignCollectionRoles.default_read_anonymous"); + private static final Message T_title = message("xmlui.administrative.collection.AssignCollectionRoles.title"); + private static final Message T_trail = message("xmlui.administrative.collection.AssignCollectionRoles.trail"); - private static final Message T_edit_authorization = message("xmlui.administrative.collection.AssignCollectionRoles.edit_authorization"); + private static final Message T_main_head = message("xmlui.administrative.collection.AssignCollectionRoles.main_head"); + private static final Message T_no_role = message("xmlui.administrative.collection.AssignCollectionRoles.no_role"); - private static final Message T_role_name = message("xmlui.administrative.collection.AssignCollectionRoles.role_name"); - private static final Message T_role_group = message("xmlui.administrative.collection.AssignCollectionRoles.role_group"); - private static final Message T_role_buttons = message("xmlui.administrative.collection.AssignCollectionRoles.role_buttons"); + private static final Message T_create = message("xmlui.administrative.collection.AssignCollectionRoles.create"); + private static final Message T_delete = message("xmlui.general.delete"); + private static final Message T_restrict = message("xmlui.administrative.collection.AssignCollectionRoles.restrict"); + + private static final Message T_help_admins = message("xmlui.administrative.collection.AssignCollectionRoles.help_admins"); + private static final Message T_help_wf_step1 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step1"); + private static final Message T_help_wf_step2 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step2"); + private static final Message T_help_wf_step3 = message("xmlui.administrative.collection.AssignCollectionRoles.help_wf_step3"); + private static final Message T_help_submitters = message("xmlui.administrative.collection.AssignCollectionRoles.help_submitters"); + private static final Message T_help_default_read = message("xmlui.administrative.collection.AssignCollectionRoles.help_default_read"); + + private static final Message T_default_read_custom = message("xmlui.administrative.collection.AssignCollectionRoles.default_read_custom"); + private static final Message T_default_read_anonymous = message("xmlui.administrative.collection.AssignCollectionRoles.default_read_anonymous"); + + private static final Message T_edit_authorization = message("xmlui.administrative.collection.AssignCollectionRoles.edit_authorization"); + + private static final Message T_role_name = message("xmlui.administrative.collection.AssignCollectionRoles.role_name"); + private static final Message T_role_group = message("xmlui.administrative.collection.AssignCollectionRoles.role_group"); + private static final Message T_role_buttons = message("xmlui.administrative.collection.AssignCollectionRoles.role_buttons"); + + private static final Message T_label_admins = message("xmlui.administrative.collection.AssignCollectionRoles.label_admins"); + private static final Message T_label_wf = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf"); + private static final Message T_label_wf_step1 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step1"); + private static final Message T_label_wf_step2 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step2"); + private static final Message T_label_wf_step3 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step3"); + private static final Message T_label_submitters = message("xmlui.administrative.collection.AssignCollectionRoles.label_submitters"); + private static final Message T_label_default_read = message("xmlui.administrative.collection.AssignCollectionRoles.label_default_read"); + + private static final Message T_sysadmins_only = message("xmlui.administrative.collection.AssignCollectionRoles.sysadmins_only"); + private static final Message T_sysadmins_only_repository_role = message("xmlui.administrative.collection.AssignCollectionRoles.repository_role"); + private static final Message T_not_allowed = message("xmlui.administrative.collection.AssignCollectionRoles.not_allowed"); - private static final Message T_label_admins = message("xmlui.administrative.collection.AssignCollectionRoles.label_admins"); - private static final Message T_label_wf = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf"); - private static final Message T_label_wf_step1 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step1"); - private static final Message T_label_wf_step2 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step2"); - private static final Message T_label_wf_step3 = message("xmlui.administrative.collection.AssignCollectionRoles.label_wf_step3"); - private static final Message T_label_submitters = message("xmlui.administrative.collection.AssignCollectionRoles.label_submitters"); - private static final Message T_label_default_read = message("xmlui.administrative.collection.AssignCollectionRoles.label_default_read"); - - private static final Message T_sysadmins_only = message("xmlui.administrative.collection.AssignCollectionRoles.sysadmins_only"); - private static final Message T_sysadmins_only_repository_role = message("xmlui.administrative.collection.AssignCollectionRoles.repository_role"); - private static final Message T_not_allowed = message("xmlui.administrative.collection.AssignCollectionRoles.not_allowed"); - private static Logger log = Logger.getLogger(AssignCollectionRoles.class); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - public void addPageMeta(PageMeta pageMeta) throws WingException + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); - Collection thisCollection = collectionService.find(context, collectionID); - - String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); - - Group admins = thisCollection.getAdministrators(); - Group submitters = thisCollection.getSubmitters(); - Group defaultRead = FlowContainerUtils.getCollectionDefaultRead(context, thisCollection); - - // DIVISION: main - Division main = body.addInteractiveDivision("collection-assign-roles",contextPath+"/admin/collection",Division.METHOD_POST,"primary administrative collection"); - main.setHead(T_main_head.parameterize(collectionService.getMetadata(thisCollection, "name"))); - - List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); - options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_roles",T_options_roles); - options.addItem().addXref(baseURL+"&submit_harvesting",T_options_harvest); - options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); - - // The table of admin roles - Table rolesTable = main.addTable("roles-table", 6, 5); - Row tableRow; - - // The header row - Row tableHeader = rolesTable.addRow(Row.ROLE_HEADER); - tableHeader.addCell().addContent(T_role_name); - tableHeader.addCell().addContent(T_role_group); - tableHeader.addCell().addContent(T_role_buttons); - rolesTable.addRow(); - - - /* - * The collection admins - */ - // data row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_admins); - if (admins != null) - { - try + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); + Collection thisCollection = collectionService.find(context, collectionID); + + String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); + + Group admins = thisCollection.getAdministrators(); + Group submitters = thisCollection.getSubmitters(); + + Group defaultRead = FlowContainerUtils.getCollectionDefaultRead(context, thisCollection); + + // DIVISION: main + Division main = body.addInteractiveDivision("collection-assign-roles",contextPath+"/admin/collection",Division.METHOD_POST,"primary administrative collection"); + main.setHead(T_main_head.parameterize(collectionService.getMetadata(thisCollection, "name"))); + + List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); + options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); + options.addItem().addHighlight("bold").addXref(baseURL+"&submit_roles",T_options_roles); + options.addItem().addXref(baseURL+"&submit_harvesting",T_options_harvest); + options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); + + // The table of admin roles + Table rolesTable = main.addTable("roles-table", 6, 5); + Row tableRow; + + // The header row + Row tableHeader = rolesTable.addRow(Row.ROLE_HEADER); + tableHeader.addCell().addContent(T_role_name); + tableHeader.addCell().addContent(T_role_group); + tableHeader.addCell().addContent(T_role_buttons); + rolesTable.addRow(); + + + /* + * The collection admins + */ + // data row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_admins); + if (admins != null) + { + try { AuthorizeUtil.authorizeManageAdminGroup(context, thisCollection); tableRow.addCell().addXref(baseURL + "&submit_edit_admin", admins.getName()); } - catch (AuthorizeException authex) { + catch (AuthorizeException authex) { // add a notice, the user is not authorized to create/edit collection's admin group tableRow.addCell().addContent(T_not_allowed); } @@ -171,11 +173,11 @@ public class AssignCollectionRoles extends AbstractDSpaceTransformer { // nothing to add, the user is not allowed to delete the group } - } - else - { - tableRow.addCell().addContent(T_no_role); - try + } + else + { + tableRow.addCell().addContent(T_no_role); + try { AuthorizeUtil.authorizeManageAdminGroup(context, thisCollection); tableRow.addCell().addButton("submit_create_admin").setValue(T_create); @@ -184,63 +186,64 @@ public class AssignCollectionRoles extends AbstractDSpaceTransformer // add a notice, the user is not authorized to create/edit collection's admin group tableRow.addCell().addContent(T_not_allowed); } - } - // help and directions row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(); - tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_admins); - - /* - * The collection submitters - */ - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_submitters); - try - { - AuthorizeUtil.authorizeManageSubmittersGroup(context, thisCollection); - if (submitters != null) - { - tableRow.addCell().addXref(baseURL + "&submit_edit_submit", submitters.getName()); + } + // help and directions row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(); + tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_admins); + + /* + * The collection submitters + */ + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_submitters); + try + { + AuthorizeUtil.authorizeManageSubmittersGroup(context, thisCollection); + if (submitters != null) + { + tableRow.addCell().addXref(baseURL + "&submit_edit_submit", submitters.getName()); tableRow.addCell().addButton("submit_delete_submit").setValue(T_delete); - } - else - { - tableRow.addCell().addContent(T_no_role); + } + else + { + tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_submit").setValue(T_create); - } - } - catch (AuthorizeException authex) - { - tableRow.addCell().addContent(T_not_allowed); - } - // help and directions row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(); - tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_submitters); + } + } + catch (AuthorizeException authex) + { + tableRow.addCell().addContent(T_not_allowed); + } + // help and directions row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(); + tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_submitters); - /* - * The collection's default read authorizations - */ - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_default_read); - if (defaultRead == null) - { - // Custome reading permissions, we can't handle it, just provide a link to the - // authorizations manager. - tableRow.addCell(1,2).addContent(T_default_read_custom); - } - else if (StringUtils.equals(defaultRead.getName(), Group.ANONYMOUS)) { - // Anonymous reading - tableRow.addCell().addContent(T_default_read_anonymous); - addAdministratorOnlyButton(tableRow.addCell(),"submit_create_default_read",T_restrict); - } - else - { - // A specific group is dedicated to reading. - tableRow.addCell().addXref(baseURL + "&submit_edit_default_read", defaultRead.getName()); - addAdministratorOnlyButton(tableRow.addCell(),"submit_delete_default_read",T_delete); - } + /* + * The collection's default read authorizations + */ + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_default_read); + if (defaultRead == null) + { + // Custome reading permissions, we can't handle it, just provide a link to the + // authorizations manager. + tableRow.addCell(1,2).addContent(T_default_read_custom); + } + else if (StringUtils.equals(defaultRead.getName(), Group.ANONYMOUS)) + { + // Anonymous reading + tableRow.addCell().addContent(T_default_read_anonymous); + addAdministratorOnlyButton(tableRow.addCell(),"submit_create_default_read",T_restrict); + } + else + { + // A specific group is dedicated to reading. + tableRow.addCell().addXref(baseURL + "&submit_edit_default_read", defaultRead.getName()); + addAdministratorOnlyButton(tableRow.addCell(),"submit_delete_default_read",T_delete); + } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); @@ -248,158 +251,186 @@ public class AssignCollectionRoles extends AbstractDSpaceTransformer tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_default_read); - if(WorkflowServiceFactory.getInstance().getWorkflowService() instanceof XmlWorkflowService) { - try{ - HashMap roles = WorkflowUtils.getAllExternalRoles(thisCollection); - addXMLWorkflowRoles(thisCollection, baseURL, roles, rolesTable); - } catch (WorkflowConfigurationException e) { + if (WorkflowServiceFactory.getInstance().getWorkflowService() instanceof XmlWorkflowService) + { + try + { + HashMap roles = WorkflowUtils.getAllExternalRoles(thisCollection); + addXMLWorkflowRoles(thisCollection, baseURL, roles, rolesTable); + } catch (WorkflowConfigurationException e) { log.error(LogManager.getHeader(context, "error while getting collection roles", "Collection id: " + thisCollection.getID())); - } catch (IOException e) { - log.error(LogManager.getHeader(context, "error while getting collection roles", "Collection id: " + thisCollection.getID())); - } - }else{ - addOriginalWorkflowRoles(thisCollection, baseURL, rolesTable); - } + } catch (IOException e) { + log.error(LogManager.getHeader(context, "error while getting collection roles", "Collection id: " + thisCollection.getID())); + } + } + else + { + addOriginalWorkflowRoles(thisCollection, baseURL, rolesTable); + } - try - { - AuthorizeUtil.authorizeManageCollectionPolicy(context, thisCollection); - // add one last link to edit the raw authorizations - Cell authCell =rolesTable.addRow().addCell(1,3); - authCell.addXref(baseURL + "&submit_authorizations", T_edit_authorization); - } - catch (AuthorizeException authex) { + try + { + AuthorizeUtil.authorizeManageCollectionPolicy(context, thisCollection); + // add one last link to edit the raw authorizations + Cell authCell =rolesTable.addRow().addCell(1,3); + authCell.addXref(baseURL + "&submit_authorizations", T_edit_authorization); + } + catch (AuthorizeException authex) { // nothing to add, the user is not authorized to edit collection's policies } - Para buttonList = main.addPara(); - buttonList.addButton("submit_return").setValue(T_submit_return); + Para buttonList = main.addPara(); + buttonList.addButton("submit_return").setValue(T_submit_return); - main.addHidden("administrative-continue").setValue(knot.getId()); + main.addHidden("administrative-continue").setValue(knot.getId()); } - private void addOriginalWorkflowRoles(Collection thisCollection, String baseURL, Table rolesTable) throws SQLException, WingException { - Row tableRow;/* - * Workflow steps 1-3 - */ - // data row - try + private void addOriginalWorkflowRoles(Collection thisCollection, String baseURL, Table rolesTable) + throws SQLException, WingException + { + Row tableRow; + /* + * Workflow steps 1-3 + */ + // data row + try { Group wfStep1 = collectionService.getWorkflowGroup(thisCollection, 1); Group wfStep2 = collectionService.getWorkflowGroup(thisCollection, 2); Group wfStep3 = collectionService.getWorkflowGroup(thisCollection, 3); AuthorizeUtil.authorizeManageWorkflowsGroup(context, thisCollection); - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step1); - if (wfStep1 != null) - { - tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step1", wfStep1.getName()); + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step1); + if (wfStep1 != null) + { + tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step1", wfStep1.getName()); tableRow.addCell().addButton("submit_delete_wf_step1").setValue(T_delete); - } - else - { - tableRow.addCell().addContent(T_no_role); + } + else + { + tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_wf_step1").setValue(T_create); - } - // help and directions row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(); - tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step1); - - - // data row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step2); - if (wfStep2 != null) - { - tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step2", wfStep2.getName()); + } + // help and directions row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(); + tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step1); + + + // data row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step2); + if (wfStep2 != null) + { + tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step2", wfStep2.getName()); tableRow.addCell().addButton("submit_delete_wf_step2").setValue(T_delete); - } - else - { - tableRow.addCell().addContent(T_no_role); + } + else + { + tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_wf_step2").setValue(T_create); - } - // help and directions row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(); - tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step2); - - - // data row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step3); - if (wfStep3 != null) - { - tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step3", wfStep3.getName()); + } + // help and directions row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(); + tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step2); + + + // data row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf_step3); + if (wfStep3 != null) + { + tableRow.addCell().addXref(baseURL + "&submit_edit_wf_step3", wfStep3.getName()); tableRow.addCell().addButton("submit_delete_wf_step3").setValue(T_delete); - } - else - { - tableRow.addCell().addContent(T_no_role); + } + else + { + tableRow.addCell().addContent(T_no_role); tableRow.addCell().addButton("submit_create_wf_step3").setValue(T_create); - } - // help and directions row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(); - tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step3); + } + // help and directions row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(); + tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_wf_step3); } - catch (AuthorizeException authex) { + catch (AuthorizeException authex) { // add a notice, the user is not allowed to manage workflow group - tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_wf); tableRow.addCell().addContent(T_not_allowed); } } - private void addXMLWorkflowRoles(Collection thisCollection, String baseURL, HashMap roles, Table rolesTable) throws WingException, SQLException { + private void addXMLWorkflowRoles(Collection thisCollection, String baseURL, HashMap roles, Table rolesTable) + throws WingException, SQLException + { Row tableRow; - if(roles != null){ + if (roles != null){ //ROLES: show group name instead of role name - for(String roleId: roles.keySet()){ + for (String roleId: roles.keySet()) + { Role role = roles.get(roleId); - if (role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY) { + if (role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY) + { tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(role.getName()); Group roleGroup = WorkflowUtils.getRoleGroup(context, thisCollection, role); - if (roleGroup != null) { - if(role.getScope() == Role.Scope.REPOSITORY){ - if(authorizeService.isAdmin(context)){ + if (roleGroup != null) + { + if (role.getScope() == Role.Scope.REPOSITORY) + { + if (authorizeService.isAdmin(context)) + { tableRow.addCell().addXref(baseURL + "&submit_edit_wf_role_" + roleId, roleGroup.getName()); - }else{ + } + else + { Cell cell = tableRow.addCell(); cell.addContent(roleGroup.getName()); cell.addHighlight("fade").addContent(T_sysadmins_only_repository_role); } - }else{ + } + else + { tableRow.addCell().addXref(baseURL + "&submit_edit_wf_role_" + roleId, roleGroup.getName()); } if (role.getScope() == Role.Scope.COLLECTION) { addAdministratorOnlyButton(tableRow.addCell(), "submit_delete_wf_role_" + roleId, T_delete); - } else { + } + else + { tableRow.addCell(); } - } else { + } + else + { tableRow.addCell().addContent(T_no_role); - if (role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY) { + if (role.getScope() == Role.Scope.COLLECTION || role.getScope() == Role.Scope.REPOSITORY) + { addAdministratorOnlyButton(tableRow.addCell(), "submit_create_wf_role_" + roleId, T_create); - } else { + } + else + { tableRow.addCell(); } } // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); - if (role.getDescription() != null){ + if (role.getDescription() != null) + { tableRow.addCell(1,2).addHighlight("fade offset").addContent(role.getDescription()); } - } else { + } + else + { tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(Cell.ROLE_HEADER).addContent(role.getName()); @@ -409,7 +440,8 @@ public class AssignCollectionRoles extends AbstractDSpaceTransformer // help and directions row tableRow = rolesTable.addRow(Row.ROLE_DATA); tableRow.addCell(); - if (role.getDescription() != null){ + if (role.getDescription() != null) + { tableRow.addCell(1,2).addHighlight("fade offset").addContent(role.getDescription()); } } @@ -418,15 +450,16 @@ public class AssignCollectionRoles extends AbstractDSpaceTransformer } - private void addAdministratorOnlyButton(Cell cell, String buttonName, Message buttonLabel) throws WingException, SQLException - { - Button button = cell.addButton(buttonName); - button.setValue(buttonLabel); - if (!authorizeService.isAdmin(context)) - { - // Only admins can create or delete - button.setDisabled(); - cell.addHighlight("fade").addContent(T_sysadmins_only); - } - } + private void addAdministratorOnlyButton(Cell cell, String buttonName, Message buttonLabel) + throws WingException, SQLException + { + Button button = cell.addButton(buttonName); + button.setValue(buttonLabel); + if (!authorizeService.isAdmin(context)) + { + // Only admins can create or delete + button.setDisabled(); + cell.addHighlight("fade").addContent(T_sysadmins_only); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/CurateCollectionForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/CurateCollectionForm.java index 0ccbf7d67a..15140772ac 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/CurateCollectionForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/CurateCollectionForm.java @@ -39,37 +39,38 @@ import org.dspace.content.Collection; * @author wbossons */ public class CurateCollectionForm extends AbstractDSpaceTransformer { - /** Common Package Language Strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); - private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); - private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); - private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); - private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); - private static final Message T_submit_perform = message("xmlui.general.perform"); - private static final Message T_submit_queue = message("xmlui.general.queue"); - private static final Message T_submit_return = message("xmlui.general.return"); - // End common package language strings + /** Common Package Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - // Page/Form specific language strings - private static final Message T_main_head = message("xmlui.administrative.collection.CurateCollectionForm.main_head"); - private static final Message T_title = message("xmlui.administrative.collection.CurateCollectionForm.title"); - private static final Message T_trail = message("xmlui.administrative.collection.CurateCollectionForm.trail"); + private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); + private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); + private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); + private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); + private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); + private static final Message T_submit_perform = message("xmlui.general.perform"); + private static final Message T_submit_queue = message("xmlui.general.queue"); + private static final Message T_submit_return = message("xmlui.general.return"); + // End common package language strings + + // Page/Form specific language strings + private static final Message T_main_head = message("xmlui.administrative.collection.CurateCollectionForm.main_head"); + private static final Message T_title = message("xmlui.administrative.collection.CurateCollectionForm.title"); + private static final Message T_trail = message("xmlui.administrative.collection.CurateCollectionForm.trail"); + + private static final Message T_label_name = message("xmlui.administrative.collection.CurateCollectionForm.label_name"); + private static final Message T_taskgroup_label_name = message("xmlui.administrative.CurateForm.taskgroup_label_name"); - private static final Message T_label_name = message("xmlui.administrative.collection.CurateCollectionForm.label_name"); - private static final Message T_taskgroup_label_name = message("xmlui.administrative.CurateForm.taskgroup_label_name"); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); @Override - public void setup(SourceResolver resolver, Map objectModel, String src, - Parameters parameters) throws ProcessingException, SAXException, IOException - { - super.setup(resolver, objectModel, src, parameters); - FlowCurationUtils.setupCurationTasks(); - } + public void setup(SourceResolver resolver, Map objectModel, String src, + Parameters parameters) throws ProcessingException, SAXException, IOException + { + super.setup(resolver, objectModel, src, parameters); + FlowCurationUtils.setupCurationTasks(); + } @Override public void addPageMeta(PageMeta pageMeta) throws WingException @@ -82,35 +83,39 @@ public class CurateCollectionForm extends AbstractDSpaceTransformer { @Override public void addBody(Body body) - throws WingException, SQLException, AuthorizeException, UnsupportedEncodingException - { - UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); - Collection thisCollection = collectionService.find(context, collectionID); - String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); + throws WingException, SQLException, AuthorizeException, UnsupportedEncodingException + { + UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); + Collection thisCollection = collectionService.find(context, collectionID); + String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); - // DIVISION: main - Division main = body.addInteractiveDivision("collection-curate",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); - main.setHead(T_main_head.parameterize(thisCollection.getName())); + // DIVISION: main + Division main = body.addInteractiveDivision("collection-curate", + contextPath + "/admin/collection", Division.METHOD_MULTIPART, + "primary administrative collection"); + main.setHead(T_main_head.parameterize(thisCollection.getName())); - List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); - options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); - options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); - options.addItem().addXref(baseURL+"&submit_harvesting",T_options_harvest); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_curate",T_options_curate); + List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); + options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); + options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); + options.addItem().addXref(baseURL+"&submit_harvesting",T_options_harvest); + options.addItem().addHighlight("bold").addXref(baseURL+"&submit_curate",T_options_curate); - List curationTaskList = main.addList("curationTaskList", "form"); + List curationTaskList = main.addList("curationTaskList", "form"); String curateGroup = ""; try { - curateGroup = (parameters.getParameter("select_curate_group") != null) ? parameters.getParameter("select_curate_group") : FlowCurationUtils.UNGROUPED_TASKS; + curateGroup = (parameters.getParameter("select_curate_group") != null) + ? parameters.getParameter("select_curate_group") + : FlowCurationUtils.UNGROUPED_TASKS; } catch (Exception pe) { - // noop + // noop } if (!FlowCurationUtils.groups.isEmpty()) { - curationTaskList.addLabel(T_taskgroup_label_name); //needs to check for >=1 group configured + curationTaskList.addLabel(T_taskgroup_label_name); //needs to check for >=1 group configured Select groupSelect = curationTaskList.addItem().addSelect("select_curate_group"); groupSelect = FlowCurationUtils.getGroupSelectOptions(groupSelect); groupSelect.setSize(1); @@ -118,7 +123,7 @@ public class CurateCollectionForm extends AbstractDSpaceTransformer { groupSelect.setEvtBehavior("submitOnChange"); if (curateGroup.equals("")) { - curateGroup = (String) (FlowCurationUtils.groups.keySet().iterator().next()); + curateGroup = (String) (FlowCurationUtils.groups.keySet().iterator().next()); } groupSelect.setOptionSelected(curateGroup); } @@ -129,12 +134,10 @@ public class CurateCollectionForm extends AbstractDSpaceTransformer { taskSelect.setRequired(); // need submit_curate_task and submit_return - Para buttonList = main.addPara(); - buttonList.addButton("submit_curate_task").setValue(T_submit_perform); - buttonList.addButton("submit_queue_task").setValue(T_submit_queue); - buttonList.addButton("submit_return").setValue(T_submit_return); - main.addHidden("administrative-continue").setValue(knot.getId()); - + Para buttonList = main.addPara(); + buttonList.addButton("submit_curate_task").setValue(T_submit_perform); + buttonList.addButton("submit_queue_task").setValue(T_submit_queue); + buttonList.addButton("submit_return").setValue(T_submit_return); + main.addHidden("administrative-continue").setValue(knot.getId()); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/EditCollectionHarvestingForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/EditCollectionHarvestingForm.java index b1aed0f628..49255368cf 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/EditCollectionHarvestingForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/EditCollectionHarvestingForm.java @@ -33,169 +33,175 @@ import org.dspace.harvest.service.HarvestedCollectionService; /** * This is the other form that deals with harvesting. This one comes up when the collection is * edited with the harvesting options set and verified. Allows two actions: "import" and "reingest", - * as well as "change", which takes the user to the other harvesting form. + * as well as "change", which takes the user to the other harvesting form. * @author Alexey Maslov */ -public class EditCollectionHarvestingForm extends AbstractDSpaceTransformer +public class EditCollectionHarvestingForm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - - private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); - private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); - private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); - private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); - private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); - - private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); - private static final Message T_title = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.title"); - private static final Message T_trail = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.trail"); - - private static final Message T_label_source = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.label_source"); - private static final Message T_source_normal = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_normal"); - private static final Message T_source_harvested = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_harvested"); + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_submit_save = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.submit_save"); - - private static final Message T_main_settings_head = message("xmlui.administrative.collection.EditCollectionHarvestingForm.main_settings_head"); - private static final Message T_label_oai_provider = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_oai_provider"); - private static final Message T_label_setid = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_setid"); - private static final Message T_label_metadata_format = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_metadata_format"); - - private static final Message T_label_harvest_level = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_level"); - private static final Message T_label_harvest_result = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_result"); - private static final Message T_harvest_result_new = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_result_new"); - - private static final Message T_label_harvest_status = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_status"); - private static final Message T_harvest_status_ready = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_ready"); - private static final Message T_harvest_status_busy = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_busy"); - private static final Message T_harvest_status_queued = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_queued"); - private static final Message T_harvest_status_oai_error = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_oai_error"); - private static final Message T_harvest_status_unknown_error = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_unknown_error"); - - private static final Message T_option_md_only = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_only"); - private static final Message T_option_md_and_ref = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_and_ref"); - private static final Message T_option_md_and_bs = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_and_bs"); + private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); + private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); + private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); + private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); + private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); - private static final Message T_submit_change_settings = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_change_settings"); - private static final Message T_submit_import_now = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_import_now"); - private static final Message T_submit_reimport_collection = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_reimport_collection"); - - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected HarvestedCollectionService harvestedCollectionService = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); + private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); + private static final Message T_title = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.title"); + private static final Message T_trail = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.trail"); - public void addPageMeta(PageMeta pageMeta) throws WingException + private static final Message T_label_source = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.label_source"); + private static final Message T_source_normal = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_normal"); + private static final Message T_source_harvested = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_harvested"); + + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_submit_save = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.submit_save"); + + private static final Message T_main_settings_head = message("xmlui.administrative.collection.EditCollectionHarvestingForm.main_settings_head"); + private static final Message T_label_oai_provider = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_oai_provider"); + private static final Message T_label_setid = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_setid"); + private static final Message T_label_metadata_format = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_metadata_format"); + + private static final Message T_label_harvest_level = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_level"); + private static final Message T_label_harvest_result = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_result"); + private static final Message T_harvest_result_new = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_result_new"); + + private static final Message T_label_harvest_status = message("xmlui.administrative.collection.EditCollectionHarvestingForm.label_harvest_status"); + private static final Message T_harvest_status_ready = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_ready"); + private static final Message T_harvest_status_busy = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_busy"); + private static final Message T_harvest_status_queued = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_queued"); + private static final Message T_harvest_status_oai_error = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_oai_error"); + private static final Message T_harvest_status_unknown_error = message("xmlui.administrative.collection.EditCollectionHarvestingForm.harvest_status_unknown_error"); + + private static final Message T_option_md_only = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_only"); + private static final Message T_option_md_and_ref = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_and_ref"); + private static final Message T_option_md_and_bs = message("xmlui.administrative.collection.EditCollectionHarvestingForm.option_md_and_bs"); + + private static final Message T_submit_change_settings = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_change_settings"); + private static final Message T_submit_import_now = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_import_now"); + private static final Message T_submit_reimport_collection = message("xmlui.administrative.collection.EditCollectionHarvestingForm.submit_reimport_collection"); + + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected HarvestedCollectionService harvestedCollectionService = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); - Collection thisCollection = collectionService.find(context, collectionID); - HarvestedCollection hc = harvestedCollectionService.find(context, thisCollection); - - String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); - - String oaiProviderValue = hc.getOaiSource(); - String oaiSetIdValue = hc.getOaiSetId(); - String metadataFormatValue = hc.getHarvestMetadataConfig(); - int harvestLevelValue = hc.getHarvestType(); - int harvestStatusValue = hc.getHarvestStatus(); - - // DIVISION: main - Division main = body.addInteractiveDivision("collection-harvesting-edit",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); - main.setHead(T_main_head.parameterize(collectionService.getMetadata(thisCollection, "name"))); - - List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); - options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); - options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_harvesting",T_options_harvest); - options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); - - - // The top-level, all-setting, countent source radio button - List harvestSource = main.addList("harvestSource", "form"); - - harvestSource.addLabel(T_label_source); - Radio source = harvestSource.addItem().addRadio("source"); - source.addOption(false, "source_normal", T_source_normal); // was hc == null - always false - source.addOption(true, "source_harvested", T_source_harvested); // was hc != null - always true - - List settings = main.addList("harvestSettings", "form"); - settings.setHead(T_main_settings_head); - - settings.addLabel(T_label_oai_provider); - settings.addItem(oaiProviderValue); - - settings.addLabel(T_label_setid); - settings.addItem(oaiSetIdValue); - // The big complex way of getting to our metadata - settings.addLabel(T_label_metadata_format); - - String key = "oai.harvester.metadataformats." + metadataFormatValue; - String metadataString = (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key)); - String displayName; - if (metadataString.indexOf(',') != -1) + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); + Collection thisCollection = collectionService.find(context, collectionID); + HarvestedCollection hc = harvestedCollectionService.find(context, thisCollection); + + String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); + + String oaiProviderValue = hc.getOaiSource(); + String oaiSetIdValue = hc.getOaiSetId(); + String metadataFormatValue = hc.getHarvestMetadataConfig(); + int harvestLevelValue = hc.getHarvestType(); + int harvestStatusValue = hc.getHarvestStatus(); + + // DIVISION: main + Division main = body.addInteractiveDivision("collection-harvesting-edit", + contextPath+"/admin/collection", Division.METHOD_MULTIPART, + "primary administrative collection"); + main.setHead(T_main_head.parameterize(collectionService.getMetadata(thisCollection, "name"))); + + List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); + options.addItem().addXref(baseURL+"&submit_metadata", T_options_metadata); + options.addItem().addXref(baseURL+"&submit_roles", T_options_roles); + options.addItem().addHighlight("bold").addXref(baseURL+"&submit_harvesting", T_options_harvest); + options.addItem().addXref(baseURL+"&submit_curate", T_options_curate); + + + // The top-level, all-setting, countent source radio button + List harvestSource = main.addList("harvestSource", "form"); + + harvestSource.addLabel(T_label_source); + Radio source = harvestSource.addItem().addRadio("source"); + source.addOption(false, "source_normal", T_source_normal); // was hc == null - always false + source.addOption(true, "source_harvested", T_source_harvested); // was hc != null - always true + + List settings = main.addList("harvestSettings", "form"); + settings.setHead(T_main_settings_head); + + settings.addLabel(T_label_oai_provider); + settings.addItem(oaiProviderValue); + + settings.addLabel(T_label_setid); + settings.addItem(oaiSetIdValue); + + // The big complex way of getting to our metadata + settings.addLabel(T_label_metadata_format); + + String key = "oai.harvester.metadataformats." + metadataFormatValue; + String metadataString = (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key)); + + String displayName; + if (metadataString.indexOf(',') != -1) { displayName = metadataString.substring(metadataString.indexOf(',') + 1); } - else + else { displayName = metadataFormatValue + "(" + metadataString + ")"; } - - settings.addItem(displayName); - - settings.addLabel(T_label_harvest_level); - Item harvestLevel = settings.addItem(); - switch (harvestLevelValue) { - case HarvestedCollection.TYPE_DMD: harvestLevel.addContent(T_option_md_only); break; - case HarvestedCollection.TYPE_DMDREF: harvestLevel.addContent(T_option_md_and_ref); break; - default: harvestLevel.addContent(T_option_md_and_bs); break; - } - + + settings.addItem(displayName); + + settings.addLabel(T_label_harvest_level); + Item harvestLevel = settings.addItem(); + switch (harvestLevelValue) + { + case HarvestedCollection.TYPE_DMD: harvestLevel.addContent(T_option_md_only); break; + case HarvestedCollection.TYPE_DMDREF: harvestLevel.addContent(T_option_md_and_ref); break; + default: harvestLevel.addContent(T_option_md_and_bs); break; + } + /* Results of the last harvesting cycle */ if (harvestLevelValue > 0) { - settings.addLabel(T_label_harvest_result); - Item harvestResult = settings.addItem(); - if (hc.getHarvestMessage() != null) { - harvestResult.addContent(hc.getHarvestMessage() + " on " + hc.getHarvestStartTime()); - } - else { - harvestResult.addContent(T_harvest_result_new); - } + settings.addLabel(T_label_harvest_result); + Item harvestResult = settings.addItem(); + if (hc.getHarvestMessage() != null) { + harvestResult.addContent(hc.getHarvestMessage() + " on " + hc.getHarvestStartTime()); + } + else + { + harvestResult.addContent(T_harvest_result_new); + } } - + /* Current status */ settings.addLabel(T_label_harvest_status); - Item harvestStatus = settings.addItem(); - switch(harvestStatusValue) { - case HarvestedCollection.STATUS_READY: harvestStatus.addContent(T_harvest_status_ready); break; - case HarvestedCollection.STATUS_BUSY: harvestStatus.addContent(T_harvest_status_busy); break; - case HarvestedCollection.STATUS_QUEUED: harvestStatus.addContent(T_harvest_status_queued); break; - case HarvestedCollection.STATUS_OAI_ERROR: harvestStatus.addContent(T_harvest_status_oai_error); break; - case HarvestedCollection.STATUS_UNKNOWN_ERROR: harvestStatus.addContent(T_harvest_status_unknown_error); break; + Item harvestStatus = settings.addItem(); + switch (harvestStatusValue) + { + case HarvestedCollection.STATUS_READY: harvestStatus.addContent(T_harvest_status_ready); break; + case HarvestedCollection.STATUS_BUSY: harvestStatus.addContent(T_harvest_status_busy); break; + case HarvestedCollection.STATUS_QUEUED: harvestStatus.addContent(T_harvest_status_queued); break; + case HarvestedCollection.STATUS_OAI_ERROR: harvestStatus.addContent(T_harvest_status_oai_error); break; + case HarvestedCollection.STATUS_UNKNOWN_ERROR: harvestStatus.addContent(T_harvest_status_unknown_error); break; } - + settings.addLabel(); - Item harvestButtons = settings.addItem(); - harvestButtons.addButton("submit_change").setValue(T_submit_change_settings); - harvestButtons.addButton("submit_import_now").setValue(T_submit_import_now); - harvestButtons.addButton("submit_reimport").setValue(T_submit_reimport_collection); - - Para buttonList = main.addPara(); - buttonList.addButton("submit_save").setValue(T_submit_save); - buttonList.addButton("submit_return").setValue(T_submit_return); - - main.addHidden("administrative-continue").setValue(knot.getId()); + Item harvestButtons = settings.addItem(); + harvestButtons.addButton("submit_change").setValue(T_submit_change_settings); + harvestButtons.addButton("submit_import_now").setValue(T_submit_import_now); + harvestButtons.addButton("submit_reimport").setValue(T_submit_reimport_collection); + + Para buttonList = main.addPara(); + buttonList.addButton("submit_save").setValue(T_submit_save); + buttonList.addButton("submit_return").setValue(T_submit_return); + + main.addHidden("administrative-continue").setValue(knot.getId()); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/SetupCollectionHarvestingForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/SetupCollectionHarvestingForm.java index f7f81f6396..7e4ad0c8d5 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/SetupCollectionHarvestingForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/collection/SetupCollectionHarvestingForm.java @@ -35,232 +35,241 @@ import org.dspace.harvest.service.HarvestedCollectionService; * form to edit that collection's metadata, logo, and item template. * @author Alexey Maslov */ -public class SetupCollectionHarvestingForm extends AbstractDSpaceTransformer +public class SetupCollectionHarvestingForm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - - private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); - private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); - private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); - private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); - private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); - - private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); - private static final Message T_title = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.title"); - private static final Message T_trail = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.trail"); - - private static final Message T_label_source = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.label_source"); - private static final Message T_source_normal = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_normal"); - private static final Message T_source_harvested = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_harvested"); + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_submit_save = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.submit_save"); - - private static final Message T_main_settings_head = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.main_settings_head"); - private static final Message T_options_head = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.options_head"); - - private static final Message T_label_oai_provider = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_oai_provider"); - private static final Message T_label_setid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_setid"); - private static final Message T_label_metadata_format = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_metadata_format"); - - private static final Message T_help_oaiurl = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.help_oaiurl"); - private static final Message T_error_oaiurl = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.error_oaiurl"); - private static final Message T_help_oaisetid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.help_oaisetid"); - private static final Message T_error_oaisetid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.error_oaisetid"); - - private static final Message T_label_harvest_level = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_harvest_level"); - - private static final Message T_option_md_only = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_only"); - private static final Message T_option_md_and_ref = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_and_ref"); - private static final Message T_option_md_and_bs = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_and_bs"); + private static final Message T_collection_trail = message("xmlui.administrative.collection.general.collection_trail"); + private static final Message T_options_metadata = message("xmlui.administrative.collection.general.options_metadata"); + private static final Message T_options_roles = message("xmlui.administrative.collection.general.options_roles"); + private static final Message T_options_curate = message("xmlui.administrative.collection.general.options_curate"); + private static final Message T_main_head = message("xmlui.administrative.collection.EditCollectionMetadataForm.main_head"); - private static final Message T_submit_test = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.submit_test"); + private static final Message T_options_harvest = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.options_harvest"); + private static final Message T_title = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.title"); + private static final Message T_trail = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.trail"); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected HarvestedCollectionService harvestedCollectionService = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); + private static final Message T_label_source = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.label_source"); + private static final Message T_source_normal = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_normal"); + private static final Message T_source_harvested = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.source_harvested"); - - public void addPageMeta(PageMeta pageMeta) throws WingException + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_submit_save = message("xmlui.administrative.collection.GeneralCollectionHarvestingForm.submit_save"); + + private static final Message T_main_settings_head = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.main_settings_head"); + private static final Message T_options_head = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.options_head"); + + private static final Message T_label_oai_provider = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_oai_provider"); + private static final Message T_label_setid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_setid"); + private static final Message T_label_metadata_format = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_metadata_format"); + + private static final Message T_help_oaiurl = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.help_oaiurl"); + private static final Message T_error_oaiurl = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.error_oaiurl"); + private static final Message T_help_oaisetid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.help_oaisetid"); + private static final Message T_error_oaisetid = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.error_oaisetid"); + + private static final Message T_label_harvest_level = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.label_harvest_level"); + + private static final Message T_option_md_only = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_only"); + private static final Message T_option_md_and_ref = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_and_ref"); + private static final Message T_option_md_and_bs = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.option_md_and_bs"); + + private static final Message T_submit_test = message("xmlui.administrative.collection.SetupCollectionHarvestingForm.submit_test"); + + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected HarvestedCollectionService harvestedCollectionService = HarvestServiceFactory.getInstance().getHarvestedCollectionService(); + + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_collection_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); - Collection thisCollection = collectionService.find(context, collectionID); - Request request = ObjectModelHelper.getRequest(objectModel); - - HarvestedCollection hc = harvestedCollectionService.find(context, thisCollection); - String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); - - String errorString = parameters.getParameter("errors",null); - String[] errors = errorString.split(","); - HashMap errorMap = new HashMap(); - for (String error : errors) { - //System.out.println(errorString); - String[] errorPieces = error.split(":",2); - - if (errorPieces.length > 1) + + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); + Collection thisCollection = collectionService.find(context, collectionID); + Request request = ObjectModelHelper.getRequest(objectModel); + + HarvestedCollection hc = harvestedCollectionService.find(context, thisCollection); + String baseURL = contextPath + "/admin/collection?administrative-continue=" + knot.getId(); + + String errorString = parameters.getParameter("errors",null); + String[] errors = errorString.split(","); + HashMap errorMap = new HashMap(); + for (String error : errors) { + //System.out.println(errorString); + String[] errorPieces = error.split(":",2); + + if (errorPieces.length > 1) { errorMap.put(errorPieces[0], errorPieces[1]); } - else + else { errorMap.put(errorPieces[0], errorPieces[0]); } - } - - - String oaiProviderValue; - String oaiSetIdValue; - String metadataFormatValue; - int harvestLevelValue; - - if (hc != null && request.getParameter("submit_test") == null) { - oaiProviderValue = hc.getOaiSource(); - oaiSetIdValue = hc.getOaiSetId(); - metadataFormatValue = hc.getHarvestMetadataConfig(); - harvestLevelValue = hc.getHarvestType(); - } - else { - oaiProviderValue = parameters.getParameter("oaiProviderValue", ""); - oaiSetIdValue = parameters.getParameter("oaiSetAll", ""); - if(!"all".equals(oaiSetIdValue)) + } + + String oaiProviderValue; + String oaiSetIdValue; + String metadataFormatValue; + int harvestLevelValue; + + if (hc != null && request.getParameter("submit_test") == null) + { + oaiProviderValue = hc.getOaiSource(); + oaiSetIdValue = hc.getOaiSetId(); + metadataFormatValue = hc.getHarvestMetadataConfig(); + harvestLevelValue = hc.getHarvestType(); + } + else + { + oaiProviderValue = parameters.getParameter("oaiProviderValue", ""); + oaiSetIdValue = parameters.getParameter("oaiSetAll", ""); + if (!"all".equals(oaiSetIdValue)) { oaiSetIdValue = parameters.getParameter("oaiSetIdValue", null); } - metadataFormatValue = parameters.getParameter("metadataFormatValue", ""); - String harvestLevelString = parameters.getParameter("harvestLevelValue","0"); - if (harvestLevelString.length() == 0) + metadataFormatValue = parameters.getParameter("metadataFormatValue", ""); + String harvestLevelString = parameters.getParameter("harvestLevelValue","0"); + if (harvestLevelString.length() == 0) { harvestLevelValue = 0; } - else + else { harvestLevelValue = Integer.parseInt(harvestLevelString); } - } - - // DIVISION: main - Division main = body.addInteractiveDivision("collection-harvesting-setup",contextPath+"/admin/collection",Division.METHOD_MULTIPART,"primary administrative collection"); - main.setHead(T_main_head.parameterize(thisCollection.getName())); - - List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); - options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); - options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_harvesting",T_options_harvest); - options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); - - - // The top-level, all-setting, countent source radio button - List harvestSource = main.addList("harvestSource", "form"); - - harvestSource.addLabel(T_label_source); - Radio source = harvestSource.addItem().addRadio("source"); - source.addOption(hc == null || harvestLevelValue == -1, "source_normal", T_source_normal); - source.addOption(hc != null, "source_harvested", T_source_harvested); - - List settings = main.addList("harvestSettings", "form"); - settings.setHead(T_main_settings_head); - - settings.addLabel(T_label_oai_provider); - Text oaiProvider = settings.addItem().addText("oai_provider"); - oaiProvider.setSize(40); - oaiProvider.setValue(oaiProviderValue); - oaiProvider.setHelp(T_help_oaiurl); - - if (errorMap.containsKey(OAIHarvester.OAI_ADDRESS_ERROR)) { - oaiProvider.addError(errorMap.get(OAIHarvester.OAI_ADDRESS_ERROR)); - } - if (errorMap.containsKey("oai_provider")) { - oaiProvider.addError(T_error_oaiurl); - //oaiProvider.addError("You must provide a set id of the target collection."); - } - - settings.addLabel(T_label_setid); + } + + // DIVISION: main + Division main = body.addInteractiveDivision("collection-harvesting-setup", + contextPath + "/admin/collection", Division.METHOD_MULTIPART, + "primary administrative collection"); + main.setHead(T_main_head.parameterize(thisCollection.getName())); + + List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); + options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); + options.addItem().addXref(baseURL+"&submit_roles",T_options_roles); + options.addItem().addHighlight("bold").addXref(baseURL+"&submit_harvesting",T_options_harvest); + options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); + + + // The top-level, all-setting, countent source radio button + List harvestSource = main.addList("harvestSource", "form"); + + harvestSource.addLabel(T_label_source); + Radio source = harvestSource.addItem().addRadio("source"); + source.addOption(hc == null || harvestLevelValue == -1, "source_normal", T_source_normal); + source.addOption(hc != null, "source_harvested", T_source_harvested); + + List settings = main.addList("harvestSettings", "form"); + settings.setHead(T_main_settings_head); + + settings.addLabel(T_label_oai_provider); + Text oaiProvider = settings.addItem().addText("oai_provider"); + oaiProvider.setSize(40); + oaiProvider.setValue(oaiProviderValue); + oaiProvider.setHelp(T_help_oaiurl); + + if (errorMap.containsKey(OAIHarvester.OAI_ADDRESS_ERROR)) + { + oaiProvider.addError(errorMap.get(OAIHarvester.OAI_ADDRESS_ERROR)); + } + if (errorMap.containsKey("oai_provider")) + { + oaiProvider.addError(T_error_oaiurl); + //oaiProvider.addError("You must provide a set id of the target collection."); + } + + settings.addLabel(T_label_setid); Composite oaiSetComp = settings.addItem().addComposite("oai-set-comp"); Radio oaiSetSettingRadio = oaiSetComp.addRadio("oai-set-setting"); oaiSetSettingRadio.addOption("all".equals(oaiSetIdValue) || oaiSetIdValue == null, "all", "All sets"); oaiSetSettingRadio.addOption(!"all".equals(oaiSetIdValue) && oaiSetIdValue != null, "specific", "Specific sets"); Text oaiSetId = oaiSetComp.addText("oai_setid"); - oaiSetId.setSize(40); - if(!"all".equals(oaiSetIdValue) && oaiSetIdValue != null) + oaiSetId.setSize(40); + if (!"all".equals(oaiSetIdValue) && oaiSetIdValue != null) { oaiSetId.setValue(oaiSetIdValue); } - oaiSetId.setHelp(T_help_oaisetid); - if (errorMap.containsKey(OAIHarvester.OAI_SET_ERROR)) { - oaiSetId.addError(errorMap.get(OAIHarvester.OAI_SET_ERROR)); - } - if (errorMap.containsKey("oai_setid")) { - oaiSetId.addError(T_error_oaisetid); - } - - settings.addLabel(T_label_metadata_format); - Select metadataFormat = settings.addItem().addSelect("metadata_format"); - if (errorMap.containsKey(OAIHarvester.OAI_ORE_ERROR)) { - metadataFormat.addError(errorMap.get(OAIHarvester.OAI_ORE_ERROR)); - } - if (errorMap.containsKey(OAIHarvester.OAI_DMD_ERROR)) { - metadataFormat.addError(errorMap.get(OAIHarvester.OAI_DMD_ERROR)); - } - - - // Add an entry for each instance of ingestion crosswalks configured for harvesting + oaiSetId.setHelp(T_help_oaisetid); + if (errorMap.containsKey(OAIHarvester.OAI_SET_ERROR)) + { + oaiSetId.addError(errorMap.get(OAIHarvester.OAI_SET_ERROR)); + } + if (errorMap.containsKey("oai_setid")) + { + oaiSetId.addError(T_error_oaisetid); + } + + settings.addLabel(T_label_metadata_format); + Select metadataFormat = settings.addItem().addSelect("metadata_format"); + if (errorMap.containsKey(OAIHarvester.OAI_ORE_ERROR)) + { + metadataFormat.addError(errorMap.get(OAIHarvester.OAI_ORE_ERROR)); + } + if (errorMap.containsKey(OAIHarvester.OAI_DMD_ERROR)) + { + metadataFormat.addError(errorMap.get(OAIHarvester.OAI_DMD_ERROR)); + } + + + // Add an entry for each instance of ingestion crosswalks configured for harvesting String metaString = "oai.harvester.metadataformats."; Enumeration pe = Collections.enumeration(DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyKeys("oai")); while (pe.hasMoreElements()) { String key = (String)pe.nextElement(); - if (key.startsWith(metaString)) { - String metadataString = (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key)); - String metadataKey = key.substring(metaString.length()); - String displayName; + if (key.startsWith(metaString)) + { + String metadataString = (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key)); + String metadataKey = key.substring(metaString.length()); + String displayName; - if (metadataString.indexOf(',') != -1) + if (metadataString.indexOf(',') != -1) { displayName = metadataString.substring(metadataString.indexOf(',') + 1); } - else + else { displayName = metadataKey + "(" + metadataString + ")"; } - - metadataFormat.addOption(metadataKey.equalsIgnoreCase(metadataFormatValue), metadataKey, displayName); + + metadataFormat.addOption(metadataKey.equalsIgnoreCase(metadataFormatValue), metadataKey, displayName); } } - - + settings.addLabel(); - Item harvestButtons = settings.addItem(); - harvestButtons.addButton("submit_test").setValue(T_submit_test); - - // Various non-critical harvesting options - //Division optionsDiv = main.addDivision("collection-harvesting-options","secondary"); - //optionsDiv.setHead(T_options_head); - - List harvestOptions = main.addList("harvestOptions", "form"); - harvestOptions.setHead(T_options_head); - - harvestOptions.addLabel(T_label_harvest_level); - Radio harvestLevel = harvestOptions.addItem().addRadio("harvest_level"); - harvestLevel.addOption(harvestLevelValue == 1, 1, T_option_md_only); - harvestLevel.addOption(harvestLevelValue == 2, 2, T_option_md_and_ref); - harvestLevel.addOption(harvestLevelValue != 1 && harvestLevelValue != 2, 3, T_option_md_and_bs); - - Para buttonList = main.addPara(); - buttonList.addButton("submit_save").setValue(T_submit_save); - buttonList.addButton("submit_return").setValue(T_submit_return); - - main.addHidden("administrative-continue").setValue(knot.getId()); + Item harvestButtons = settings.addItem(); + harvestButtons.addButton("submit_test").setValue(T_submit_test); + + // Various non-critical harvesting options + //Division optionsDiv = main.addDivision("collection-harvesting-options","secondary"); + //optionsDiv.setHead(T_options_head); + + List harvestOptions = main.addList("harvestOptions", "form"); + harvestOptions.setHead(T_options_head); + + harvestOptions.addLabel(T_label_harvest_level); + Radio harvestLevel = harvestOptions.addItem().addRadio("harvest_level"); + harvestLevel.addOption(harvestLevelValue == 1, 1, T_option_md_only); + harvestLevel.addOption(harvestLevelValue == 2, 2, T_option_md_and_ref); + harvestLevel.addOption(harvestLevelValue != 1 && harvestLevelValue != 2, 3, T_option_md_and_bs); + + Para buttonList = main.addPara(); + buttonList.addButton("submit_save").setValue(T_submit_save); + buttonList.addButton("submit_return").setValue(T_submit_return); + + main.addHidden("administrative-continue").setValue(knot.getId()); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/community/AssignCommunityRoles.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/community/AssignCommunityRoles.java index 15d9b0ac2f..045eb57175 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/community/AssignCommunityRoles.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/community/AssignCommunityRoles.java @@ -39,154 +39,160 @@ import org.dspace.eperson.Group; * @author Alexey Maslov * @author Nicholas Riley */ -public class AssignCommunityRoles extends AbstractDSpaceTransformer +public class AssignCommunityRoles extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - - private static final Message T_community_trail = message("xmlui.administrative.community.general.community_trail"); - private static final Message T_options_metadata = message("xmlui.administrative.community.general.options_metadata"); - private static final Message T_options_roles = message("xmlui.administrative.community.general.options_roles"); - private static final Message T_options_curate = message("xmlui.administrative.community.general.options_curate"); - - private static final Message T_submit_return = message("xmlui.general.return"); - - private static final Message T_title = message("xmlui.administrative.community.AssignCommunityRoles.title"); - private static final Message T_trail = message("xmlui.administrative.community.AssignCommunityRoles.trail"); + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_main_head = message("xmlui.administrative.community.AssignCommunityRoles.main_head"); - private static final Message T_no_role = message("xmlui.administrative.community.AssignCommunityRoles.no_role"); - - private static final Message T_create = message("xmlui.administrative.community.AssignCommunityRoles.create"); - private static final Message T_delete = message("xmlui.general.delete"); + private static final Message T_community_trail = message("xmlui.administrative.community.general.community_trail"); + private static final Message T_options_metadata = message("xmlui.administrative.community.general.options_metadata"); + private static final Message T_options_roles = message("xmlui.administrative.community.general.options_roles"); + private static final Message T_options_curate = message("xmlui.administrative.community.general.options_curate"); - private static final Message T_help_admins = message("xmlui.administrative.community.AssignCommunityRoles.help_admins"); + private static final Message T_submit_return = message("xmlui.general.return"); + + private static final Message T_title = message("xmlui.administrative.community.AssignCommunityRoles.title"); + private static final Message T_trail = message("xmlui.administrative.community.AssignCommunityRoles.trail"); + + private static final Message T_main_head = message("xmlui.administrative.community.AssignCommunityRoles.main_head"); + private static final Message T_no_role = message("xmlui.administrative.community.AssignCommunityRoles.no_role"); + + private static final Message T_create = message("xmlui.administrative.community.AssignCommunityRoles.create"); + private static final Message T_delete = message("xmlui.general.delete"); + + private static final Message T_help_admins = message("xmlui.administrative.community.AssignCommunityRoles.help_admins"); private static final Message T_edit_authorizations = message("xmlui.administrative.community.EditCommunityMetadataForm.edit_authorizations"); - private static final Message T_role_name = message("xmlui.administrative.community.AssignCommunityRoles.role_name"); - private static final Message T_role_group = message("xmlui.administrative.community.AssignCommunityRoles.role_group"); - private static final Message T_role_buttons = message("xmlui.administrative.community.AssignCommunityRoles.role_buttons"); + private static final Message T_role_name = message("xmlui.administrative.community.AssignCommunityRoles.role_name"); + private static final Message T_role_group = message("xmlui.administrative.community.AssignCommunityRoles.role_group"); + private static final Message T_role_buttons = message("xmlui.administrative.community.AssignCommunityRoles.role_buttons"); - private static final Message T_label_admins = message("xmlui.administrative.community.AssignCommunityRoles.label_admins"); - - private static final Message T_sysadmins_only = message("xmlui.administrative.community.AssignCommunityRoles.sysadmins_only"); + private static final Message T_label_admins = message("xmlui.administrative.community.AssignCommunityRoles.label_admins"); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + private static final Message T_sysadmins_only = message("xmlui.administrative.community.AssignCommunityRoles.sysadmins_only"); - public void addPageMeta(PageMeta pageMeta) throws WingException + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrail().addContent(T_community_trail); pageMeta.addTrail().addContent(T_trail); } - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { UUID communityID = UUID.fromString(parameters.getParameter("communityID", null)); Community thisCommunity = communityService.find(context, communityID); - - String baseURL = contextPath + "/admin/community?administrative-continue=" + knot.getId(); - - Group admins = thisCommunity.getAdministrators(); - // DIVISION: main - Division main = body.addInteractiveDivision("community-assign-roles",contextPath+"/admin/community",Division.METHOD_POST,"primary administrative community"); + String baseURL = contextPath + "/admin/community?administrative-continue=" + knot.getId(); + + Group admins = thisCommunity.getAdministrators(); + + // DIVISION: main + Division main = body.addInteractiveDivision("community-assign-roles", + contextPath+"/admin/community", Division.METHOD_POST, + "primary administrative community"); main.setHead(T_main_head.parameterize(thisCommunity.getName())); - - List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); - options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_roles",T_options_roles); - options.addItem().addXref(baseURL+"&submit_curate",T_options_curate); - // The table of admin roles - Table rolesTable = main.addTable("roles-table", 6, 5); - Row tableRow; - - // The header row - Row tableHeader = rolesTable.addRow(Row.ROLE_HEADER); - tableHeader.addCell().addContent(T_role_name); - tableHeader.addCell().addContent(T_role_group); - tableHeader.addCell().addContent(T_role_buttons); - rolesTable.addRow(); - - /* - * The community admins - */ - // data row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_admins); - if (admins != null) - { - try - { - AuthorizeUtil.authorizeManageAdminGroup(context, thisCommunity); - tableRow.addCell().addXref(baseURL + "&submit_edit_admin", admins.getName()); - } - catch (AuthorizeException authex) { - // add a notice, the user is not authorized to create/edit community's admin group - tableRow.addCell().addContent(T_sysadmins_only); - } - try - { - AuthorizeUtil.authorizeRemoveAdminGroup(context, thisCommunity); - tableRow.addCell().addButton("submit_delete_admin").setValue(T_delete); - } - catch (AuthorizeException authex) - { - // nothing to add, the user is not allowed to delete the group - } - } - else - { - tableRow.addCell().addContent(T_no_role); - Cell commAdminCell = tableRow.addCell(); - try + List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); + options.addItem().addXref(baseURL+"&submit_metadata",T_options_metadata); + options.addItem().addHighlight("bold").addXref( + baseURL + "&submit_roles", T_options_roles); + options.addItem().addXref(baseURL + "&submit_curate", T_options_curate); + + // The table of admin roles + Table rolesTable = main.addTable("roles-table", 6, 5); + Row tableRow; + + // The header row + Row tableHeader = rolesTable.addRow(Row.ROLE_HEADER); + tableHeader.addCell().addContent(T_role_name); + tableHeader.addCell().addContent(T_role_group); + tableHeader.addCell().addContent(T_role_buttons); + rolesTable.addRow(); + + /* + * The community admins + */ + // data row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(Cell.ROLE_HEADER).addContent(T_label_admins); + if (admins != null) + { + try + { + AuthorizeUtil.authorizeManageAdminGroup(context, thisCommunity); + tableRow.addCell().addXref(baseURL + "&submit_edit_admin", admins.getName()); + } + catch (AuthorizeException authex) { + // add a notice, the user is not authorized to create/edit community's admin group + tableRow.addCell().addContent(T_sysadmins_only); + } + try + { + AuthorizeUtil.authorizeRemoveAdminGroup(context, thisCommunity); + tableRow.addCell().addButton("submit_delete_admin").setValue(T_delete); + } + catch (AuthorizeException authex) + { + // nothing to add, the user is not allowed to delete the group + } + } + else + { + tableRow.addCell().addContent(T_no_role); + Cell commAdminCell = tableRow.addCell(); + try { AuthorizeUtil.authorizeManageAdminGroup(context, thisCommunity); commAdminCell.addButton("submit_create_admin").setValue(T_create); } - catch (AuthorizeException authex) + catch (AuthorizeException authex) { // add a notice, the user is not authorized to create/edit community's admin group addAdministratorOnlyButton(commAdminCell, "submit_create_admin", T_create); - } - } - // help and directions row - tableRow = rolesTable.addRow(Row.ROLE_DATA); - tableRow.addCell(); - tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_admins); - - try - { - AuthorizeUtil.authorizeManageCommunityPolicy(context, thisCommunity); - // add one last link to edit the raw authorizations - Cell authCell =rolesTable.addRow().addCell(1,3); - authCell.addXref(baseURL + "&submit_authorizations", T_edit_authorizations); - } - catch (AuthorizeException authex) { - // nothing to add, the user is not authorized to manage community's policies - } + } + } + // help and directions row + tableRow = rolesTable.addRow(Row.ROLE_DATA); + tableRow.addCell(); + tableRow.addCell(1,2).addHighlight("fade offset").addContent(T_help_admins); + + try + { + AuthorizeUtil.authorizeManageCommunityPolicy(context, thisCommunity); + // add one last link to edit the raw authorizations + Cell authCell = rolesTable.addRow().addCell(1,3); + authCell.addXref(baseURL + "&submit_authorizations", T_edit_authorizations); + } + catch (AuthorizeException authex) { + // nothing to add, the user is not authorized to manage community's policies + } + + Para buttonList = main.addPara(); + buttonList.addButton("submit_return").setValue(T_submit_return); + + main.addHidden("administrative-continue").setValue(knot.getId()); - Para buttonList = main.addPara(); - buttonList.addButton("submit_return").setValue(T_submit_return); - - main.addHidden("administrative-continue").setValue(knot.getId()); - } - - - private void addAdministratorOnlyButton(Cell cell, String buttonName, Message buttonLabel) throws WingException, SQLException - { - Button button = cell.addButton(buttonName); - button.setValue(buttonLabel); - if (!authorizeService.isAdmin(context)) - { - // Only admins can create or delete - button.setDisabled(); - cell.addHighlight("fade").addContent(T_sysadmins_only); - } - } + + + private void addAdministratorOnlyButton(Cell cell, String buttonName, Message buttonLabel) + throws WingException, SQLException + { + Button button = cell.addButton(buttonName); + button.setValue(buttonLabel); + if (!authorizeService.isAdmin(context)) + { + // Only admins can create or delete + button.setDisabled(); + cell.addHighlight("fade").addContent(T_sysadmins_only); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/AbstractControlPanelTab.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/AbstractControlPanelTab.java index 545eb4d054..d5ec083c02 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/AbstractControlPanelTab.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/AbstractControlPanelTab.java @@ -23,8 +23,8 @@ import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; */ public abstract class AbstractControlPanelTab extends AbstractDSpaceTransformer implements Serviceable, Disposable, ControlPanelTab { - /** - * The service manager allows us to access the continuation's + /** + * The service manager allows us to access the continuation's * manager. It is obtained from the Serviceable API */ protected ServiceManager serviceManager; @@ -48,36 +48,44 @@ public abstract class AbstractControlPanelTab extends AbstractDSpaceTransformer * The Cocoon Persistent Store (used for cache statistics) */ protected Store storePersistent; - - + + /** * Link of the tab */ protected String web_link; - - - @Override - public void service(ServiceManager serviceManager) throws ServiceException { + + + @Override + public void service(ServiceManager serviceManager) + throws ServiceException + { this.serviceManager = serviceManager; - + this.settings = (Settings) this.serviceManager.lookup(Settings.ROLE); - - if(this.serviceManager.hasService(StoreJanitor.ROLE)) + + if (this.serviceManager.hasService(StoreJanitor.ROLE)) + { this.storeJanitor = (StoreJanitor) this.serviceManager.lookup(StoreJanitor.ROLE); - + } + if (this.serviceManager.hasService(Store.ROLE)) + { this.storeDefault = (Store) this.serviceManager.lookup(Store.ROLE); - - if(this.serviceManager.hasService(Store.PERSISTENT_STORE)) + } + + if (this.serviceManager.hasService(Store.PERSISTENT_STORE)) + { this.storePersistent = (Store) this.serviceManager.lookup(Store.PERSISTENT_STORE); - } - + } + } + /** * Release all Cocoon resources. * @see org.apache.avalon.framework.activity.Disposable#dispose() */ @Override - public void dispose() + public void dispose() { if (this.serviceManager != null) { @@ -86,7 +94,7 @@ public abstract class AbstractControlPanelTab extends AbstractDSpaceTransformer this.serviceManager.release(this.storeDefault); this.serviceManager.release(this.settings); this.storePersistent = null; - this.storeJanitor = null; + this.storeJanitor = null; this.storeDefault = null; this.settings = null; } @@ -94,8 +102,7 @@ public abstract class AbstractControlPanelTab extends AbstractDSpaceTransformer } public void setWebLink(String web_link) { - this.web_link = web_link; + this.web_link = web_link; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelAlertsTab.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelAlertsTab.java index 7df48c4e36..0177a8381f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelAlertsTab.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelAlertsTab.java @@ -25,79 +25,85 @@ import org.dspace.app.xmlui.wing.element.TextArea; */ public class ControlPanelAlertsTab extends AbstractControlPanelTab { - private static final Message T_alerts_head = message("xmlui.administrative.ControlPanel.alerts_head"); - private static final Message T_alerts_warning = message("xmlui.administrative.ControlPanel.alerts_warning"); - private static final Message T_alerts_message_label = message("xmlui.administrative.ControlPanel.alerts_message_label"); - private static final Message T_alerts_message_default = message("xmlui.administrative.ControlPanel.alerts_message_default"); - private static final Message T_alerts_countdown_label = message("xmlui.administrative.ControlPanel.alerts_countdown_label"); - private static final Message T_alerts_countdown_none = message("xmlui.administrative.ControlPanel.alerts_countdown_none"); - private static final Message T_alerts_countdown_5 = message("xmlui.administrative.ControlPanel.alerts_countdown_5"); - private static final Message T_alerts_countdown_15 = message("xmlui.administrative.ControlPanel.alerts_countdown_15"); - private static final Message T_alerts_countdown_30 = message("xmlui.administrative.ControlPanel.alerts_countdown_30"); - private static final Message T_alerts_countdown_60 = message("xmlui.administrative.ControlPanel.alerts_countdown_60"); - private static final Message T_alerts_countdown_keep = message("xmlui.administrative.ControlPanel.alerts_countdown_keep"); - private static final Message T_alerts_session_label = message("xmlui.administrative.ControlPanel.alerts_session_label"); - private static final Message T_alerts_session_all_sessions = message("xmlui.administrative.ControlPanel.alerts_session_all_sessions"); - private static final Message T_alerts_session_current_sessions = message("xmlui.administrative.ControlPanel.alerts_session_current_sessions"); - private static final Message T_alerts_session_only_administrative = message("xmlui.administrative.ControlPanel.alerts_session_only_administrative_sessions"); - private static final Message T_alerts_session_note = message("xmlui.administrative.ControlPanel.alerts_session_note"); - private static final Message T_alerts_submit_activate = message("xmlui.administrative.ControlPanel.alerts_submit_activate"); - private static final Message T_alerts_submit_deactivate = message("xmlui.administrative.ControlPanel.alerts_submit_deactivate"); + private static final Message T_alerts_head = message("xmlui.administrative.ControlPanel.alerts_head"); + private static final Message T_alerts_warning = message("xmlui.administrative.ControlPanel.alerts_warning"); + private static final Message T_alerts_message_label = message("xmlui.administrative.ControlPanel.alerts_message_label"); + private static final Message T_alerts_message_default = message("xmlui.administrative.ControlPanel.alerts_message_default"); + private static final Message T_alerts_countdown_label = message("xmlui.administrative.ControlPanel.alerts_countdown_label"); + private static final Message T_alerts_countdown_none = message("xmlui.administrative.ControlPanel.alerts_countdown_none"); + private static final Message T_alerts_countdown_5 = message("xmlui.administrative.ControlPanel.alerts_countdown_5"); + private static final Message T_alerts_countdown_15 = message("xmlui.administrative.ControlPanel.alerts_countdown_15"); + private static final Message T_alerts_countdown_30 = message("xmlui.administrative.ControlPanel.alerts_countdown_30"); + private static final Message T_alerts_countdown_60 = message("xmlui.administrative.ControlPanel.alerts_countdown_60"); + private static final Message T_alerts_countdown_keep = message("xmlui.administrative.ControlPanel.alerts_countdown_keep"); + private static final Message T_alerts_session_label = message("xmlui.administrative.ControlPanel.alerts_session_label"); + private static final Message T_alerts_session_all_sessions = message("xmlui.administrative.ControlPanel.alerts_session_all_sessions"); + private static final Message T_alerts_session_current_sessions = message("xmlui.administrative.ControlPanel.alerts_session_current_sessions"); + private static final Message T_alerts_session_only_administrative = message("xmlui.administrative.ControlPanel.alerts_session_only_administrative_sessions"); + private static final Message T_alerts_session_note = message("xmlui.administrative.ControlPanel.alerts_session_note"); + private static final Message T_alerts_submit_activate = message("xmlui.administrative.ControlPanel.alerts_submit_activate"); + private static final Message T_alerts_submit_deactivate = message("xmlui.administrative.ControlPanel.alerts_submit_deactivate"); - @Override - public void addBody(Map objectModel, Division div) throws WingException { - List form = div.addList("system-wide-alerts", List.TYPE_FORM); - form.setHead(T_alerts_head); + @Override + public void addBody(Map objectModel, Division div) + throws WingException + { + List form = div.addList("system-wide-alerts", List.TYPE_FORM); + form.setHead(T_alerts_head); - form.addItem(T_alerts_warning); + form.addItem(T_alerts_warning); - TextArea message = form.addItem().addTextArea("message"); - message.setAutofocus("autofocus"); - message.setLabel(T_alerts_message_label); - message.setSize(5, 45); - if (SystemwideAlerts.getMessage() == null) { - message.setValue(T_alerts_message_default); - } else { - message.setValue(SystemwideAlerts.getMessage()); - } + TextArea message = form.addItem().addTextArea("message"); + message.setAutofocus("autofocus"); + message.setLabel(T_alerts_message_label); + message.setSize(5, 45); + if (SystemwideAlerts.getMessage() == null) + { + message.setValue(T_alerts_message_default); + } + else + { + message.setValue(SystemwideAlerts.getMessage()); + } - Select countdown = form.addItem().addSelect("countdown"); - countdown.setLabel(T_alerts_countdown_label); + Select countdown = form.addItem().addSelect("countdown"); + countdown.setLabel(T_alerts_countdown_label); - countdown.addOption(0, T_alerts_countdown_none); - countdown.addOption(5, T_alerts_countdown_5); - countdown.addOption(15, T_alerts_countdown_15); - countdown.addOption(30, T_alerts_countdown_30); - countdown.addOption(60, T_alerts_countdown_60); + countdown.addOption(0, T_alerts_countdown_none); + countdown.addOption(5, T_alerts_countdown_5); + countdown.addOption(15, T_alerts_countdown_15); + countdown.addOption(30, T_alerts_countdown_30); + countdown.addOption(60, T_alerts_countdown_60); - // Is there a current count down active? - if (SystemwideAlerts.isAlertActive() - && SystemwideAlerts.getCountDownToo() - - System.currentTimeMillis() > 0) { - countdown.addOption(true, -1, T_alerts_countdown_keep); - } else { - countdown.setOptionSelected(0); - } + // Is there a current count down active? + if (SystemwideAlerts.isAlertActive() && + SystemwideAlerts.getCountDownToo() + - System.currentTimeMillis() > 0) + { + countdown.addOption(true, -1, T_alerts_countdown_keep); + } + else + { + countdown.setOptionSelected(0); + } - Select restrictsessions = form.addItem().addSelect("restrictsessions"); - restrictsessions.setLabel(T_alerts_session_label); - restrictsessions.addOption(SystemwideAlerts.STATE_ALL_SESSIONS, - T_alerts_session_all_sessions); - restrictsessions.addOption(SystemwideAlerts.STATE_CURRENT_SESSIONS, - T_alerts_session_current_sessions); - restrictsessions.addOption( - SystemwideAlerts.STATE_ONLY_ADMINISTRATIVE_SESSIONS, - T_alerts_session_only_administrative); - restrictsessions.setOptionSelected(SystemwideAlerts - .getRestrictSessions()); + Select restrictsessions = form.addItem().addSelect("restrictsessions"); + restrictsessions.setLabel(T_alerts_session_label); + restrictsessions.addOption(SystemwideAlerts.STATE_ALL_SESSIONS, + T_alerts_session_all_sessions); + restrictsessions.addOption(SystemwideAlerts.STATE_CURRENT_SESSIONS, + T_alerts_session_current_sessions); + restrictsessions.addOption( + SystemwideAlerts.STATE_ONLY_ADMINISTRATIVE_SESSIONS, + T_alerts_session_only_administrative); + restrictsessions.setOptionSelected(SystemwideAlerts + .getRestrictSessions()); - form.addItem(T_alerts_session_note); - - Item actions = form.addItem(); - actions.addButton("submit_activate").setValue(T_alerts_submit_activate); - actions.addButton("submit_deactivate").setValue( - T_alerts_submit_deactivate); - } + form.addItem(T_alerts_session_note); + Item actions = form.addItem(); + actions.addButton("submit_activate").setValue(T_alerts_submit_activate); + actions.addButton("submit_deactivate").setValue( + T_alerts_submit_deactivate); + } } - diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelConfigurationTab.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelConfigurationTab.java index 8a6938f5d7..eaf645b297 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelConfigurationTab.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelConfigurationTab.java @@ -27,24 +27,24 @@ import org.dspace.services.factory.DSpaceServicesFactory; */ public class ControlPanelConfigurationTab extends AbstractControlPanelTab { - private static final Message T_DSPACE_HEAD = message("xmlui.administrative.ControlPanel.dspace_head"); - private static final Message T_DSPACE_DIR = message("xmlui.administrative.ControlPanel.dspace_dir"); - private static final Message T_DSPACE_URL = message("xmlui.administrative.ControlPanel.dspace_url"); - private static final Message T_DSPACE_HOST_NAME = message("xmlui.administrative.ControlPanel.dspace_hostname"); - private static final Message T_DSPACE_NAME = message("xmlui.administrative.ControlPanel.dspace_name"); - private static final Message T_DSPACE_VERSION = message("xmlui.administrative.ControlPanel.dspace_version"); - private static final Message T_DB_NAME = message("xmlui.administrative.ControlPanel.db_name"); - private static final Message T_DB_URL = message("xmlui.administrative.ControlPanel.db_url"); - private static final Message T_DB_DRIVER = message("xmlui.administrative.ControlPanel.db_driver"); - private static final Message T_DB_MAX_CONN = message("xmlui.administrative.ControlPanel.db_maxconnections"); - private static final Message T_MAIL_SERVER = message("xmlui.administrative.ControlPanel.mail_server"); - private static final Message T_MAIL_FROM_ADDRESS = message("xmlui.administrative.ControlPanel.mail_from_address"); - private static final Message T_FEEDBACK_RECIPIENT = message("xmlui.administrative.ControlPanel.mail_feedback_recipient"); - private static final Message T_MAIL_ADMIN = message("xmlui.administrative.ControlPanel.mail_admin"); + private static final Message T_DSPACE_HEAD = message("xmlui.administrative.ControlPanel.dspace_head"); + private static final Message T_DSPACE_DIR = message("xmlui.administrative.ControlPanel.dspace_dir"); + private static final Message T_DSPACE_URL = message("xmlui.administrative.ControlPanel.dspace_url"); + private static final Message T_DSPACE_HOST_NAME = message("xmlui.administrative.ControlPanel.dspace_hostname"); + private static final Message T_DSPACE_NAME = message("xmlui.administrative.ControlPanel.dspace_name"); + private static final Message T_DSPACE_VERSION = message("xmlui.administrative.ControlPanel.dspace_version"); + private static final Message T_DB_NAME = message("xmlui.administrative.ControlPanel.db_name"); + private static final Message T_DB_URL = message("xmlui.administrative.ControlPanel.db_url"); + private static final Message T_DB_DRIVER = message("xmlui.administrative.ControlPanel.db_driver"); + private static final Message T_DB_MAX_CONN = message("xmlui.administrative.ControlPanel.db_maxconnections"); + private static final Message T_MAIL_SERVER = message("xmlui.administrative.ControlPanel.mail_server"); + private static final Message T_MAIL_FROM_ADDRESS = message("xmlui.administrative.ControlPanel.mail_from_address"); + private static final Message T_FEEDBACK_RECIPIENT = message("xmlui.administrative.ControlPanel.mail_feedback_recipient"); + private static final Message T_MAIL_ADMIN = message("xmlui.administrative.ControlPanel.mail_admin"); - private static final String T_UNSET = "UNSET"; - - protected ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); + private static final String T_UNSET = "UNSET"; + + protected ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); /** * Guarantee a non-null String. * @@ -53,53 +53,53 @@ public class ControlPanelConfigurationTab extends AbstractControlPanelTab { */ private static String notempty(String value) { return (null == value || "".equals(value)) ? T_UNSET : value; } - @Override - public void addBody(Map objectModel, Division div) throws WingException, SQLException { - // LIST: DSpace - List dspace = div.addList("dspace"); - dspace.setHead(T_DSPACE_HEAD); + @Override + public void addBody(Map objectModel, Division div) + throws WingException, SQLException + { + // LIST: DSpace + List dspace = div.addList("dspace"); + dspace.setHead(T_DSPACE_HEAD); - dspace.addLabel(T_DSPACE_VERSION); - dspace.addItem(Util.getSourceVersion()); + dspace.addLabel(T_DSPACE_VERSION); + dspace.addItem(Util.getSourceVersion()); - dspace.addLabel(T_DSPACE_DIR); - dspace.addItem(notempty(configurationService.getProperty("dspace.dir"))); + dspace.addLabel(T_DSPACE_DIR); + dspace.addItem(notempty(configurationService.getProperty("dspace.dir"))); - dspace.addLabel(T_DSPACE_URL); - String base_url = notempty(configurationService.getProperty("dspace.url")); - dspace.addItemXref(base_url, base_url); + dspace.addLabel(T_DSPACE_URL); + String base_url = notempty(configurationService.getProperty("dspace.url")); + dspace.addItemXref(base_url, base_url); - dspace.addLabel(T_DSPACE_HOST_NAME); - dspace.addItem(notempty(configurationService.getProperty("dspace.hostname"))); + dspace.addLabel(T_DSPACE_HOST_NAME); + dspace.addItem(notempty(configurationService.getProperty("dspace.hostname"))); - dspace.addLabel(T_DSPACE_NAME); - dspace.addItem(notempty(configurationService.getProperty("dspace.name"))); + dspace.addLabel(T_DSPACE_NAME); + dspace.addItem(notempty(configurationService.getProperty("dspace.name"))); - dspace.addLabel(T_DB_NAME); - dspace.addItem(notempty(context.getDbType())); + dspace.addLabel(T_DB_NAME); + dspace.addItem(notempty(context.getDbType())); - DatabaseConfigVO dbConfig = context.getDBConfig(); - dspace.addLabel(T_DB_URL); - dspace.addItem(notempty(dbConfig.getDatabaseUrl())); + DatabaseConfigVO dbConfig = context.getDBConfig(); + dspace.addLabel(T_DB_URL); + dspace.addItem(notempty(dbConfig.getDatabaseUrl())); - dspace.addLabel(T_DB_DRIVER); - dspace.addItem(notempty(dbConfig.getDatabaseDriver())); + dspace.addLabel(T_DB_DRIVER); + dspace.addItem(notempty(dbConfig.getDatabaseDriver())); - dspace.addLabel(T_DB_MAX_CONN); - dspace.addItem(notempty(String.valueOf(dbConfig.getMaxConnections()))); + dspace.addLabel(T_DB_MAX_CONN); + dspace.addItem(notempty(String.valueOf(dbConfig.getMaxConnections()))); - dspace.addLabel(T_MAIL_SERVER); - dspace.addItem(notempty(configurationService.getProperty("mail.server"))); + dspace.addLabel(T_MAIL_SERVER); + dspace.addItem(notempty(configurationService.getProperty("mail.server"))); - dspace.addLabel(T_MAIL_FROM_ADDRESS); - dspace.addItem(notempty(configurationService.getProperty("mail.from.address"))); + dspace.addLabel(T_MAIL_FROM_ADDRESS); + dspace.addItem(notempty(configurationService.getProperty("mail.from.address"))); - dspace.addLabel(T_FEEDBACK_RECIPIENT); - dspace.addItem(notempty(configurationService.getProperty("feedback.recipient"))); - - dspace.addLabel(T_MAIL_ADMIN); - dspace.addItem(notempty(configurationService.getProperty("mail.admin"))); - } + dspace.addLabel(T_FEEDBACK_RECIPIENT); + dspace.addItem(notempty(configurationService.getProperty("feedback.recipient"))); + dspace.addLabel(T_MAIL_ADMIN); + dspace.addItem(notempty(configurationService.getProperty("mail.admin"))); + } } - diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelCurrentActivityTab.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelCurrentActivityTab.java index f704d9c34e..80fd1e6b4e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelCurrentActivityTab.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/controlpanel/ControlPanelCurrentActivityTab.java @@ -31,305 +31,372 @@ import org.dspace.eperson.service.EPersonService; */ public class ControlPanelCurrentActivityTab extends AbstractControlPanelTab { - private static final Message T_activity_head = message("xmlui.administrative.ControlPanel.activity_head"); - private static final Message T_stop_anonymous = message("xmlui.administrative.ControlPanel.stop_anonymous"); - private static final Message T_start_anonymous = message("xmlui.administrative.ControlPanel.start_anonymous"); - private static final Message T_stop_bot = message("xmlui.administrative.ControlPanel.stop_bot"); - private static final Message T_start_bot = message("xmlui.administrative.ControlPanel.start_bot"); - private static final Message T_activity_sort_time = message("xmlui.administrative.ControlPanel.activity_sort_time"); - private static final Message T_activity_sort_user = message("xmlui.administrative.ControlPanel.activity_sort_user"); - private static final Message T_activity_sort_ip = message("xmlui.administrative.ControlPanel.activity_sort_ip"); - private static final Message T_activity_sort_url = message("xmlui.administrative.ControlPanel.activity_sort_url"); - private static final Message T_activity_sort_agent = message("xmlui.administrative.ControlPanel.activity_sort_Agent"); - private static final Message T_activity_anonymous = message("xmlui.administrative.ControlPanel.activity_anonymous"); - private static final Message T_activity_none = message("xmlui.administrative.ControlPanel.activity_none"); - private static final Message T_seconds = message("xmlui.administrative.ControlPanel.seconds"); - private static final Message T_hours = message("xmlui.administrative.ControlPanel.hours"); - private static final Message T_minutes = message("xmlui.administrative.ControlPanel.minutes"); - private static final Message T_detail = message("xmlui.administrative.ControlPanel.detail"); - private static final Message T_show_hide = message("xmlui.administrative.ControlPanel.show_hide"); - private static final Message T_host = message("xmlui.administrative.ControlPanel.host"); - private static final Message T_puser = message("xmlui.administrative.ControlPanel.puser"); - private static final Message T_headers = message("xmlui.administrative.ControlPanel.headers"); - private static final Message T_cookies = message("xmlui.administrative.ControlPanel.cookies"); + private static final Message T_activity_head = message("xmlui.administrative.ControlPanel.activity_head"); + private static final Message T_stop_anonymous = message("xmlui.administrative.ControlPanel.stop_anonymous"); + private static final Message T_start_anonymous = message("xmlui.administrative.ControlPanel.start_anonymous"); + private static final Message T_stop_bot = message("xmlui.administrative.ControlPanel.stop_bot"); + private static final Message T_start_bot = message("xmlui.administrative.ControlPanel.start_bot"); + private static final Message T_activity_sort_time = message("xmlui.administrative.ControlPanel.activity_sort_time"); + private static final Message T_activity_sort_user = message("xmlui.administrative.ControlPanel.activity_sort_user"); + private static final Message T_activity_sort_ip = message("xmlui.administrative.ControlPanel.activity_sort_ip"); + private static final Message T_activity_sort_url = message("xmlui.administrative.ControlPanel.activity_sort_url"); + private static final Message T_activity_sort_agent = message("xmlui.administrative.ControlPanel.activity_sort_Agent"); + private static final Message T_activity_anonymous = message("xmlui.administrative.ControlPanel.activity_anonymous"); + private static final Message T_activity_none = message("xmlui.administrative.ControlPanel.activity_none"); + private static final Message T_seconds = message("xmlui.administrative.ControlPanel.seconds"); + private static final Message T_hours = message("xmlui.administrative.ControlPanel.hours"); + private static final Message T_minutes = message("xmlui.administrative.ControlPanel.minutes"); + private static final Message T_detail = message("xmlui.administrative.ControlPanel.detail"); + private static final Message T_show_hide = message("xmlui.administrative.ControlPanel.show_hide"); + private static final Message T_host = message("xmlui.administrative.ControlPanel.host"); + private static final Message T_puser = message("xmlui.administrative.ControlPanel.puser"); + private static final Message T_headers = message("xmlui.administrative.ControlPanel.headers"); + private static final Message T_cookies = message("xmlui.administrative.ControlPanel.cookies"); - protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); + protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); - @Override - public void addBody(Map objectModel, Division div) throws WingException, - SQLException { - // 0) Update recording settings - Request request = ObjectModelHelper.getRequest(objectModel); + @Override + public void addBody(Map objectModel, Division div) + throws WingException, SQLException + { + // 0) Update recording settings + Request request = ObjectModelHelper.getRequest(objectModel); - // Toggle anonymous recording - String recordAnonymousString = request.getParameter("recordanonymous"); - if (recordAnonymousString != null) { - if ("ON".equals(recordAnonymousString)) { - CurrentActivityAction.setRecordAnonymousEvents(true); - } - if ("OFF".equals(recordAnonymousString)) { - CurrentActivityAction.setRecordAnonymousEvents(false); - } - } + // Toggle anonymous recording + String recordAnonymousString = request.getParameter("recordanonymous"); + if (recordAnonymousString != null) + { + if ("ON".equals(recordAnonymousString)) + { + CurrentActivityAction.setRecordAnonymousEvents(true); + } + if ("OFF".equals(recordAnonymousString)) + { + CurrentActivityAction.setRecordAnonymousEvents(false); + } + } - // Toggle bot recording - String recordBotString = request.getParameter("recordbots"); - if (recordBotString != null) { - if ("ON".equals(recordBotString)) { - CurrentActivityAction.setRecordBotEvents(true); - } - if ("OFF".equals(recordBotString)) { - CurrentActivityAction.setRecordBotEvents(false); - } - } + // Toggle bot recording + String recordBotString = request.getParameter("recordbots"); + if (recordBotString != null) + { + if ("ON".equals(recordBotString)) + { + CurrentActivityAction.setRecordBotEvents(true); + } + if ("OFF".equals(recordBotString)) + { + CurrentActivityAction.setRecordBotEvents(false); + } + } - // 1) Determine how to sort - EventSort sortBy = EventSort.TIME; - String sortByString = request.getParameter("sortBy"); - if (EventSort.TIME.toString().equals(sortByString)) { - sortBy = EventSort.TIME; - } - if (EventSort.URL.toString().equals(sortByString)) { - sortBy = EventSort.URL; - } - if (EventSort.SESSION.toString().equals(sortByString)) { - sortBy = EventSort.SESSION; - } - if (EventSort.AGENT.toString().equals(sortByString)) { - sortBy = EventSort.AGENT; - } - if (EventSort.IP.toString().equals(sortByString)) { - sortBy = EventSort.IP; - } + // 1) Determine how to sort + EventSort sortBy = EventSort.TIME; + String sortByString = request.getParameter("sortBy"); + if (EventSort.TIME.toString().equals(sortByString)) + { + sortBy = EventSort.TIME; + } + if (EventSort.URL.toString().equals(sortByString)) + { + sortBy = EventSort.URL; + } + if (EventSort.SESSION.toString().equals(sortByString)) + { + sortBy = EventSort.SESSION; + } + if (EventSort.AGENT.toString().equals(sortByString)) + { + sortBy = EventSort.AGENT; + } + if (EventSort.IP.toString().equals(sortByString)) + { + sortBy = EventSort.IP; + } - // 2) Sort the events by the requested sorting parameter - java.util.List events = CurrentActivityAction - .getEvents(); - Collections.sort(events, new ActivitySort( - sortBy)); - Collections.reverse(events); - - div = div.addDivision("activitydiv", "well well-light"); + // 2) Sort the events by the requested sorting parameter + java.util.List events = + CurrentActivityAction.getEvents(); + Collections.sort(events, + new ActivitySort(sortBy)); + Collections.reverse(events); - // 3) Toggle controls for anonymous and bot activity - if (CurrentActivityAction.getRecordAnonymousEvents()) { - div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordanonymous=OFF").addContent(T_stop_anonymous); - } else { - div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordanonymous=ON").addContent(T_start_anonymous); - } + div = div.addDivision("activitydiv", "well well-light"); - if (CurrentActivityAction.getRecordBotEvents()) { - div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordbots=OFF").addContent(T_stop_bot); - } else { - div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordbots=ON").addContent(T_start_bot); - } + // 3) Toggle controls for anonymous and bot activity + if (CurrentActivityAction.getRecordAnonymousEvents()) + { + div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordanonymous=OFF").addContent(T_stop_anonymous); + } + else + { + div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordanonymous=ON").addContent(T_start_anonymous); + } - // 4) Display the results Table - // TABLE: activeUsers - Table activeUsers = div.addTable("users", 1, 1); - activeUsers.setHead(T_activity_head - .parameterize(CurrentActivityAction.MAX_EVENTS)); - Row row = activeUsers.addRow(null, Row.ROLE_HEADER, "font_smaller"); - if (sortBy == EventSort.TIME) { - row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time); - } else { - row.addCell().addXref(web_link + "&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time); - } + if (CurrentActivityAction.getRecordBotEvents()) + { + div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordbots=OFF").addContent(T_stop_bot); + } + else + { + div.addPara().addXref(web_link + "&sortBy=" + sortBy + "&recordbots=ON").addContent(T_start_bot); + } - if (sortBy == EventSort.SESSION) { - row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user); - } else { - row.addCell().addXref(web_link + "&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user); - } + // 4) Display the results Table + // TABLE: activeUsers + Table activeUsers = div.addTable("users", 1, 1); + activeUsers.setHead(T_activity_head + .parameterize(CurrentActivityAction.MAX_EVENTS)); + Row row = activeUsers.addRow(null, Row.ROLE_HEADER, "font_smaller"); + if (sortBy == EventSort.TIME) + { + row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time); + } + else + { + row.addCell().addXref(web_link + "&sortBy=" + EventSort.TIME).addContent(T_activity_sort_time); + } - if (sortBy == EventSort.IP) { - row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip); - } else { - row.addCell().addXref(web_link + "&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip); - } + if (sortBy == EventSort.SESSION) + { + row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user); + } + else + { + row.addCell().addXref(web_link + "&sortBy=" + EventSort.SESSION).addContent(T_activity_sort_user); + } - if (sortBy == EventSort.URL) { - row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.URL).addContent(T_activity_sort_url); - } else { - row.addCell().addXref(web_link + "&sortBy=" + EventSort.URL).addContent(T_activity_sort_url); - } + if (sortBy == EventSort.IP) { + row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip); + } + else + { + row.addCell().addXref(web_link + "&sortBy=" + EventSort.IP).addContent(T_activity_sort_ip); + } - if (sortBy == EventSort.AGENT) { - row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent); - } else { - row.addCell().addXref(web_link + "&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent); - } + if (sortBy == EventSort.URL) + { + row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.URL).addContent(T_activity_sort_url); + } + else + { + row.addCell().addXref(web_link + "&sortBy=" + EventSort.URL).addContent(T_activity_sort_url); + } - // add + - row.addCellContent(T_detail); + if (sortBy == EventSort.AGENT) + { + row.addCell().addHighlight("bold").addXref(web_link + "&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent); + } + else + { + row.addCell().addXref(web_link + "&sortBy=" + EventSort.AGENT).addContent(T_activity_sort_agent); + } - // Keep track of how many individual anonymous users there are, each - // unique anonymous - // user is assigned an index based upon the servlet session id. - HashMap anonymousHash = new HashMap(); - int anonymousCount = 1; + // add + + row.addCellContent(T_detail); - int shown = 0; - for (CurrentActivityAction.Event event : events) { - if (event == null) { - continue; - } + // Keep track of how many individual anonymous users there are, each + // unique anonymous + // user is assigned an index based upon the servlet session id. + HashMap anonymousHash = new HashMap(); + int anonymousCount = 1; - shown++; + int shown = 0; + for (CurrentActivityAction.Event event : events) + { + if (event == null) + { + continue; + } - Message timeStampMessage = null; - long ago = System.currentTimeMillis() - event.getTimeStamp(); + shown++; - if (ago > 2 * 60 * 60 * 1000) { - timeStampMessage = T_hours - .parameterize((ago / (60 * 60 * 1000))); - } else if (ago > 60 * 1000) { - timeStampMessage = T_minutes.parameterize((ago / (60 * 1000))); - } else { - timeStampMessage = T_seconds.parameterize((ago / (1000))); - } + Message timeStampMessage = null; + long ago = System.currentTimeMillis() - event.getTimeStamp(); - Row eventRow = activeUsers.addRow(null, Row.ROLE_DATA, "font_smaller"); + if (ago > 2 * 60 * 60 * 1000) + { + timeStampMessage = T_hours + .parameterize((ago / (60 * 60 * 1000))); + } + else if (ago > 60 * 1000) + { + timeStampMessage = T_minutes.parameterize((ago / (60 * 1000))); + } + else + { + timeStampMessage = T_seconds.parameterize((ago / (1000))); + } - eventRow.addCellContent(timeStampMessage); - UUID eid = event.getEPersonID(); - EPerson eperson = ePersonService.find(context, eid); - if (eperson != null) { - String name = eperson.getFullName(); - eventRow.addCellContent(name); - } else { - // Is this a new anonymous user? - if (!anonymousHash.containsKey(event.getSessionID())) { - anonymousHash.put(event.getSessionID(), anonymousCount++); - } + Row eventRow = activeUsers.addRow(null, Row.ROLE_DATA, "font_smaller"); - eventRow.addCellContent(T_activity_anonymous - .parameterize(anonymousHash.get(event.getSessionID()))); - } - eventRow.addCellContent(event.getIP()); - eventRow.addCell().addXref(contextPath + "/" + event.getURL()) - .addContent("/" + event.getURL()); - eventRow.addCellContent(event.getDectectedBrowser()); - eventRow.addCell(null, null, - "toggle-onclick-parent-next4 bold btn-link") - .addContent(T_show_hide); - final String not_present = "not present"; + eventRow.addCellContent(timeStampMessage); + UUID eid = event.getEPersonID(); + EPerson eperson = ePersonService.find(context, eid); + if (eperson != null) + { + String name = eperson.getFullName(); + eventRow.addCellContent(name); + } + else + { + // Is this a new anonymous user? + if (!anonymousHash.containsKey(event.getSessionID())) + { + anonymousHash.put(event.getSessionID(), anonymousCount++); + } - String host = event.host != null ? (String) (event.host) - : not_present; - activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) - .addContent(T_host.parameterize(host)); + eventRow.addCellContent(T_activity_anonymous + .parameterize(anonymousHash.get(event.getSessionID()))); + } + eventRow.addCellContent(event.getIP()); + eventRow.addCell().addXref(contextPath + "/" + event.getURL()) + .addContent("/" + event.getURL()); + eventRow.addCellContent(event.getDectectedBrowser()); + eventRow.addCell(null, null, + "toggle-onclick-parent-next4 bold btn-link") + .addContent(T_show_hide); + final String not_present = "not present"; - String puser = event.puser != null ? event.puser : not_present; - activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) - .addContent(T_puser.parameterize(puser)); + String host = event.host != null ? (String) (event.host) + : not_present; + activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) + .addContent(T_host.parameterize(host)); - // - String headers = ""; - for (Map.Entry o : event.headers.entrySet()) - headers += o.getKey() + ":[" + o.getValue() + "];"; - headers = headers != "" ? headers : not_present; - activeUsers.addRow(null, null, "hidden").addCell(1, 6) - .addContent(T_headers.parameterize(headers)); + String puser = event.puser != null ? event.puser : not_present; + activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) + .addContent(T_puser.parameterize(puser)); - // - String cookies = ""; - for (Map.Entry o : event.cookieMap.entrySet()) - cookies += o.getKey() + ":[" + o.getValue() + "];"; - cookies = cookies != "" ? cookies : not_present; - activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) - .addContent(T_cookies.parameterize(cookies)); - } + // + String headers = ""; + for (Map.Entry o : event.headers.entrySet()) + { + headers += o.getKey() + ":[" + o.getValue() + "];"; + } + headers = headers != "" ? headers : not_present; + activeUsers.addRow(null, null, "hidden").addCell(1, 6) + .addContent(T_headers.parameterize(headers)); - if (shown == 0) { - activeUsers.addRow().addCell(1, 5).addContent(T_activity_none); - } - } + // + String cookies = ""; + for (Map.Entry o : event.cookieMap.entrySet()) + { + cookies += o.getKey() + ":[" + o.getValue() + "];"; + } + cookies = cookies != "" ? cookies : not_present; + activeUsers.addRow(null, null, "hidden font_smaller").addCell(1, 6) + .addContent(T_cookies.parameterize(cookies)); + } - /** The possible sorting parameters */ - private static enum EventSort { - TIME, URL, SESSION, AGENT, IP - }; + if (shown == 0) + { + activeUsers.addRow().addCell(1, 5).addContent(T_activity_none); + } + } - /** - * Comparator to sort activity events by their access times. - */ - public static class ActivitySort - implements Comparator, Serializable { - // Sort parameter - private EventSort sortBy; + /** The possible sorting parameters */ + private static enum EventSort { + TIME, URL, SESSION, AGENT, IP + }; - public ActivitySort(EventSort sortBy) { - this.sortBy = sortBy; - } + /** + * Comparator to sort activity events by their access times. + */ + public static class ActivitySort + implements Comparator, Serializable + { + // Sort parameter + private EventSort sortBy; - /** - * Compare these two activity events based upon the given sort - * parameter. In the case of a tie, allways fallback to sorting based - * upon the timestamp. - */ - @Override - public int compare(E a, E b) { - // Protect against null events while sorting - if (a != null && b == null) { - return 1; // A > B - } else if (a == null && b != null) { - return -1; // B > A - } else if (a == null && b == null) { - return 0; // A == B - } + public ActivitySort(EventSort sortBy) { + this.sortBy = sortBy; + } - // Sort by the given ordering matrix - if (EventSort.URL == sortBy) { - String aURL = a.getURL(); - String bURL = b.getURL(); - int cmp = aURL.compareTo(bURL); - if (cmp != 0) { - return cmp; - } - } else if (EventSort.AGENT == sortBy) { - String aAgent = a.getDectectedBrowser(); - String bAgent = b.getDectectedBrowser(); - int cmp = aAgent.compareTo(bAgent); - if (cmp != 0) { - return cmp; - } - } else if (EventSort.IP == sortBy) { - String aIP = a.getIP(); - String bIP = b.getIP(); - int cmp = aIP.compareTo(bIP); - if (cmp != 0) { - return cmp; - } + /** + * Compare these two activity events based upon the given sort + * parameter. In the case of a tie, allways fallback to sorting based + * upon the timestamp. + */ + @Override + public int compare(E a, E b) { + // Protect against null events while sorting + if (a != null && b == null) + { + return 1; // A > B + } + else if (a == null && b != null) + { + return -1; // B > A + } + else if (a == null && b == null) + { + return 0; // A == B + } - } else if (EventSort.SESSION == sortBy) { - // Ensure that all sessions with an EPersonID associated are - // ordered to the top. Otherwise fall back to comparing session - // IDs. Unfortunately we can not compare eperson names because - // we do not have access to a context object. - if (a.getEPersonID() != null && b.getEPersonID() == null) { - return 1; // A > B - } else if (a.getEPersonID() == null && b.getEPersonID() != null) { - return -1; // B > A - } + // Sort by the given ordering matrix + if (EventSort.URL == sortBy) + { + String aURL = a.getURL(); + String bURL = b.getURL(); + int cmp = aURL.compareTo(bURL); + if (cmp != 0) { + return cmp; + } + } + else if (EventSort.AGENT == sortBy) + { + String aAgent = a.getDectectedBrowser(); + String bAgent = b.getDectectedBrowser(); + int cmp = aAgent.compareTo(bAgent); + if (cmp != 0) + { + return cmp; + } + } + else if (EventSort.IP == sortBy) + { + String aIP = a.getIP(); + String bIP = b.getIP(); + int cmp = aIP.compareTo(bIP); + if (cmp != 0) { + return cmp; + } - String aSession = a.getSessionID(); - String bSession = b.getSessionID(); - int cmp = aSession.compareTo(bSession); - if (cmp != 0) { - return cmp; - } - } + } + else if (EventSort.SESSION == sortBy) + { + // Ensure that all sessions with an EPersonID associated are + // ordered to the top. Otherwise fall back to comparing session + // IDs. Unfortunately we can not compare eperson names because + // we do not have access to a context object. + if (a.getEPersonID() != null && b.getEPersonID() == null) + { + return 1; // A > B + } + else if (a.getEPersonID() == null && b.getEPersonID() != null) + { + return -1; // B > A + } - // All ways fall back to sorting by time, when events are equal. - if (a.getTimeStamp() > b.getTimeStamp()) { - return 1; // A > B - } else if (a.getTimeStamp() > b.getTimeStamp()) { - return -1; // B > A - } - return 0; // A == B - } - } + String aSession = a.getSessionID(); + String bSession = b.getSessionID(); + int cmp = aSession.compareTo(bSession); + if (cmp != 0) + { + return cmp; + } + } + // All ways fall back to sorting by time, when events are equal. + if (a.getTimeStamp() > b.getTimeStamp()) + { + return 1; // A > B + } + else if (a.getTimeStamp() > b.getTimeStamp()) + { + return -1; // B > A + } + return 0; // A == B + } + } } - diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/AddEPersonForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/AddEPersonForm.java index a6c2c15a13..27a96a68f2 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/AddEPersonForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/AddEPersonForm.java @@ -28,169 +28,177 @@ import org.dspace.authorize.AuthorizeException; /** * Present the user with all the eperson metadata fields so that they - * can describe the new eperson before being created. If the user's - * input is incorrect in someway then they may be returning here with - * some fields in error. In particular there is a special case for the - * condition when the email-address entered is already in use by + * can describe the new eperson before being created. If the user's + * input is incorrect in someway then they may be returning here with + * some fields in error. In particular there is a special case for the + * condition when the email-address entered is already in use by * another user. - * + * * @author Alexey Maslov */ -public class AddEPersonForm extends AbstractDSpaceTransformer +public class AddEPersonForm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - - private static final Message T_eperson_trail = - message("xmlui.administrative.eperson.general.epeople_trail"); - - private static final Message T_title = - message("xmlui.administrative.eperson.AddEPersonForm.title"); - private static final Message T_trail = - message("xmlui.administrative.eperson.AddEPersonForm.trail"); + private static final Message T_eperson_trail = + message("xmlui.administrative.eperson.general.epeople_trail"); - private static final Message T_head1 = - message("xmlui.administrative.eperson.AddEPersonForm.head1"); + private static final Message T_title = + message("xmlui.administrative.eperson.AddEPersonForm.title"); - private static final Message T_email_taken = - message("xmlui.administrative.eperson.AddEPersonForm.email_taken"); + private static final Message T_trail = + message("xmlui.administrative.eperson.AddEPersonForm.trail"); - private static final Message T_head2 = - message("xmlui.administrative.eperson.AddEPersonForm.head2"); + private static final Message T_head1 = + message("xmlui.administrative.eperson.AddEPersonForm.head1"); - private static final Message T_error_email_unique = - message("xmlui.administrative.eperson.AddEPersonForm.error_email_unique"); + private static final Message T_email_taken = + message("xmlui.administrative.eperson.AddEPersonForm.email_taken"); - private static final Message T_error_email = - message("xmlui.administrative.eperson.AddEPersonForm.error_email"); + private static final Message T_head2 = + message("xmlui.administrative.eperson.AddEPersonForm.head2"); - private static final Message T_error_fname = - message("xmlui.administrative.eperson.AddEPersonForm.error_fname"); + private static final Message T_error_email_unique = + message("xmlui.administrative.eperson.AddEPersonForm.error_email_unique"); - private static final Message T_error_lname = - message("xmlui.administrative.eperson.AddEPersonForm.error_lname"); + private static final Message T_error_email = + message("xmlui.administrative.eperson.AddEPersonForm.error_email"); - private static final Message T_req_certs = - message("xmlui.administrative.eperson.AddEPersonForm.req_certs"); + private static final Message T_error_fname = + message("xmlui.administrative.eperson.AddEPersonForm.error_fname"); - private static final Message T_can_log_in = - message("xmlui.administrative.eperson.AddEPersonForm.can_log_in"); + private static final Message T_error_lname = + message("xmlui.administrative.eperson.AddEPersonForm.error_lname"); - private static final Message T_submit_create = - message("xmlui.administrative.eperson.AddEPersonForm.submit_create"); + private static final Message T_req_certs = + message("xmlui.administrative.eperson.AddEPersonForm.req_certs"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); - - - /** Language string used from other aspects: */ - - private static final Message T_email_address = + private static final Message T_can_log_in = + message("xmlui.administrative.eperson.AddEPersonForm.can_log_in"); + + private static final Message T_submit_create = + message("xmlui.administrative.eperson.AddEPersonForm.submit_create"); + + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); + + + /** Language string used from other aspects: */ + + private static final Message T_email_address = message("xmlui.EPerson.EditProfile.email_address"); - - private static final Message T_first_name = + + private static final Message T_first_name = message("xmlui.EPerson.EditProfile.first_name"); - - private static final Message T_last_name = + + private static final Message T_last_name = message("xmlui.EPerson.EditProfile.last_name"); - + private static final Message T_telephone = message("xmlui.EPerson.EditProfile.telephone"); - - - public void addPageMeta(PageMeta pageMeta) throws WingException + + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/epeople",T_eperson_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - Request request = ObjectModelHelper.getRequest(objectModel); - - String errorString = parameters.getParameter("errors",null); - ArrayList errors = new ArrayList(); - if (errorString != null) - { - for (String error : errorString.split(",")) + + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + Request request = ObjectModelHelper.getRequest(objectModel); + + String errorString = parameters.getParameter("errors",null); + ArrayList errors = new ArrayList(); + if (errorString != null) + { + for (String error : errorString.split(",")) { errors.add(error); } - } - - String emailValue = request.getParameter("email_address"); - String firstValue = request.getParameter("first_name"); - String lastValue = request.getParameter("last_name"); - String phoneValue = request.getParameter("phone"); - boolean canLogInValue = (request.getParameter("can_log_in") == null) ? false : true; - boolean certificateValue = (request.getParameter("certificate") == null) ? false : true; - - - - // DIVISION: eperson-add - Division add = body.addInteractiveDivision("eperson-add",contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative eperson"); - - add.setHead(T_head1); - - if (errors.contains("eperson_email_key")) { - Para problem = add.addPara(); - problem.addHighlight("bold").addContent(T_email_taken); - } - + } + + String emailValue = request.getParameter("email_address"); + String firstValue = request.getParameter("first_name"); + String lastValue = request.getParameter("last_name"); + String phoneValue = request.getParameter("phone"); + boolean canLogInValue = (request.getParameter("can_log_in") == null) ? false : true; + boolean certificateValue = (request.getParameter("certificate") == null) ? false : true; + + + + // DIVISION: eperson-add + Division add = body.addInteractiveDivision("eperson-add", + contextPath + "/admin/epeople", Division.METHOD_POST, + "primary administrative eperson"); + + add.setHead(T_head1); + + if (errors.contains("eperson_email_key")) + { + Para problem = add.addPara(); + problem.addHighlight("bold").addContent(T_email_taken); + } + List identity = add.addList("identity",List.TYPE_FORM); - identity.setHead(T_head2); - + identity.setHead(T_head2); + Text email = identity.addItem().addText("email_address"); email.setRequired(); email.setAutofocus("autofocus"); email.setLabel(T_email_address); email.setValue(emailValue); - if (errors.contains("eperson_email_key")) { - email.addError(T_error_email_unique); + if (errors.contains("eperson_email_key")) + { + email.addError(T_error_email_unique); } - else if (errors.contains("email_address")) { - email.addError(T_error_email); + else if (errors.contains("email_address")) + { + email.addError(T_error_email); } - + Text firstName = identity.addItem().addText("first_name"); firstName.setRequired(); firstName.setLabel(T_first_name); firstName.setValue(firstValue); - if (errors.contains("first_name")) { - firstName.addError(T_error_fname); + if (errors.contains("first_name")) + { + firstName.addError(T_error_fname); } - + Text lastName = identity.addItem().addText("last_name"); lastName.setRequired(); lastName.setLabel(T_last_name); lastName.setValue(lastValue); - if (errors.contains("last_name")) { - lastName.addError(T_error_lname); + if (errors.contains("last_name")) + { + lastName.addError(T_error_lname); } - + Text phone = identity.addItem().addText("phone"); phone.setLabel(T_telephone); phone.setValue(phoneValue); - + CheckBox canLogIn = identity.addItem().addCheckBox("can_log_in"); canLogIn.setLabel(T_can_log_in); canLogIn.addOption(canLogInValue, "yes"); - + CheckBox certificate = identity.addItem().addCheckBox("certificate"); certificate.setLabel(T_req_certs); certificate.addOption(certificateValue,"yes"); - + Item buttons = identity.addItem(); buttons.addButton("submit_save").setValue(T_submit_create); buttons.addButton("submit_cancel").setValue(T_submit_cancel); - + add.addHidden("administrative-continue").setValue(knot.getId()); - } - + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/DeleteEPeopleConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/DeleteEPeopleConfirm.java index f9868acb46..7159a4669e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/DeleteEPeopleConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/DeleteEPeopleConfirm.java @@ -32,85 +32,89 @@ import org.dspace.eperson.service.EPersonService; */ public class DeleteEPeopleConfirm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - - private static final Message T_eperson_trail = - message("xmlui.administrative.eperson.general.epeople_trail"); - - private static final Message T_title = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.title"); - - private static final Message T_trail = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.trail"); - - private static final Message T_confirm_head = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.confirm_head"); - - private static final Message T_confirm_para = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.confirm_para"); - - private static final Message T_head_id = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_id"); - - private static final Message T_head_name = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_name"); - - private static final Message T_head_email = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_email"); - - private static final Message T_submit_confirm = - message("xmlui.administrative.eperson.DeleteEPeopleConfirm.submit_confirm"); - - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); + + private static final Message T_eperson_trail = + message("xmlui.administrative.eperson.general.epeople_trail"); + + private static final Message T_title = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.title"); + + private static final Message T_trail = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.trail"); + + private static final Message T_confirm_head = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.confirm_head"); + + private static final Message T_confirm_para = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.confirm_para"); + + private static final Message T_head_id = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_id"); + + private static final Message T_head_name = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_name"); + + private static final Message T_head_email = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.head_email"); + + private static final Message T_submit_confirm = + message("xmlui.administrative.eperson.DeleteEPeopleConfirm.submit_confirm"); + + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); - protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); + protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/epeople",T_eperson_trail); pageMeta.addTrail().addContent(T_trail); } - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - String idsString = parameters.getParameter("epeopleIDs", null); - - ArrayList epeople = new ArrayList(); - for (String id : idsString.split(",")) - { - EPerson person = ePersonService.find(context, UUID.fromString(id)); - epeople.add(person); - } + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + String idsString = parameters.getParameter("epeopleIDs", null); + + ArrayList epeople = new ArrayList(); + for (String id : idsString.split(",")) + { + EPerson person = ePersonService.find(context, UUID.fromString(id)); + epeople.add(person); + } - // DIVISION: epeople-confirm-delete - Division deleted = body.addInteractiveDivision("epeople-confirm-delete",contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative eperson"); - deleted.setHead(T_confirm_head); - deleted.addPara(T_confirm_para); - - Table table = deleted.addTable("epeople-confirm-delete",epeople.size() + 1, 1); + // DIVISION: epeople-confirm-delete + Division deleted = body.addInteractiveDivision("epeople-confirm-delete", + contextPath + "/admin/epeople", Division.METHOD_POST, + "primary administrative eperson"); + deleted.setHead(T_confirm_head); + deleted.addPara(T_confirm_para); + + Table table = deleted.addTable("epeople-confirm-delete",epeople.size() + 1, 1); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_head_id); header.addCell().addContent(T_head_name); header.addCell().addContent(T_head_email); - - for (EPerson eperson : epeople) - { - Row row = table.addRow(); - row.addCell().addContent(eperson.getID().toString()); - row.addCell().addContent(eperson.getFullName()); - row.addCell().addContent(eperson.getEmail()); - } - Para buttons = deleted.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_confirm); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - deleted.addHidden("administrative-continue").setValue(knot.getId()); + + for (EPerson eperson : epeople) + { + Row row = table.addRow(); + row.addCell().addContent(eperson.getID().toString()); + row.addCell().addContent(eperson.getFullName()); + row.addCell().addContent(eperson.getEmail()); + } + Para buttons = deleted.addPara(); + buttons.addButton("submit_confirm").setValue(T_submit_confirm); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + deleted.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/EditEPersonForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/EditEPersonForm.java index 4a3091c74f..6ced1d608b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/EditEPersonForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/eperson/EditEPersonForm.java @@ -38,415 +38,418 @@ import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.GroupService; /** - * Edit an existing EPerson, display all the eperson's metadata - * along with two special options two reset the eperson's - * password and delete this user. + * Edit an existing EPerson, display all the eperson's metadata + * along with two special options two reset the eperson's + * password and delete this user. * * @author Alexey Maslov */ -public class EditEPersonForm extends AbstractDSpaceTransformer +public class EditEPersonForm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - - private static final Message T_submit_save = - message("xmlui.general.save"); - - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); - - private static final Message T_title = - message("xmlui.administrative.eperson.EditEPersonForm.title"); - - private static final Message T_eperson_trail = - message("xmlui.administrative.eperson.general.epeople_trail"); - - private static final Message T_trail = - message("xmlui.administrative.eperson.EditEPersonForm.trail"); - - private static final Message T_head1 = - message("xmlui.administrative.eperson.EditEPersonForm.head1"); - - private static final Message T_email_taken = - message("xmlui.administrative.eperson.EditEPersonForm.email_taken"); - - private static final Message T_head2 = - message("xmlui.administrative.eperson.EditEPersonForm.head2"); - - private static final Message T_error_email_unique = - message("xmlui.administrative.eperson.EditEPersonForm.error_email_unique"); - - private static final Message T_error_email = - message("xmlui.administrative.eperson.EditEPersonForm.error_email"); - - private static final Message T_error_fname = - message("xmlui.administrative.eperson.EditEPersonForm.error_fname"); - - private static final Message T_error_lname = - message("xmlui.administrative.eperson.EditEPersonForm.error_lname"); - - private static final Message T_req_certs = - message("xmlui.administrative.eperson.EditEPersonForm.req_certs"); - - private static final Message T_can_log_in = - message("xmlui.administrative.eperson.EditEPersonForm.can_log_in"); - - private static final Message T_submit_reset_password = - message("xmlui.administrative.eperson.EditEPersonForm.submit_reset_password"); - - private static final Message T_special_help = - message("xmlui.administrative.eperson.EditEPersonForm.special_help"); - - private static final Message T_submit_delete = - message("xmlui.administrative.eperson.EditEPersonForm.submit_delete"); - - private static final Message T_submit_login_as = - message("xmlui.administrative.eperson.EditEPersonForm.submit_login_as"); - - private static final Message T_delete_constraint = - message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint"); + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); - private static final Message T_constraint_last_conjunction = - message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.last_conjunction"); - - private static final Message T_constraint_item = - message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.item"); - - private static final Message T_constraint_workflowitem = - message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.workflowitem"); - - private static final Message T_constraint_tasklistitem = - message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.tasklistitem"); + private static final Message T_submit_save = + message("xmlui.general.save"); + + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); + + private static final Message T_title = + message("xmlui.administrative.eperson.EditEPersonForm.title"); + + private static final Message T_eperson_trail = + message("xmlui.administrative.eperson.general.epeople_trail"); + + private static final Message T_trail = + message("xmlui.administrative.eperson.EditEPersonForm.trail"); + + private static final Message T_head1 = + message("xmlui.administrative.eperson.EditEPersonForm.head1"); + + private static final Message T_email_taken = + message("xmlui.administrative.eperson.EditEPersonForm.email_taken"); + + private static final Message T_head2 = + message("xmlui.administrative.eperson.EditEPersonForm.head2"); + + private static final Message T_error_email_unique = + message("xmlui.administrative.eperson.EditEPersonForm.error_email_unique"); + + private static final Message T_error_email = + message("xmlui.administrative.eperson.EditEPersonForm.error_email"); + + private static final Message T_error_fname = + message("xmlui.administrative.eperson.EditEPersonForm.error_fname"); + + private static final Message T_error_lname = + message("xmlui.administrative.eperson.EditEPersonForm.error_lname"); + + private static final Message T_req_certs = + message("xmlui.administrative.eperson.EditEPersonForm.req_certs"); + + private static final Message T_can_log_in = + message("xmlui.administrative.eperson.EditEPersonForm.can_log_in"); + + private static final Message T_submit_reset_password = + message("xmlui.administrative.eperson.EditEPersonForm.submit_reset_password"); + + private static final Message T_special_help = + message("xmlui.administrative.eperson.EditEPersonForm.special_help"); + + private static final Message T_submit_delete = + message("xmlui.administrative.eperson.EditEPersonForm.submit_delete"); + + private static final Message T_submit_login_as = + message("xmlui.administrative.eperson.EditEPersonForm.submit_login_as"); + + private static final Message T_delete_constraint = + message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint"); + + private static final Message T_constraint_last_conjunction = + message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.last_conjunction"); + + private static final Message T_constraint_item = + message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.item"); + + private static final Message T_constraint_workflowitem = + message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.workflowitem"); + + private static final Message T_constraint_tasklistitem = + message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.tasklistitem"); + + private static final Message T_constraint_unknown = + message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.unknown"); + + private static final Message T_member_head = + message("xmlui.administrative.eperson.EditEPersonForm.member_head"); + + private static final Message T_indirect_member = + message("xmlui.administrative.eperson.EditEPersonForm.indirect_member"); + + private static final Message T_member_none = + message("xmlui.administrative.eperson.EditEPersonForm.member_none"); + + /** Language string used: */ + + private static final Message T_email_address = + message("xmlui.EPerson.EditProfile.email_address"); + + private static final Message T_first_name = + message("xmlui.EPerson.EditProfile.first_name"); + + private static final Message T_last_name = + message("xmlui.EPerson.EditProfile.last_name"); - private static final Message T_constraint_unknown = - message("xmlui.administrative.eperson.EditEPersonForm.delete_constraint.unknown"); - - private static final Message T_member_head = - message("xmlui.administrative.eperson.EditEPersonForm.member_head"); - - private static final Message T_indirect_member = - message("xmlui.administrative.eperson.EditEPersonForm.indirect_member"); - - private static final Message T_member_none = - message("xmlui.administrative.eperson.EditEPersonForm.member_none"); - - /** Language string used: */ - - private static final Message T_email_address = - message("xmlui.EPerson.EditProfile.email_address"); - - private static final Message T_first_name = - message("xmlui.EPerson.EditProfile.first_name"); - - private static final Message T_last_name = - message("xmlui.EPerson.EditProfile.last_name"); - private static final Message T_telephone = - message("xmlui.EPerson.EditProfile.telephone"); - + message("xmlui.EPerson.EditProfile.telephone"); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); - protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); + protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/epeople",T_eperson_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - boolean admin = authorizeService.isAdmin(context); - - Request request = ObjectModelHelper.getRequest(objectModel); - - // Get our parameters; - UUID epersonID = UUID.fromString(parameters.getParameter("epersonID",null)); - String errorString = parameters.getParameter("errors",null); - ArrayList errors = new ArrayList(); - if (errorString != null) - { - for (String error : errorString.split(",")) + + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + boolean admin = authorizeService.isAdmin(context); + + Request request = ObjectModelHelper.getRequest(objectModel); + + // Get our parameters; + UUID epersonID = UUID.fromString(parameters.getParameter("epersonID",null)); + String errorString = parameters.getParameter("errors",null); + ArrayList errors = new ArrayList(); + if (errorString != null) + { + for (String error : errorString.split(",")) { errors.add(error); } - } - - // Grab the person in question - EPerson eperson = ePersonService.find(context, epersonID); - - if (eperson == null) + } + + // Grab the person in question + EPerson eperson = ePersonService.find(context, epersonID); + + if (eperson == null) { throw new UIException("Unable to find eperson for id:" + epersonID); } - - String emailValue = eperson.getEmail(); - String firstValue = eperson.getFirstName(); - String lastValue = eperson.getLastName(); - String phoneValue = ePersonService.getMetadata(eperson, "phone"); - boolean canLogInValue = eperson.canLogIn(); - boolean certificatValue = eperson.getRequireCertificate(); - java.util.List deleteConstraints = ePersonService.getDeleteConstraints(context, eperson); - - if (request.getParameter("email_address") != null) + + String emailValue = eperson.getEmail(); + String firstValue = eperson.getFirstName(); + String lastValue = eperson.getLastName(); + String phoneValue = ePersonService.getMetadata(eperson, "phone"); + boolean canLogInValue = eperson.canLogIn(); + boolean certificatValue = eperson.getRequireCertificate(); + java.util.List deleteConstraints = ePersonService.getDeleteConstraints(context, eperson); + + if (request.getParameter("email_address") != null) { emailValue = request.getParameter("email_address"); } - if (request.getParameter("first_name") != null) + if (request.getParameter("first_name") != null) { firstValue = request.getParameter("first_name"); } - if (request.getParameter("last_name") != null) + if (request.getParameter("last_name") != null) { lastValue = request.getParameter("last_name"); } - if (request.getParameter("phone") != null) + if (request.getParameter("phone") != null) { phoneValue = request.getParameter("phone"); } - - - - // DIVISION: eperson-edit - Division edit = body.addInteractiveDivision("eperson-edit",contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative eperson"); - edit.setHead(T_head1); - - - if (errors.contains("eperson_email_key")) { - Para problem = edit.addPara(); - problem.addHighlight("bold").addContent(T_email_taken); - } - - + + + + // DIVISION: eperson-edit + Division edit = body.addInteractiveDivision("eperson-edit", + contextPath+"/admin/epeople", Division.METHOD_POST, + "primary administrative eperson"); + edit.setHead(T_head1); + + + if (errors.contains("eperson_email_key")) + { + Para problem = edit.addPara(); + problem.addHighlight("bold").addContent(T_email_taken); + } + + List identity = edit.addList("form",List.TYPE_FORM); - identity.setHead(T_head2.parameterize(eperson.getFullName())); - + identity.setHead(T_head2.parameterize(eperson.getFullName())); + if (admin) { - Text email = identity.addItem().addText("email_address"); - email.setRequired(); - email.setLabel(T_email_address); - email.setValue(emailValue); - if (errors.contains("eperson_email_key")) + Text email = identity.addItem().addText("email_address"); + email.setRequired(); + email.setLabel(T_email_address); + email.setValue(emailValue); + if (errors.contains("eperson_email_key")) { email.addError(T_error_email_unique); } - else if (errors.contains("email_address")) + else if (errors.contains("email_address")) { email.addError(T_error_email); } } else { - identity.addLabel(T_email_address); - identity.addItem(emailValue); + identity.addLabel(T_email_address); + identity.addItem(emailValue); } - + if (admin) { - Text firstName = identity.addItem().addText("first_name"); - firstName.setRequired(); - firstName.setLabel(T_first_name); - firstName.setValue(firstValue); - if (errors.contains("first_name")) + Text firstName = identity.addItem().addText("first_name"); + firstName.setRequired(); + firstName.setLabel(T_first_name); + firstName.setValue(firstValue); + if (errors.contains("first_name")) { firstName.addError(T_error_fname); } } else { - identity.addLabel(T_first_name); - identity.addItem(firstValue); + identity.addLabel(T_first_name); + identity.addItem(firstValue); } - + if (admin) { - Text lastName = identity.addItem().addText("last_name"); - lastName.setRequired(); - lastName.setLabel(T_last_name); - lastName.setValue(lastValue); - if (errors.contains("last_name")) + Text lastName = identity.addItem().addText("last_name"); + lastName.setRequired(); + lastName.setLabel(T_last_name); + lastName.setValue(lastValue); + if (errors.contains("last_name")) { lastName.addError(T_error_lname); } } else { - identity.addLabel(T_last_name); - identity.addItem(lastValue); + identity.addLabel(T_last_name); + identity.addItem(lastValue); } - + if (admin) { - Text phone = identity.addItem().addText("phone"); - phone.setLabel(T_telephone); - phone.setValue(phoneValue); + Text phone = identity.addItem().addText("phone"); + phone.setLabel(T_telephone); + phone.setValue(phoneValue); } else { - identity.addLabel(T_telephone); - identity.addItem(phoneValue); + identity.addLabel(T_telephone); + identity.addItem(phoneValue); } - + if (admin) - { - // Administrative options: - CheckBox canLogInField = identity.addItem().addCheckBox("can_log_in"); - canLogInField.setLabel(T_can_log_in); - canLogInField.addOption(canLogInValue, "true"); - - CheckBox certificateField = identity.addItem().addCheckBox("certificate"); - certificateField.setLabel(T_req_certs); - certificateField.addOption(certificatValue,"true"); - - - // Buttons to reset, delete or login as - identity.addItem().addHighlight("italic").addContent(T_special_help); - Item special = identity.addItem(); - special.addButton("submit_reset_password").setValue(T_submit_reset_password); - - Button submitDelete = special.addButton("submit_delete"); - submitDelete.setValue(T_submit_delete); - - Button submitLoginAs = special.addButton("submit_login_as"); - submitLoginAs.setValue(T_submit_login_as); - if (!DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.user.assumelogin", false)) + { + // Administrative options: + CheckBox canLogInField = identity.addItem().addCheckBox("can_log_in"); + canLogInField.setLabel(T_can_log_in); + canLogInField.addOption(canLogInValue, "true"); + + CheckBox certificateField = identity.addItem().addCheckBox("certificate"); + certificateField.setLabel(T_req_certs); + certificateField.addOption(certificatValue,"true"); + + + // Buttons to reset, delete or login as + identity.addItem().addHighlight("italic").addContent(T_special_help); + Item special = identity.addItem(); + special.addButton("submit_reset_password").setValue(T_submit_reset_password); + + Button submitDelete = special.addButton("submit_delete"); + submitDelete.setValue(T_submit_delete); + + Button submitLoginAs = special.addButton("submit_login_as"); + submitLoginAs.setValue(T_submit_login_as); + if (!DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.user.assumelogin", false)) { submitLoginAs.setDisabled(); } - - if (deleteConstraints != null && deleteConstraints.size() > 0) - { - submitDelete.setDisabled(); - - Highlight hi = identity.addItem("eperson-delete-constraint","eperson-delete-constraint").addHighlight("error"); - hi.addContent(T_delete_constraint); - hi.addContent(" "); - - for (String constraint : deleteConstraints) - { - int idx = deleteConstraints.indexOf(constraint); - if (idx > 0 && idx == deleteConstraints.size() -1 ) - { - hi.addContent(", "); - hi.addContent(T_constraint_last_conjunction); - hi.addContent(" "); - } - else if (idx > 0) + + if (deleteConstraints != null && deleteConstraints.size() > 0) + { + submitDelete.setDisabled(); + + Highlight hi = identity.addItem("eperson-delete-constraint","eperson-delete-constraint").addHighlight("error"); + hi.addContent(T_delete_constraint); + hi.addContent(" "); + + for (String constraint : deleteConstraints) + { + int idx = deleteConstraints.indexOf(constraint); + if (idx > 0 && idx == deleteConstraints.size() -1 ) + { + hi.addContent(", "); + hi.addContent(T_constraint_last_conjunction); + hi.addContent(" "); + } + else if (idx > 0) { hi.addContent(", "); } - - if ("item".equals(constraint)) + + if ("item".equals(constraint)) { hi.addContent(T_constraint_item); } - else if ("workflowitem".equals(constraint)) + else if ("workflowitem".equals(constraint)) { hi.addContent(T_constraint_workflowitem); } - else if ("tasklistitem".equals(constraint)) + else if ("tasklistitem".equals(constraint)) { hi.addContent(T_constraint_tasklistitem); } - else + else { hi.addContent(T_constraint_unknown); } - - } - hi.addContent("."); - } + + } + hi.addContent("."); + } } - - + + Item buttons = identity.addItem(); if (admin) { buttons.addButton("submit_save").setValue(T_submit_save); } buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - - + + if (admin) { - List member = edit.addList("eperson-member-of"); - member.setHead(T_member_head); + List member = edit.addList("eperson-member-of"); + member.setHead(T_member_head); - java.util.List groups = groupService.allMemberGroups(context, eperson); - for (Group group : groups) - { - String url = contextPath + "/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+group.getID(); - - Item item = member.addItem(); - item.addXref(url,group.getName()); - - // Check if this membership is via another group or not, if so then add a note. - Group via = findViaGroup(eperson, group); - if (via != null) + java.util.List groups = groupService.allMemberGroups(context, eperson); + for (Group group : groups) + { + String url = contextPath + "/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+group.getID(); + + Item item = member.addItem(); + item.addXref(url,group.getName()); + + // Check if this membership is via another group or not, if so then add a note. + Group via = findViaGroup(eperson, group); + if (via != null) { item.addHighlight("fade").addContent(T_indirect_member.parameterize(via.getName())); } - } - - if (groups.size() <= 0) + } + + if (groups.size() <= 0) { member.addItem().addHighlight("italic").addContent(T_member_none); } } - - edit.addHidden("administrative-continue").setValue(knot.getId()); - } - - - /** - * Determine if the given eperson is a direct member of this group if - * they are not the return the group that membership is implied - * through (the via group!). This will only find one possible relation - * path, there may be multiple. - * - * - * @param eperson The source group to search from - * @param group The target group to search for. - * @return The group this member is related through or null if none found. - */ - private Group findViaGroup(EPerson eperson, Group group) throws SQLException - { - // First check if this eperson is a direct member of the group. - for (EPerson direct : group.getMembers()) - { - if (direct.getID() == eperson.getID()) + + edit.addHidden("administrative-continue").setValue(knot.getId()); + } + + + /** + * Determine if the given eperson is a direct member of this group if + * they are not the return the group that membership is implied + * through (the via group!). This will only find one possible relation + * path, there may be multiple. + * + * @param eperson The source group to search from + * @param group The target group to search for. + * @return The group this member is related through or null if none found. + */ + private Group findViaGroup(EPerson eperson, Group group) + throws SQLException + { + // First check if this eperson is a direct member of the group. + for (EPerson direct : group.getMembers()) + { + if (direct.getID() == eperson.getID()) { // Direct membership return null; } - } - - // Otherwise check what group this eperson is a member through - java.util.List targets = group.getMemberGroups(); - - java.util.List groups = groupService.allMemberGroups(context, eperson); - for (Group member : groups) - { - for (Group target : targets) - { - if (member.getID() == target.getID()) + } + + // Otherwise check what group this eperson is a member through + java.util.List targets = group.getMemberGroups(); + + java.util.List groups = groupService.allMemberGroups(context, eperson); + for (Group member : groups) + { + for (Group target : targets) + { + if (member.getID() == target.getID()) { return member; } - } - } - - // This should never happen, but let's just say we couldn't find the relationship. - return null; - } - + } + } + + // This should never happen, but let's just say we couldn't find the relationship. + return null; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/DeleteGroupsConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/DeleteGroupsConfirm.java index 28771455f4..b549ce9ea0 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/DeleteGroupsConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/DeleteGroupsConfirm.java @@ -26,86 +26,89 @@ import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.service.GroupService; /** - * Present the user with a list of soon-to-be-deleted Groups. - * If the user clicks confirm deletion then they will be + * Present the user with a list of soon-to-be-deleted Groups. + * If the user clicks confirm deletion then they will be * deleted otherwise they will be spared the wrath of deletion. * @author Scott Phillips */ -public class DeleteGroupsConfirm extends AbstractDSpaceTransformer +public class DeleteGroupsConfirm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = + /** Language Strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_group_trail = - message("xmlui.administrative.group.general.group_trail"); - private static final Message T_title = - message("xmlui.administrative.group.DeleteGroupsConfirm.title"); - private static final Message T_trail = - message("xmlui.administrative.group.DeleteGroupsConfirm.trail"); - private static final Message T_head = - message("xmlui.administrative.group.DeleteGroupsConfirm.head"); - private static final Message T_para = - message("xmlui.administrative.group.DeleteGroupsConfirm.para"); - private static final Message T_column1 = - message("xmlui.administrative.group.DeleteGroupsConfirm.column1"); - private static final Message T_column2 = - message("xmlui.administrative.group.DeleteGroupsConfirm.column2"); - private static final Message T_column3 = - message("xmlui.administrative.group.DeleteGroupsConfirm.column3"); - private static final Message T_column4 = - message("xmlui.administrative.group.DeleteGroupsConfirm.column4"); - private static final Message T_submit_confirm = - message("xmlui.general.delete"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); + private static final Message T_group_trail = + message("xmlui.administrative.group.general.group_trail"); + private static final Message T_title = + message("xmlui.administrative.group.DeleteGroupsConfirm.title"); + private static final Message T_trail = + message("xmlui.administrative.group.DeleteGroupsConfirm.trail"); + private static final Message T_head = + message("xmlui.administrative.group.DeleteGroupsConfirm.head"); + private static final Message T_para = + message("xmlui.administrative.group.DeleteGroupsConfirm.para"); + private static final Message T_column1 = + message("xmlui.administrative.group.DeleteGroupsConfirm.column1"); + private static final Message T_column2 = + message("xmlui.administrative.group.DeleteGroupsConfirm.column2"); + private static final Message T_column3 = + message("xmlui.administrative.group.DeleteGroupsConfirm.column3"); + private static final Message T_column4 = + message("xmlui.administrative.group.DeleteGroupsConfirm.column4"); + private static final Message T_submit_confirm = + message("xmlui.general.delete"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); - protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/groups",T_group_trail); pageMeta.addTrail().addContent(T_trail); } - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - String idsString = parameters.getParameter("groupIDs", null); - - ArrayList groups = new ArrayList(); - for (String id : idsString.split(",")) - { - Group group = groupService.find(context, UUID.fromString(id)); - groups.add(group); - } - - Division deleted = body.addInteractiveDivision("group-confirm-delete", - contextPath+"/admin/epeople",Division.METHOD_POST,"primary administrative groups"); - deleted.setHead(T_head); - deleted.addPara(T_para); - - Table table = deleted.addTable("groups-list",groups.size() + 1, 3); + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + String idsString = parameters.getParameter("groupIDs", null); + + ArrayList groups = new ArrayList(); + for (String id : idsString.split(",")) + { + Group group = groupService.find(context, UUID.fromString(id)); + groups.add(group); + } + + Division deleted = body.addInteractiveDivision("group-confirm-delete", + contextPath+"/admin/epeople", Division.METHOD_POST, + "primary administrative groups"); + deleted.setHead(T_head); + deleted.addPara(T_para); + + Table table = deleted.addTable("groups-list", groups.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); header.addCell().addContent(T_column4); - - for (Group group : groups) - { - Row row = table.addRow(); - row.addCell().addContent(group.getID().toString()); - row.addCell().addContent(group.getName()); - row.addCell().addContent(group.getMembers().size()); - row.addCell().addContent(group.getMemberGroups().size()); - } - - Para buttons = deleted.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_confirm); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - deleted.addHidden("administrative-continue").setValue(knot.getId()); + + for (Group group : groups) + { + Row row = table.addRow(); + row.addCell().addContent(group.getID().toString()); + row.addCell().addContent(group.getName()); + row.addCell().addContent(group.getMembers().size()); + row.addCell().addContent(group.getMemberGroups().size()); + } + + Para buttons = deleted.addPara(); + buttons.addButton("submit_confirm").setValue(T_submit_confirm); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + deleted.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/EditGroupForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/EditGroupForm.java index b510d40646..2022a7bd8f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/EditGroupForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/group/EditGroupForm.java @@ -31,297 +31,300 @@ import java.util.*; import java.util.List; /** - * Present the user with the group's current state. The user may select to - * change the group's name, OR search for new epeople / groups to add, OR select + * Present the user with the group's current state. The user may select to + * change the group's name, OR search for new epeople / groups to add, OR select * current group members for removal. - * + * * @author Alexey Maslov * @author Scott Phillips * @author Oriol Olivé - DS-3205 */ -public class EditGroupForm extends AbstractDSpaceTransformer +public class EditGroupForm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); - private static final Message T_group_trail = - message("xmlui.administrative.group.general.group_trail"); - - private static final Message T_title = - message("xmlui.administrative.group.EditGroupForm.title"); + private static final Message T_group_trail = + message("xmlui.administrative.group.general.group_trail"); - private static final Message T_trail = - message("xmlui.administrative.group.EditGroupForm.trail"); - - private static final Message T_main_head = - message("xmlui.administrative.group.EditGroupForm.main_head"); - - private static final Message T_collection_para = - message("xmlui.administrative.group.EditGroupForm.collection_para"); + private static final Message T_title = + message("xmlui.administrative.group.EditGroupForm.title"); - private static final Message T_community_para = + private static final Message T_trail = + message("xmlui.administrative.group.EditGroupForm.trail"); + + private static final Message T_main_head = + message("xmlui.administrative.group.EditGroupForm.main_head"); + + private static final Message T_collection_para = + message("xmlui.administrative.group.EditGroupForm.collection_para"); + + private static final Message T_community_para = message("xmlui.administrative.group.EditGroupForm.community_para"); - private static final Message T_label_name = - message("xmlui.administrative.group.EditGroupForm.label_name"); - - private static final Message T_label_instructions = - message("xmlui.administrative.group.EditGroupForm.label_instructions"); + private static final Message T_label_name = + message("xmlui.administrative.group.EditGroupForm.label_name"); - private static final Message T_label_search = - message("xmlui.administrative.group.EditGroupForm.label_search"); + private static final Message T_label_instructions = + message("xmlui.administrative.group.EditGroupForm.label_instructions"); - private static final Message T_submit_search_people = - message("xmlui.administrative.group.EditGroupForm.submit_search_people"); + private static final Message T_label_search = + message("xmlui.administrative.group.EditGroupForm.label_search"); - private static final Message T_submit_search_groups = - message("xmlui.administrative.group.EditGroupForm.submit_search_groups"); + private static final Message T_submit_search_people = + message("xmlui.administrative.group.EditGroupForm.submit_search_people"); - private static final Message T_no_results = - message("xmlui.administrative.group.EditGroupForm.no_results"); - - private static final Message T_main_head_new = - message("xmlui.administrative.group.EditGroupForm.main_head_new"); - - private static final Message T_submit_clear = - message("xmlui.administrative.group.EditGroupForm.submit_clear"); - - private static final Message T_submit_save = - message("xmlui.general.save"); - - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); - - private static final Message T_member = - message("xmlui.administrative.group.EditGroupForm.member"); - - private static final Message T_cycle = - message("xmlui.administrative.group.EditGroupForm.cycle"); - - private static final Message T_pending = - message("xmlui.administrative.group.EditGroupForm.pending"); - - private static final Message T_pending_warn = - message("xmlui.administrative.group.EditGroupForm.pending_warn"); - - private static final Message T_submit_add = - message("xmlui.administrative.group.EditGroupForm.submit_add"); - - private static final Message T_submit_remove = - message("xmlui.administrative.group.EditGroupForm.submit_remove"); - - - // EPeople Search - private static final Message T_epeople_column1 = - message("xmlui.administrative.group.EditGroupForm.epeople_column1"); - - private static final Message T_epeople_column2 = - message("xmlui.administrative.group.EditGroupForm.epeople_column2"); + private static final Message T_submit_search_groups = + message("xmlui.administrative.group.EditGroupForm.submit_search_groups"); - private static final Message T_epeople_column3 = - message("xmlui.administrative.group.EditGroupForm.epeople_column3"); + private static final Message T_no_results = + message("xmlui.administrative.group.EditGroupForm.no_results"); - private static final Message T_epeople_column4 = - message("xmlui.administrative.group.EditGroupForm.epeople_column4"); - - // Group Search - private static final Message T_groups_column1 = - message("xmlui.administrative.group.EditGroupForm.groups_column1"); - - private static final Message T_groups_column2 = - message("xmlui.administrative.group.EditGroupForm.groups_column2"); + private static final Message T_main_head_new = + message("xmlui.administrative.group.EditGroupForm.main_head_new"); - private static final Message T_groups_column3 = - message("xmlui.administrative.group.EditGroupForm.groups_column3"); + private static final Message T_submit_clear = + message("xmlui.administrative.group.EditGroupForm.submit_clear"); - private static final Message T_groups_column4 = - message("xmlui.administrative.group.EditGroupForm.groups_column4"); + private static final Message T_submit_save = + message("xmlui.general.save"); - private static final Message T_groups_column5 = - message("xmlui.administrative.group.EditGroupForm.groups_column5"); - - private static final Message T_groups_collection_link = - message("xmlui.administrative.group.ManageGroupsMain.groups_collection_link"); - - // Members - private static final Message T_members_head = - message("xmlui.administrative.group.EditGroupForm.members_head"); - - private static final Message T_members_column1 = - message("xmlui.administrative.group.EditGroupForm.members_column1"); - - private static final Message T_members_column2 = - message("xmlui.administrative.group.EditGroupForm.members_column2"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); - private static final Message T_members_column3 = - message("xmlui.administrative.group.EditGroupForm.members_column3"); + private static final Message T_member = + message("xmlui.administrative.group.EditGroupForm.member"); - private static final Message T_members_column4 = - message("xmlui.administrative.group.EditGroupForm.members_column4"); + private static final Message T_cycle = + message("xmlui.administrative.group.EditGroupForm.cycle"); - private static final Message T_members_group_name = - message("xmlui.administrative.group.EditGroupForm.members_group_name"); - - private static final Message T_members_pending = - message("xmlui.administrative.group.EditGroupForm.members_pending"); - - private static final Message T_members_none = - message("xmlui.administrative.group.EditGroupForm.members_none"); - - - // How many results to show on a page. - private static final int RESULTS_PER_PAGE = 5; - - /** The maximum size of a collection name allowed */ - private static final int MAX_COLLECTION_NAME = 25; + private static final Message T_pending = + message("xmlui.administrative.group.EditGroupForm.pending"); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); - protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + private static final Message T_pending_warn = + message("xmlui.administrative.group.EditGroupForm.pending_warn"); - public void addPageMeta(PageMeta pageMeta) throws WingException + private static final Message T_submit_add = + message("xmlui.administrative.group.EditGroupForm.submit_add"); + + private static final Message T_submit_remove = + message("xmlui.administrative.group.EditGroupForm.submit_remove"); + + // EPeople Search + private static final Message T_epeople_column1 = + message("xmlui.administrative.group.EditGroupForm.epeople_column1"); + + private static final Message T_epeople_column2 = + message("xmlui.administrative.group.EditGroupForm.epeople_column2"); + + private static final Message T_epeople_column3 = + message("xmlui.administrative.group.EditGroupForm.epeople_column3"); + + private static final Message T_epeople_column4 = + message("xmlui.administrative.group.EditGroupForm.epeople_column4"); + + // Group Search + private static final Message T_groups_column1 = + message("xmlui.administrative.group.EditGroupForm.groups_column1"); + + private static final Message T_groups_column2 = + message("xmlui.administrative.group.EditGroupForm.groups_column2"); + + private static final Message T_groups_column3 = + message("xmlui.administrative.group.EditGroupForm.groups_column3"); + + private static final Message T_groups_column4 = + message("xmlui.administrative.group.EditGroupForm.groups_column4"); + + private static final Message T_groups_column5 = + message("xmlui.administrative.group.EditGroupForm.groups_column5"); + + private static final Message T_groups_collection_link = + message("xmlui.administrative.group.ManageGroupsMain.groups_collection_link"); + + // Members + private static final Message T_members_head = + message("xmlui.administrative.group.EditGroupForm.members_head"); + + private static final Message T_members_column1 = + message("xmlui.administrative.group.EditGroupForm.members_column1"); + + private static final Message T_members_column2 = + message("xmlui.administrative.group.EditGroupForm.members_column2"); + + private static final Message T_members_column3 = + message("xmlui.administrative.group.EditGroupForm.members_column3"); + + private static final Message T_members_column4 = + message("xmlui.administrative.group.EditGroupForm.members_column4"); + + private static final Message T_members_group_name = + message("xmlui.administrative.group.EditGroupForm.members_group_name"); + + private static final Message T_members_pending = + message("xmlui.administrative.group.EditGroupForm.members_pending"); + + private static final Message T_members_none = + message("xmlui.administrative.group.EditGroupForm.members_none"); + + + // How many results to show on a page. + private static final int RESULTS_PER_PAGE = 5; + + /** The maximum size of a collection name allowed */ + private static final int MAX_COLLECTION_NAME = 25; + + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); + protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/groups",T_group_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException - { - // Find the group in question - UUID groupID = null; - if (StringUtils.isNotBlank(parameters.getParameter("groupID", null))) - { - groupID = UUID.fromString(parameters.getParameter("groupID",null)); - } - String currentName = decodeFromURL(parameters.getParameter("groupName",null)); - if (currentName == null || currentName.length() == 0) + + + public void addBody(Body body) + throws WingException, SQLException + { + // Find the group in question + UUID groupID = null; + if (StringUtils.isNotBlank(parameters.getParameter("groupID", null))) + { + groupID = UUID.fromString(parameters.getParameter("groupID",null)); + } + String currentName = decodeFromURL(parameters.getParameter("groupName",null)); + if (currentName == null || currentName.length() == 0) { currentName = FlowGroupUtils.getName(context, groupID); } - - Group group = null; - if (groupID != null) + + Group group = null; + if (groupID != null) { group = groupService.find(context, groupID); } - // Find the collection or community if applicable - Collection collection = null; - Community community = null; - if (group != null) - { - UUID collectionID = FlowGroupUtils.getCollectionId(context, group.getName()); - if (collectionID != null) + // Find the collection or community if applicable + Collection collection = null; + Community community = null; + if (group != null) + { + UUID collectionID = FlowGroupUtils.getCollectionId(context, group.getName()); + if (collectionID != null) { collection = collectionService.find(context, collectionID); } - else - { - UUID communityID = FlowGroupUtils.getCommunityId(context, group.getName()); - if (communityID != null) + else + { + UUID communityID = FlowGroupUtils.getCommunityId(context, group.getName()); + if (communityID != null) { community = communityService.find(context, communityID); } - } - } - - // Get list of member groups - String memberGroupIDsString = parameters.getParameter("memberGroupIDs",null); - List memberGroupIDs = new ArrayList(); - if (memberGroupIDsString != null) - { - for (String id : memberGroupIDsString.split(",")) - { - if (id.length() > 0) + } + } + + // Get list of member groups + String memberGroupIDsString = parameters.getParameter("memberGroupIDs",null); + List memberGroupIDs = new ArrayList(); + if (memberGroupIDsString != null) + { + for (String id : memberGroupIDsString.split(",")) + { + if (id.length() > 0) { memberGroupIDs.add(UUID.fromString(id)); } - } - } - - // Get list of member epeople - String memberEPeopleIDsString = parameters.getParameter("memberEPeopleIDs",null); - List memberEPeopleIDs = new ArrayList(); - if (memberEPeopleIDsString != null) - { - for (String id : memberEPeopleIDsString.split(",")) - { - if (id.length() > 0) - { - memberEPeopleIDs.add(UUID.fromString(id)); - } - } - } - - // Get highlight parameters - String highlightEPersonID = parameters.getParameter("highlightEPersonID", null); - String highlightGroupID = parameters.getParameter("highlightGroupID",null); - - // Get search parameters - String query = decodeFromURL(parameters.getParameter("query",null)); - int page = parameters.getParameterAsInteger("page",0); - String type = parameters.getParameter("type",null); - - // Get any errors - String errorString = parameters.getParameter("errors",null); - List errors = new ArrayList(); - if (errorString != null) - { - for (String error : errorString.split(",")) - { - errors.add(error); } } - - //DIVISION: group-edit - Division main = body.addInteractiveDivision("group-edit",contextPath+"/admin/groups",Division.METHOD_POST,"primary administrative groups"); - if (group == null) + + // Get list of member epeople + String memberEPeopleIDsString = parameters.getParameter("memberEPeopleIDs",null); + List memberEPeopleIDs = new ArrayList(); + if (memberEPeopleIDsString != null) + { + for (String id : memberEPeopleIDsString.split(",")) + { + if (id.length() > 0) + { + memberEPeopleIDs.add(UUID.fromString(id)); + } + } + } + + // Get highlight parameters + String highlightEPersonID = parameters.getParameter("highlightEPersonID", null); + String highlightGroupID = parameters.getParameter("highlightGroupID",null); + + // Get search parameters + String query = decodeFromURL(parameters.getParameter("query",null)); + int page = parameters.getParameterAsInteger("page",0); + String type = parameters.getParameter("type",null); + + // Get any errors + String errorString = parameters.getParameter("errors",null); + List errors = new ArrayList(); + if (errorString != null) + { + for (String error : errorString.split(",")) + { + errors.add(error); + } + } + + //DIVISION: group-edit + Division main = body.addInteractiveDivision("group-edit", + contextPath + "/admin/groups", Division.METHOD_POST, + "primary administrative groups"); + if (group == null) { main.setHead(T_main_head_new); } - else + else { main.setHead(T_main_head.parameterize(group.getName(), groupID)); } - - - if(collection != null) - { - Para para = main.addPara(); - para.addContent(T_collection_para); - para.addXref(contextPath + "/handle/" + collection.getHandle(), collectionService.getMetadata(collection, "name")); - } - else if(community != null) + + + if (collection != null) + { + Para para = main.addPara(); + para.addContent(T_collection_para); + para.addXref(contextPath + "/handle/" + collection.getHandle(), collectionService.getMetadata(collection, "name")); + } + else if (community != null) { Para para = main.addPara(); para.addContent(T_community_para); para.addXref(contextPath + "/handle/" + community.getHandle(), communityService.getMetadata(community, "name")); } - - // DIVISION: group-actions - Division actions = main.addDivision("group-edit-actions"); - Para groupName = actions.addPara(); + + // DIVISION: group-actions + Division actions = main.addDivision("group-edit-actions"); + Para groupName = actions.addPara(); groupName.addContent(T_label_name); Text groupText = groupName.addText("group_name"); groupText.setValue(currentName); - if(collection != null || community != null) + if (collection != null || community != null) { - // If this group is associated with a collection or community then it is special, - // thus they shouldn't be able to update it. - groupText.setDisabled(); - groupText.setHelp(T_label_instructions); + // If this group is associated with a collection or community then it is special, + // thus they shouldn't be able to update it. + groupText.setDisabled(); + groupText.setHelp(T_label_instructions); } else if (errors.contains("group_name") || errors.contains("group_name_duplicate")) { groupText.addError(""); } - + Para searchBoxes = actions.addPara(); searchBoxes.addContent(T_label_search); @@ -330,156 +333,151 @@ public class EditGroupForm extends AbstractDSpaceTransformer queryField.setSize(15); searchBoxes.addButton("submit_search_epeople").setValue(T_submit_search_people); searchBoxes.addButton("submit_search_groups").setValue(T_submit_search_groups); - - + + if (query != null) { - if ("eperson".equals(type)) - { - searchBoxes.addButton("submit_clear").setValue(T_submit_clear); - addEPeopleSearch(main,query,page,group,memberEPeopleIDs); - } - else if ("group".equals(type)) - { - searchBoxes.addButton("submit_clear").setValue(T_submit_clear); - addGroupSearch(main,group,query,page,group,memberGroupIDs); - } + if ("eperson".equals(type)) + { + searchBoxes.addButton("submit_clear").setValue(T_submit_clear); + addEPeopleSearch(main,query,page,group,memberEPeopleIDs); + } + else if ("group".equals(type)) + { + searchBoxes.addButton("submit_clear").setValue(T_submit_clear); + addGroupSearch(main,group,query,page,group,memberGroupIDs); + } } - + boolean changes = false; if (group != null) { changes = addMemberList(main, group, memberGroupIDs, memberEPeopleIDs, highlightEPersonID, highlightGroupID); } - - - Para buttons = main.addPara(); - buttons.addButton("submit_save").setValue(T_submit_save); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - if (changes) + + Para buttons = main.addPara(); + buttons.addButton("submit_save").setValue(T_submit_save); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + if (changes) { main.addPara().addHighlight("warn").addContent(T_pending_warn); } - - + main.addHidden("administrative-continue").setValue(knot.getId()); - } - - - - /** - * Search for epeople to add to this group. - */ - private void addEPeopleSearch(Division div, String query, int page, Group group, List memberEPeopleIDs) throws SQLException, WingException - { - int resultCount = ePersonService.searchResultCount(context, query); + } + + + /** + * Search for epeople to add to this group. + */ + private void addEPeopleSearch(Division div, String query, int page, Group group, List memberEPeopleIDs) + throws SQLException, WingException + { + int resultCount = ePersonService.searchResultCount(context, query); java.util.List epeople = ePersonService.search(context, query, page*RESULTS_PER_PAGE, RESULTS_PER_PAGE); - - Division results = div.addDivision("results"); - - if (resultCount > RESULTS_PER_PAGE) - { - // If there are enough results then paginate the results - String baseURL = contextPath +"/admin/groups?administrative-continue="+knot.getId(); - int firstIndex = page*RESULTS_PER_PAGE+1; - int lastIndex = page*RESULTS_PER_PAGE + epeople.size(); - - String nextURL = null, prevURL = null; - if (page < (resultCount / RESULTS_PER_PAGE)) + + Division results = div.addDivision("results"); + + if (resultCount > RESULTS_PER_PAGE) + { + // If there are enough results then paginate the results + String baseURL = contextPath + + "/admin/groups?administrative-continue=" + knot.getId(); + int firstIndex = page*RESULTS_PER_PAGE + 1; + int lastIndex = page*RESULTS_PER_PAGE + epeople.size(); + + String nextURL = null, prevURL = null; + if (page < (resultCount / RESULTS_PER_PAGE)) { nextURL = baseURL + "&page=" + (page + 1); } - if (page > 0) + if (page > 0) { prevURL = baseURL + "&page=" + (page - 1); } - - results.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL); - } - - /* Set up a table with search results (if there are any). */ - Table table = results.addTable("group-edit-search-eperson",epeople.size() + 1, 1); - Row header = table.addRow(Row.ROLE_HEADER); - header.addCell().addContent(T_epeople_column1); - header.addCell().addContent(T_epeople_column2); - header.addCell().addContent(T_epeople_column3); - header.addCell().addContent(T_epeople_column4); - for (EPerson person : epeople) - { - String epersonID = String.valueOf(person.getID()); - String fullName = person.getFullName(); - String email = person.getEmail(); - String url = contextPath+"/admin/epeople?administrative-continue="+knot.getId()+"&submit_edit_eperson&epersonID="+epersonID; - - - - Row personData = table.addRow(); + results.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL); + } - personData.addCell().addContent(person.getID().toString()); - personData.addCell().addXref(url, fullName); - personData.addCell().addXref(url, email); - - // check if they are already a member of the group - if (memberEPeopleIDs.contains(person.getID())) - { - // Check if they really members or just pending members - if (group != null && groupService.isDirectMember(group, person)) + /* Set up a table with search results (if there are any). */ + Table table = results.addTable("group-edit-search-eperson",epeople.size() + 1, 1); + Row header = table.addRow(Row.ROLE_HEADER); + header.addCell().addContent(T_epeople_column1); + header.addCell().addContent(T_epeople_column2); + header.addCell().addContent(T_epeople_column3); + header.addCell().addContent(T_epeople_column4); + + for (EPerson person : epeople) + { + String epersonID = String.valueOf(person.getID()); + String fullName = person.getFullName(); + String email = person.getEmail(); + String url = contextPath+"/admin/epeople?administrative-continue="+knot.getId()+"&submit_edit_eperson&epersonID="+epersonID; + + Row personData = table.addRow(); + + personData.addCell().addContent(person.getID().toString()); + personData.addCell().addXref(url, fullName); + personData.addCell().addXref(url, email); + + // check if they are already a member of the group + if (memberEPeopleIDs.contains(person.getID())) + { + // Check if they really members or just pending members + if (group != null && groupService.isDirectMember(group, person)) { personData.addCellContent(T_member); } - else + else { personData.addCell().addHighlight("warn").addContent(T_pending); } - } - else - { - personData.addCell().addButton("submit_add_eperson_"+epersonID).setValue(T_submit_add); - } - } + } + else + { + personData.addCell().addButton("submit_add_eperson_"+epersonID).setValue(T_submit_add); + } + } - if (epeople.size() <= 0) { - table.addRow().addCell(1, 4).addContent(T_no_results); - } - } - - - - - - /** - * Search for groups to add to this group. - */ - private void addGroupSearch(Division div, Group sourceGroup, String query, int page, Group parent, List memberGroupIDs) throws WingException, SQLException - { - int resultCount = groupService.searchResultCount(context, query); + if (epeople.size() <= 0) { + table.addRow().addCell(1, 4).addContent(T_no_results); + } + } + + + /** + * Search for groups to add to this group. + */ + private void addGroupSearch(Division div, Group sourceGroup, String query, int page, Group parent, List memberGroupIDs) + throws WingException, SQLException + { + int resultCount = groupService.searchResultCount(context, query); java.util.List groups = groupService.search(context, query, page*RESULTS_PER_PAGE, RESULTS_PER_PAGE); - - Division results = div.addDivision("results"); - - if (resultCount > RESULTS_PER_PAGE) - { - // If there are enough results then paginate the results - String baseURL = contextPath +"/admin/groups?administrative-continue="+knot.getId(); - int firstIndex = page*RESULTS_PER_PAGE+1; - int lastIndex = page*RESULTS_PER_PAGE + groups.size(); - - String nextURL = null, prevURL = null; - if (page < (resultCount / RESULTS_PER_PAGE)) + + Division results = div.addDivision("results"); + + if (resultCount > RESULTS_PER_PAGE) + { + // If there are enough results then paginate the results + String baseURL = contextPath +"/admin/groups?administrative-continue="+knot.getId(); + int firstIndex = page*RESULTS_PER_PAGE+1; + int lastIndex = page*RESULTS_PER_PAGE + groups.size(); + + String nextURL = null, prevURL = null; + if (page < (resultCount / RESULTS_PER_PAGE)) { nextURL = baseURL + "&page=" + (page + 1); } - if (page > 0) + if (page > 0) { prevURL = baseURL + "&page=" + (page - 1); } - - results.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL); - } -// DS-3205 fix + results.setSimplePagination(resultCount,firstIndex,lastIndex,prevURL, nextURL); + } + +// DS-3205 fix // Table table = results.addTable("roup-edit-search-group",groups.size() + 1, 1); Table table = results.addTable("group-edit-search-group",groups.size() + 1, 1); Row header = table.addRow(Row.ROLE_HEADER); @@ -487,302 +485,300 @@ public class EditGroupForm extends AbstractDSpaceTransformer header.addCell().addContent(T_groups_column2); header.addCell().addContent(T_groups_column3); header.addCell().addContent(T_groups_column4); - header.addCell().addContent(T_groups_column5); - + header.addCell().addContent(T_groups_column5); + for (Group group : groups) { - String groupID = String.valueOf(group.getID()); - String name = group.getName(); - String url = contextPath+"/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+groupID; - int memberCount = group.getMembers().size() + group.getMemberGroups().size(); - - Row row = table.addRow(); - - row.addCell().addContent(groupID); - if (authorizeService.isAdmin(context)) - // Only administrators can edit other groups. + String groupID = String.valueOf(group.getID()); + String name = group.getName(); + String url = contextPath+"/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+groupID; + int memberCount = group.getMembers().size() + group.getMemberGroups().size(); + + Row row = table.addRow(); + + row.addCell().addContent(groupID); + if (authorizeService.isAdmin(context)) + // Only administrators can edit other groups. { row.addCell().addXref(url, name); } - else + else { row.addCell().addContent(name); } - - - - row.addCell().addContent(memberCount == 0 ? "-" : String.valueOf(memberCount)); - - Cell cell = row.addCell(); - if (FlowGroupUtils.getCollectionId(context, group.getName()) != null) - { - Collection collection = collectionService.find(context, FlowGroupUtils.getCollectionId(context, group.getName()) ); - if (collection != null) - { - String collectionName = collectionService.getMetadata(collection, "name"); - - if (collectionName == null) + + + row.addCell().addContent(memberCount == 0 ? "-" : String.valueOf(memberCount)); + + Cell cell = row.addCell(); + if (FlowGroupUtils.getCollectionId(context, group.getName()) != null) + { + Collection collection = collectionService.find(context, FlowGroupUtils.getCollectionId(context, group.getName()) ); + if (collection != null) + { + String collectionName = collectionService.getMetadata(collection, "name"); + + if (collectionName == null) { collectionName = ""; } - else if (collectionName.length() > MAX_COLLECTION_NAME) + else if (collectionName.length() > MAX_COLLECTION_NAME) { collectionName = collectionName.substring(0, MAX_COLLECTION_NAME - 3) + "..."; } - - cell.addContent(collectionName+" "); - - Highlight highlight = cell.addHighlight("fade"); - highlight.addContent("["); - highlight.addXref(contextPath+"/handle/"+collection.getHandle(), T_groups_collection_link); - highlight.addContent("]"); - } - } - - - // Check if the group is already a member or would create a cycle. - if (memberGroupIDs.contains(group.getID())) - { - // Check if they really members or just pending members - if (parent != null && groupService.isMember(parent, group)) + + cell.addContent(collectionName+" "); + + Highlight highlight = cell.addHighlight("fade"); + highlight.addContent("["); + highlight.addXref(contextPath+"/handle/"+collection.getHandle(), T_groups_collection_link); + highlight.addContent("]"); + } + } + + + // Check if the group is already a member or would create a cycle. + if (memberGroupIDs.contains(group.getID())) + { + // Check if they really members or just pending members + if (parent != null && groupService.isMember(parent, group)) { row.addCellContent(T_member); } - else + else { row.addCell().addHighlight("warn").addContent(T_pending); } - } - else if (isDescendant(sourceGroup, group, memberGroupIDs)) - { - row.addCellContent(T_cycle); - } - else - { - row.addCell().addButton("submit_add_group_"+groupID).setValue(T_submit_add); - } - + } + else if (isDescendant(sourceGroup, group, memberGroupIDs)) + { + row.addCellContent(T_cycle); + } + else + { + row.addCell().addButton("submit_add_group_"+groupID).setValue(T_submit_add); + } + } if (groups.size() <= 0) { - table.addRow().addCell(1, 4).addContent(T_no_results); - } - } - - - - - - - /** - * Method to extensively check whether the first group has the second group as a distant - * parent. This is used to avoid creating cycles like A->B, B->C, C->D, D->A which leads - * all the groups involved to essentially include themselves. - */ - private boolean isDescendant(Group descendant, Group ancestor, List memberGroupIDs) throws SQLException - { - Queue toVisit = new LinkedList(); - Group currentGroup; - - toVisit.offer(ancestor); - - // Initialize by adding a list of our current list of group members. - for (UUID groupid : memberGroupIDs) - { - Group member = groupService.find(context,groupid); - toVisit.offer(member); - } - - while (!toVisit.isEmpty()) { - // 1. Grab a group from the queue - currentGroup = toVisit.poll(); - - // 2. See if it's the descendant we're looking for - if (currentGroup.equals(descendant)) { + table.addRow().addCell(1, 4).addContent(T_no_results); + } + } + + + /** + * Method to extensively check whether the first group has the second group as a distant + * parent. This is used to avoid creating cycles like A->B, B->C, C->D, D->A which leads + * all the groups involved to essentially include themselves. + */ + private boolean isDescendant(Group descendant, Group ancestor, List memberGroupIDs) + throws SQLException + { + Queue toVisit = new LinkedList(); + Group currentGroup; + + toVisit.offer(ancestor); + + // Initialize by adding a list of our current list of group members. + for (UUID groupid : memberGroupIDs) + { + Group member = groupService.find(context,groupid); + toVisit.offer(member); + } + + while (!toVisit.isEmpty()) { + // 1. Grab a group from the queue + currentGroup = toVisit.poll(); + + // 2. See if it's the descendant we're looking for + if (currentGroup.equals(descendant)) { return true; } - - // 3. If not, add that group's children to the queue - for (Group nextBatch : currentGroup.getMemberGroups()) { - toVisit.offer(nextBatch); - } - } - return false; - } - - - - - - - /** - * Add a table with all the current group's members to the specified division. - * @throws SQLException - */ - private boolean addMemberList(Division div, Group parent, List memberGroupIDs, List memberEPeopleIDs, String highlightEPersonID, String highlightGroupID) throws WingException, SQLException - { - // Flag to remember if there are any pending changes. + + // 3. If not, add that group's children to the queue + for (Group nextBatch : currentGroup.getMemberGroups()) { + toVisit.offer(nextBatch); + } + } + return false; + } + + + /** + * Add a table with all the current group's members to the specified division. + * @throws SQLException + */ + private boolean addMemberList(Division div, Group parent, List memberGroupIDs, List memberEPeopleIDs, String highlightEPersonID, String highlightGroupID) + throws WingException, SQLException + { + // Flag to remember if there are any pending changes. boolean changes = false; - + Division members = div.addDivision("group-edit-members"); members.setHead(T_members_head); - + Table table = members.addTable("group-edit-members-table",memberGroupIDs.size() + memberEPeopleIDs.size() + 1, 4); - + Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_members_column1); header.addCell().addContent(T_members_column2); header.addCell().addContent(T_members_column3); header.addCell().addContent(T_members_column4); - + // get all group members, pend or actual @SuppressWarnings("unchecked") // the cast is correct List allMemberGroupIDs = new ArrayList(memberGroupIDs); for (Group group : parent.getMemberGroups()) { - if (!allMemberGroupIDs.contains(group.getID())) + if (!allMemberGroupIDs.contains(group.getID())) { allMemberGroupIDs.add(group.getID()); } } // Sort them to a consistent ordering Collections.sort(allMemberGroupIDs); - + // Loop through all group ids and display them. for (UUID groupID : allMemberGroupIDs) { - Group group = groupService.find(context,groupID); - boolean highlight = (group.getID().toString().equals(highlightGroupID)); - boolean pendingAddition = !groupService.isMember(parent, group); - boolean pendingRemoval = !memberGroupIDs.contains(groupID); - addMemberRow(table, group, highlight,pendingAddition,pendingRemoval); - - if (pendingAddition || pendingRemoval) + Group group = groupService.find(context,groupID); + boolean highlight = (group.getID().toString().equals(highlightGroupID)); + boolean pendingAddition = !groupService.isMember(parent, group); + boolean pendingRemoval = !memberGroupIDs.contains(groupID); + addMemberRow(table, group, highlight,pendingAddition,pendingRemoval); + + if (pendingAddition || pendingRemoval) { changes = true; } } - - + + // get all members, pend or actual @SuppressWarnings("unchecked") // the cast is correct List allMemberEPeopleIDs = new ArrayList(memberEPeopleIDs); for (EPerson eperson : parent.getMembers()) { - if (!allMemberEPeopleIDs.contains(eperson.getID())) + if (!allMemberEPeopleIDs.contains(eperson.getID())) { allMemberEPeopleIDs.add(eperson.getID()); } } // Sort them to a consistent ordering Collections.sort(allMemberEPeopleIDs); - + for (UUID epersonID : allMemberEPeopleIDs) { - EPerson eperson = ePersonService.find(context, epersonID); - boolean highlight = (eperson.getID().toString().equals(highlightEPersonID)); - boolean pendingAddition = !groupService.isDirectMember(parent, eperson); - boolean pendingRemoval = !memberEPeopleIDs.contains(epersonID); - addMemberRow(table,eperson,highlight,pendingAddition,pendingRemoval); - - if (pendingAddition || pendingRemoval) + EPerson eperson = ePersonService.find(context, epersonID); + boolean highlight = (eperson.getID().toString().equals(highlightEPersonID)); + boolean pendingAddition = !groupService.isDirectMember(parent, eperson); + boolean pendingRemoval = !memberEPeopleIDs.contains(epersonID); + addMemberRow(table,eperson,highlight,pendingAddition,pendingRemoval); + + if (pendingAddition || pendingRemoval) { changes = true; } } - + if (allMemberGroupIDs.size() <= 0 && allMemberEPeopleIDs.size() <= 0) { - table.addRow().addCell(1, 4).addContent(T_members_none); + table.addRow().addCell(1, 4).addContent(T_members_none); } - + return changes; - } - - - /** - * Add a single member row for groups. - * - * @param table The table to add the row too. - * @param group The group being displayed in this row. - * @param highlight Should the row be highlighted. - * @param pendingAddition Is this group pending addition - * @param pendingRemoval Is this group pending removal - */ - private void addMemberRow(Table table,Group group, boolean highlight, boolean pendingAddition, boolean pendingRemoval) throws WingException, SQLException - { - String name = group.getName(); - String url = contextPath+"/admin/groups?administrative-continue="+knot.getId()+"&submit_edit_group&groupID="+group.getID(); - - Row groupData = table.addRow(null,null,highlight ? "highlight" : null); - - groupData.addCell().addHighlight("bold").addContent(group.getID().toString()); - - // Mark if this member is pending or not. - Cell nameCell = groupData.addCell(); - if (authorizeService.isAdmin(context)) + } + + + /** + * Add a single member row for groups. + * + * @param table The table to add the row too. + * @param group The group being displayed in this row. + * @param highlight Should the row be highlighted. + * @param pendingAddition Is this group pending addition + * @param pendingRemoval Is this group pending removal + */ + private void addMemberRow(Table table, Group group, boolean highlight, boolean pendingAddition, boolean pendingRemoval) + throws WingException, SQLException + { + String name = group.getName(); + String url = contextPath + "/admin/groups?administrative-continue=" + + knot.getId() + "&submit_edit_group&groupID=" + group.getID(); + + Row groupData = table.addRow(null,null,highlight ? "highlight" : null); + + groupData.addCell().addHighlight("bold").addContent(group.getID().toString()); + + // Mark if this member is pending or not. + Cell nameCell = groupData.addCell(); + if (authorizeService.isAdmin(context)) { nameCell.addHighlight("bold").addXref(url, T_members_group_name.parameterize(name)); } - else + else { nameCell.addHighlight("bold").addContent(T_members_group_name.parameterize(name)); } - - if (pendingAddition) - { - nameCell.addContent(" "); - nameCell.addHighlight("warn").addContent(T_members_pending); - } - - groupData.addCell().addContent("-"); - - if (pendingRemoval) + + if (pendingAddition) + { + nameCell.addContent(" "); + nameCell.addHighlight("warn").addContent(T_members_pending); + } + + groupData.addCell().addContent("-"); + + if (pendingRemoval) { groupData.addCell().addHighlight("warn").addContent(T_pending); } - else + else { groupData.addCell().addButton("submit_remove_group_" + group.getID()).setValue(T_submit_remove); } - } - - /** - * Add a single member row for epeople. - * - * @param table The table to add a row too. - * @param eperson The eperson being displayed - * @param highlight Should this eperson be highlighted? - * @param pendingAddition Is this eperson pending addition? - * @param pendingRemoval Is this eperson pending removal? - */ - private void addMemberRow(Table table, EPerson eperson, boolean highlight, boolean pendingAddition, boolean pendingRemoval) throws WingException, SQLException - { - String fullName = eperson.getFullName(); - String email = eperson.getEmail(); - String url = contextPath+"/admin/epeople?administrative-continue="+knot.getId()+"&submit_edit_eperson&epersonID="+eperson.getID(); - - - Row personData = table.addRow(null,null,highlight ? "highlight" : null); - - personData.addCell().addContent(eperson.getID().toString()); - - Cell nameCell = personData.addCell(); - nameCell.addXref(url, fullName); - if (pendingAddition) - { - nameCell.addContent(" "); - nameCell.addHighlight("warn").addContent(T_members_pending); - } - - personData.addCell().addXref(url, email); - - if (pendingRemoval) + } + + /** + * Add a single member row for epeople. + * + * @param table The table to add a row too. + * @param eperson The eperson being displayed + * @param highlight Should this eperson be highlighted? + * @param pendingAddition Is this eperson pending addition? + * @param pendingRemoval Is this eperson pending removal? + */ + private void addMemberRow(Table table, EPerson eperson, boolean highlight, boolean pendingAddition, boolean pendingRemoval) + throws WingException, SQLException + { + String fullName = eperson.getFullName(); + String email = eperson.getEmail(); + String url = contextPath + "/admin/epeople?administrative-continue=" + + knot.getId() + "&submit_edit_eperson&epersonID=" + eperson.getID(); + + + Row personData = table.addRow(null,null,highlight ? "highlight" : null); + + personData.addCell().addContent(eperson.getID().toString()); + + Cell nameCell = personData.addCell(); + nameCell.addXref(url, fullName); + if (pendingAddition) + { + nameCell.addContent(" "); + nameCell.addHighlight("warn").addContent(T_members_pending); + } + + personData.addCell().addXref(url, email); + + if (pendingRemoval) { personData.addCell().addHighlight("warn").addContent(T_pending); } - else + else { - personData.addCell().addButton("submit_remove_eperson_" + eperson.getID()).setValue(T_submit_remove); + personData.addCell().addButton("submit_remove_eperson_" + + eperson.getID()).setValue(T_submit_remove); } - } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ConfirmItemForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ConfirmItemForm.java index a3b6678f5d..3b8e0741ab 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ConfirmItemForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ConfirmItemForm.java @@ -34,108 +34,113 @@ import org.dspace.content.service.ItemService; * This page is used as a general confirmation page for any * actions on items. It will display the item and ask if the * user is sure they want to perform the action. - * + * * The "confirm" parameter determines what action is confirmed. * There are three possible values, "delete", "withdraw", or * "reinstate" - * + * * @author Jay Paz * @author Scott Phillips */ public class ConfirmItemForm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); - - private static final Message T_title = message("xmlui.administrative.item.ConfirmItemForm.title"); - private static final Message T_trail = message("xmlui.administrative.item.ConfirmItemForm.trail"); - private static final Message T_head1 = message("xmlui.administrative.item.ConfirmItemForm.head1"); - private static final Message T_para_delete = message("xmlui.administrative.item.ConfirmItemForm.para_delete"); - private static final Message T_para_withdraw = message("xmlui.administrative.item.ConfirmItemForm.para_withdraw"); - private static final Message T_para_reinstate = message("xmlui.administrative.item.ConfirmItemForm.para_reinstate"); - private static final Message T_column1 = message("xmlui.administrative.item.ConfirmItemForm.column1"); - private static final Message T_column2 = message("xmlui.administrative.item.ConfirmItemForm.column2"); - private static final Message T_column3 = message("xmlui.administrative.item.ConfirmItemForm.column3"); - private static final Message T_submit_delete = message("xmlui.general.delete"); - private static final Message T_submit_withdraw = message("xmlui.administrative.item.ConfirmItemForm.submit_withdraw"); - private static final Message T_submit_reinstate = message("xmlui.administrative.item.ConfirmItemForm.submit_reinstate"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); + + private static final Message T_title = message("xmlui.administrative.item.ConfirmItemForm.title"); + private static final Message T_trail = message("xmlui.administrative.item.ConfirmItemForm.trail"); + private static final Message T_head1 = message("xmlui.administrative.item.ConfirmItemForm.head1"); + private static final Message T_para_delete = message("xmlui.administrative.item.ConfirmItemForm.para_delete"); + private static final Message T_para_withdraw = message("xmlui.administrative.item.ConfirmItemForm.para_withdraw"); + private static final Message T_para_reinstate = message("xmlui.administrative.item.ConfirmItemForm.para_reinstate"); + private static final Message T_column1 = message("xmlui.administrative.item.ConfirmItemForm.column1"); + private static final Message T_column2 = message("xmlui.administrative.item.ConfirmItemForm.column2"); + private static final Message T_column3 = message("xmlui.administrative.item.ConfirmItemForm.column3"); + private static final Message T_submit_delete = message("xmlui.general.delete"); + private static final Message T_submit_withdraw = message("xmlui.administrative.item.ConfirmItemForm.submit_withdraw"); + private static final Message T_submit_reinstate = message("xmlui.administrative.item.ConfirmItemForm.submit_reinstate"); private static final Message T_submit_private = message("xmlui.administrative.item.ConfirmItemForm.submit_private"); private static final Message T_submit_public = message("xmlui.administrative.item.ConfirmItemForm.submit_public"); - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - @SuppressWarnings("unchecked") // the cast is correct - public void addBody(Body body) throws WingException, SQLException - { - // Get our parameters and state - UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); - Item item = itemService.find(context, itemID); - final java.util.List values = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); - Collections.sort(values, new DCValueComparator()); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } - String confirm = parameters.getParameter("confirm",null); + @SuppressWarnings("unchecked") // the cast is correct + public void addBody(Body body) + throws WingException, SQLException + { + // Get our parameters and state + UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); + Item item = itemService.find(context, itemID); + final java.util.List values = itemService.getMetadata( + item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); + Collections.sort(values, new DCValueComparator()); + + String confirm = parameters.getParameter("confirm",null); - // DIVISION: Main - Division main = body.addInteractiveDivision("confirm-item", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative item"); - main.setHead(T_head1.parameterize(item.getHandle())); + // DIVISION: Main + Division main = body.addInteractiveDivision("confirm-item", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative item"); + main.setHead(T_head1.parameterize(item.getHandle())); - // PARA: descriptive instructions - if("delete".equals(confirm)) - { - main.addPara(T_para_delete); - } - else if ("reinstate".equals(confirm)) - { - main.addPara(T_para_reinstate); - } - else if ("withdraw".equals(confirm)) - { - main.addPara(T_para_withdraw); - } + // PARA: descriptive instructions + if("delete".equals(confirm)) + { + main.addPara(T_para_delete); + } + else if ("reinstate".equals(confirm)) + { + main.addPara(T_para_reinstate); + } + else if ("withdraw".equals(confirm)) + { + main.addPara(T_para_withdraw); + } - // TABLE: metadata table - Table table = main.addTable("withdrawValues", values.size()+1, 3); - final Row header = table.addRow(Row.ROLE_HEADER); - header.addCell().addContent(T_column1); - header.addCell().addContent(T_column2); - header.addCell().addContent(T_column3); - for(final MetadataValue value:values){ - MetadataField metadataField = value.getMetadataField(); - final String dcValue = metadataField.getMetadataSchema().getName() + ". " + metadataField.getElement() + (metadataField.getQualifier()==null?"":(". " + metadataField.getQualifier())); - final Row row = table.addRow(); - row.addCell().addContent(dcValue); - row.addCell().addContent(value.getValue()); - row.addCell().addContent(value.getLanguage()); - } + // TABLE: metadata table + Table table = main.addTable("withdrawValues", values.size() + 1, 3); + final Row header = table.addRow(Row.ROLE_HEADER); + header.addCell().addContent(T_column1); + header.addCell().addContent(T_column2); + header.addCell().addContent(T_column3); + for (final MetadataValue value:values) + { + MetadataField metadataField = value.getMetadataField(); + final String dcValue = metadataField.getMetadataSchema().getName() + + ". " + metadataField.getElement() + + (metadataField.getQualifier() == null ? "" : (". " + metadataField.getQualifier())); + final Row row = table.addRow(); + row.addCell().addContent(dcValue); + row.addCell().addContent(value.getValue()); + row.addCell().addContent(value.getLanguage()); + } - // LIST: actions, confirm or return - org.dspace.app.xmlui.wing.element.Item actions = main.addList("actions", List.TYPE_FORM).addItem(); + // LIST: actions, confirm or return + org.dspace.app.xmlui.wing.element.Item actions = main.addList("actions", List.TYPE_FORM).addItem(); - Button confirmButton = actions.addButton("submit_confirm"); + Button confirmButton = actions.addButton("submit_confirm"); - if("delete".equals(confirm)) - { - confirmButton.setValue(T_submit_delete); - } - else if ("reinstate".equals(confirm)) - { - confirmButton.setValue(T_submit_reinstate); - } + if("delete".equals(confirm)) + { + confirmButton.setValue(T_submit_delete); + } + else if ("reinstate".equals(confirm)) + { + confirmButton.setValue(T_submit_reinstate); + } else if ("private".equals(confirm)) { confirmButton.setValue(T_submit_private); @@ -144,29 +149,32 @@ public class ConfirmItemForm extends AbstractDSpaceTransformer { { confirmButton.setValue(T_submit_public); } - else if ("withdraw".equals(confirm)) - { - confirmButton.setValue(T_submit_withdraw); - } - actions.addButton("submit_cancel").setValue(T_submit_cancel); + else if ("withdraw".equals(confirm)) + { + confirmButton.setValue(T_submit_withdraw); + } + actions.addButton("submit_cancel").setValue(T_submit_cancel); - main.addHidden("administrative-continue").setValue(knot.getId()); - } + main.addHidden("administrative-continue").setValue(knot.getId()); + } - /** - * Compare names of two metadata elements so that they may be sorted. - */ - static class DCValueComparator implements Comparator, Serializable { - public int compare(Object arg0, Object arg1) { - final MetadataValue o1 = (MetadataValue)arg0; - final MetadataValue o2 = (MetadataValue)arg1; - MetadataField o1Field = o1.getMetadataField(); - MetadataField o2Field = o2.getMetadataField(); - final String s1 = o1Field.getMetadataSchema().getName() + o1Field.getElement() + (o1Field.getQualifier()==null?"":("." + o1Field.getQualifier())); - final String s2 = o2Field.getMetadataSchema().getName() + o2Field.getElement() + (o2Field.getQualifier()==null?"":("." + o2Field.getQualifier())); - return s1.compareTo(s2); - } - } - + /** + * Compare names of two metadata elements so that they may be sorted. + */ + static class DCValueComparator implements Comparator, Serializable { + public int compare(Object arg0, Object arg1) { + final MetadataValue o1 = (MetadataValue)arg0; + final MetadataValue o2 = (MetadataValue)arg1; + MetadataField o1Field = o1.getMetadataField(); + MetadataField o2Field = o2.getMetadataField(); + final String s1 = o1Field.getMetadataSchema().getName() + + o1Field.getElement() + + (o1Field.getQualifier() == null ? "" : ("." + o1Field.getQualifier())); + final String s2 = o2Field.getMetadataSchema().getName() + + o2Field.getElement() + + (o2Field.getQualifier() == null ? "" : ("." + o2Field.getQualifier())); + return s1.compareTo(s2); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/CurateItemForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/CurateItemForm.java index 82e28c0f5a..238eddebfd 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/CurateItemForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/CurateItemForm.java @@ -39,21 +39,21 @@ import org.dspace.authorize.AuthorizeException; */ public class CurateItemForm extends AbstractDSpaceTransformer { - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_perform = message("xmlui.general.perform"); - private static final Message T_submit_queue = message("xmlui.general.queue"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); - private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); - private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); - private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); - private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); - private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); - private static final Message T_title = message("xmlui.administrative.item.CurateItemForm.title"); - private static final Message T_trail = message("xmlui.administrative.item.CurateItemForm.trail"); - private static final Message T_label_name = message("xmlui.administrative.item.CurateItemForm.label_name"); - private static final Message T_taskgroup_label_name = message("xmlui.administrative.CurateForm.taskgroup_label_name"); + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_perform = message("xmlui.general.perform"); + private static final Message T_submit_queue = message("xmlui.general.queue"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); + private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); + private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); + private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); + private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); + private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); + private static final Message T_title = message("xmlui.administrative.item.CurateItemForm.title"); + private static final Message T_trail = message("xmlui.administrative.item.CurateItemForm.trail"); + private static final Message T_label_name = message("xmlui.administrative.item.CurateItemForm.label_name"); + private static final Message T_taskgroup_label_name = message("xmlui.administrative.CurateForm.taskgroup_label_name"); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); @@ -68,20 +68,22 @@ public class CurateItemForm extends AbstractDSpaceTransformer { * @throws IOException passed through. */ @Override - public void setup(SourceResolver resolver, Map objectModel, String src, - Parameters parameters) throws ProcessingException, SAXException, IOException - { - super.setup(resolver, objectModel, src, parameters); - FlowCurationUtils.setupCurationTasks(); - } + public void setup(SourceResolver resolver, Map objectModel, String src, + Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver, objectModel, src, parameters); + FlowCurationUtils.setupCurationTasks(); + } @Override - public void addPageMeta(PageMeta pageMeta) throws WingException + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); - pageMeta.addTrail().addContent(T_trail); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); + pageMeta.addTrail().addContent(T_trail); } /** @@ -93,37 +95,40 @@ public class CurateItemForm extends AbstractDSpaceTransformer { @Override public void addBody(Body body) throws WingException, SQLException, AuthorizeException, UnsupportedEncodingException - { - String baseURL = contextPath + "/admin/item?administrative-continue=" - + knot.getId() ; + { + String baseURL = contextPath + "/admin/item?administrative-continue=" + + knot.getId() ; - // DIVISION: main - Division main = body.addInteractiveDivision("edit-item-status", contextPath + "/admin/item", Division.METHOD_POST,"primary administrative edit-item-status"); - main.setHead(T_option_head); + // DIVISION: main + Division main = body.addInteractiveDivision("edit-item-status", + contextPath + "/admin/item", Division.METHOD_POST, + "primary administrative edit-item-status"); + main.setHead(T_option_head); - // LIST: options - List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); - options.addItem().addXref(baseURL + "&submit_status", T_option_status); - options.addItem().addXref(baseURL + "&submit_bitstreams", T_option_bitstreams); - options.addItem().addXref(baseURL + "&submit_metadata", T_option_metadata); - options.addItem().addXref(baseURL + "&view_item", T_option_view); - options.addItem().addHighlight("bold").addXref(baseURL + "&submit_curate", T_option_curate); - + // LIST: options + List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); + options.addItem().addXref(baseURL + "&submit_status", T_option_status); + options.addItem().addXref(baseURL + "&submit_bitstreams", T_option_bitstreams); + options.addItem().addXref(baseURL + "&submit_metadata", T_option_metadata); + options.addItem().addXref(baseURL + "&view_item", T_option_view); + options.addItem().addHighlight("bold").addXref(baseURL + "&submit_curate", T_option_curate); - List curationTaskList = main.addList("curationTaskList", "form"); + List curationTaskList = main.addList("curationTaskList", "form"); String curateGroup = ""; try { - curateGroup = (parameters.getParameter("select_curate_group") != null) ? parameters.getParameter("select_curate_group") : FlowCurationUtils.UNGROUPED_TASKS; + curateGroup = (parameters.getParameter("select_curate_group") != null) + ? parameters.getParameter("select_curate_group") + : FlowCurationUtils.UNGROUPED_TASKS; } catch (Exception pe) { - // noop + // noop } if (!FlowCurationUtils.groups.isEmpty()) { - curationTaskList.addLabel(T_taskgroup_label_name); //needs to check for >=1 group configured + curationTaskList.addLabel(T_taskgroup_label_name); //needs to check for >=1 group configured Select groupSelect = curationTaskList.addItem().addSelect("select_curate_group"); groupSelect = FlowCurationUtils.getGroupSelectOptions(groupSelect); groupSelect.setSize(1); @@ -131,7 +136,7 @@ public class CurateItemForm extends AbstractDSpaceTransformer { groupSelect.setEvtBehavior("submitOnChange"); if (curateGroup.equals("")) { - curateGroup = (String) (FlowCurationUtils.groups.keySet().iterator().next()); + curateGroup = (String) (FlowCurationUtils.groups.keySet().iterator().next()); } groupSelect.setOptionSelected(curateGroup); } @@ -142,16 +147,16 @@ public class CurateItemForm extends AbstractDSpaceTransformer { taskSelect.setSize(1); taskSelect.setRequired(); - // need submit_curate_task and submit_return - Para buttonList = main.addPara(); + // need submit_curate_task and submit_return + Para buttonList = main.addPara(); buttonList.addButton("submit_curate_task").setValue(T_submit_perform); buttonList.addButton("submit_queue_task").setValue(T_submit_queue); - buttonList.addButton("submit_return").setValue(T_submit_return); + buttonList.addButton("submit_return").setValue(T_submit_return); main.addHidden("administrative-continue").setValue(knot.getId()); } - // Add a method here to build it into the dspace.cfg ... ui.curation_tasks = estimate = "Estate" - // Mapping the task name to either the description or the mapping key + // Add a method here to build it into the dspace.cfg ... ui.curation_tasks = estimate = "Estate" + // Mapping the task name to either the description or the mapping key } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/DeleteBitstreamsConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/DeleteBitstreamsConfirm.java index e8d256b4c1..969da91572 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/DeleteBitstreamsConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/DeleteBitstreamsConfirm.java @@ -29,89 +29,89 @@ import org.dspace.content.service.BitstreamService; /** * Present the user with a list of not-yet-but-soon-to-be-deleted-bitstreams. - * + * * @author Scott Phillips */ -public class DeleteBitstreamsConfirm extends AbstractDSpaceTransformer +public class DeleteBitstreamsConfirm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - - - private static final Message T_title = message("xmlui.administrative.item.DeleteBitstreamConfirm.title"); - private static final Message T_trail = message("xmlui.administrative.item.DeleteBitstreamConfirm.trail"); - private static final Message T_head1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.head1"); - private static final Message T_para1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.para1"); - private static final Message T_column1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column1"); - private static final Message T_column2 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column2"); - private static final Message T_column3 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column3"); - private static final Message T_submit_delete = message("xmlui.general.delete"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_title = message("xmlui.administrative.item.DeleteBitstreamConfirm.title"); + private static final Message T_trail = message("xmlui.administrative.item.DeleteBitstreamConfirm.trail"); + private static final Message T_head1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.head1"); + private static final Message T_para1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.para1"); + private static final Message T_column1 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column1"); + private static final Message T_column2 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column2"); + private static final Message T_column3 = message("xmlui.administrative.item.DeleteBitstreamConfirm.column3"); + private static final Message T_submit_delete = message("xmlui.general.delete"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); - protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); + protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - String idsString = parameters.getParameter("bitstreamIDs", null); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } - ArrayList bitstreams = new ArrayList(); - for (String id : idsString.split(",")) - { - String[] parts = id.split("/"); + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + String idsString = parameters.getParameter("bitstreamIDs", null); - if (parts.length != 2) + ArrayList bitstreams = new ArrayList(); + for (String id : idsString.split(",")) + { + String[] parts = id.split("/"); + + if (parts.length != 2) { throw new UIException("Unable to parse id into bundle and bitstream id: " + id); } - UUID bitstreamID = UUID.fromString(parts[1]); + UUID bitstreamID = UUID.fromString(parts[1]); - Bitstream bitstream = bitstreamService.find(context,bitstreamID); - bitstreams.add(bitstream); + Bitstream bitstream = bitstreamService.find(context,bitstreamID); + bitstreams.add(bitstream); - } + } - // DIVISION: bitstream-confirm-delete - Division deleted = body.addInteractiveDivision("bitstreams-confirm-delete",contextPath+"/admin/item",Division.METHOD_POST,"primary administrative item"); - deleted.setHead(T_head1); - deleted.addPara(T_para1); + // DIVISION: bitstream-confirm-delete + Division deleted = body.addInteractiveDivision("bitstreams-confirm-delete",contextPath+"/admin/item",Division.METHOD_POST,"primary administrative item"); + deleted.setHead(T_head1); + deleted.addPara(T_para1); - Table table = deleted.addTable("bitstreams-confirm-delete",bitstreams.size() + 1, 1); + Table table = deleted.addTable("bitstreams-confirm-delete",bitstreams.size() + 1, 1); - Row header = table.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column1); - header.addCellContent(T_column2); - header.addCellContent(T_column3); + Row header = table.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column1); + header.addCellContent(T_column2); + header.addCellContent(T_column3); - for (Bitstream bitstream : bitstreams) - { - String format = null; - BitstreamFormat bitstreamFormat = bitstream.getFormat(context); - if (bitstreamFormat != null) + for (Bitstream bitstream : bitstreams) + { + String format = null; + BitstreamFormat bitstreamFormat = bitstream.getFormat(context); + if (bitstreamFormat != null) { format = bitstreamFormat.getShortDescription(); } - Row row = table.addRow(); - row.addCell().addContent(bitstream.getName()); - row.addCell().addContent(bitstream.getDescription()); - row.addCell().addContent(format); - } - Para buttons = deleted.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_delete); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); + Row row = table.addRow(); + row.addCell().addContent(bitstream.getName()); + row.addCell().addContent(bitstream.getDescription()); + row.addCell().addContent(format); + } + Para buttons = deleted.addPara(); + buttons.addButton("submit_confirm").setValue(T_submit_delete); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); - deleted.addHidden("administrative-continue").setValue(knot.getId()); - } + deleted.addHidden("administrative-continue").setValue(knot.getId()); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditBitstreamForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditBitstreamForm.java index fcfbc9dc11..3811a83788 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditBitstreamForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditBitstreamForm.java @@ -35,7 +35,7 @@ import org.dspace.services.factory.DSpaceServicesFactory; import org.xml.sax.SAXException; /** - * + * * Show a form allowing the user to edit a bitstream's metadata, the description * and format. * @@ -44,88 +44,90 @@ import org.xml.sax.SAXException; public class EditBitstreamForm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_save = message("xmlui.general.save"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - - private static final Message T_title = message("xmlui.administrative.item.EditBitstreamForm.title"); - private static final Message T_trail = message("xmlui.administrative.item.EditBitstreamForm.trail"); - private static final Message T_head1 = message("xmlui.administrative.item.EditBitstreamForm.head1"); - private static final Message T_file_label = message("xmlui.administrative.item.EditBitstreamForm.file_label"); - private static final Message T_primary_label = message("xmlui.administrative.item.EditBitstreamForm.primary_label"); - private static final Message T_primary_option_yes = message("xmlui.administrative.item.EditBitstreamForm.primary_option_yes"); - private static final Message T_primary_option_no = message("xmlui.administrative.item.EditBitstreamForm.primary_option_no"); - private static final Message T_description_label = message("xmlui.administrative.item.EditBitstreamForm.description_label"); - private static final Message T_description_help = message("xmlui.administrative.item.EditBitstreamForm.description_help"); - private static final Message T_para1 = message("xmlui.administrative.item.EditBitstreamForm.para1"); - private static final Message T_format_label = message("xmlui.administrative.item.EditBitstreamForm.format_label"); - private static final Message T_format_default = message("xmlui.administrative.item.EditBitstreamForm.format_default"); - private static final Message T_para2 = message("xmlui.administrative.item.EditBitstreamForm.para2"); - private static final Message T_user_label = message("xmlui.administrative.item.EditBitstreamForm.user_label"); - private static final Message T_user_help = message("xmlui.administrative.item.EditBitstreamForm.user_help"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_save = message("xmlui.general.save"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + + private static final Message T_title = message("xmlui.administrative.item.EditBitstreamForm.title"); + private static final Message T_trail = message("xmlui.administrative.item.EditBitstreamForm.trail"); + private static final Message T_head1 = message("xmlui.administrative.item.EditBitstreamForm.head1"); + private static final Message T_file_label = message("xmlui.administrative.item.EditBitstreamForm.file_label"); + private static final Message T_primary_label = message("xmlui.administrative.item.EditBitstreamForm.primary_label"); + private static final Message T_primary_option_yes = message("xmlui.administrative.item.EditBitstreamForm.primary_option_yes"); + private static final Message T_primary_option_no = message("xmlui.administrative.item.EditBitstreamForm.primary_option_no"); + private static final Message T_description_label = message("xmlui.administrative.item.EditBitstreamForm.description_label"); + private static final Message T_description_help = message("xmlui.administrative.item.EditBitstreamForm.description_help"); + private static final Message T_para1 = message("xmlui.administrative.item.EditBitstreamForm.para1"); + private static final Message T_format_label = message("xmlui.administrative.item.EditBitstreamForm.format_label"); + private static final Message T_format_default = message("xmlui.administrative.item.EditBitstreamForm.format_default"); + private static final Message T_para2 = message("xmlui.administrative.item.EditBitstreamForm.para2"); + private static final Message T_user_label = message("xmlui.administrative.item.EditBitstreamForm.user_label"); + private static final Message T_user_help = message("xmlui.administrative.item.EditBitstreamForm.user_help"); private static final Message T_filename_label = message("xmlui.administrative.item.EditBitstreamForm.name_label"); private static final Message T_filename_help = message("xmlui.administrative.item.EditBitstreamForm.name_help"); private boolean isAdvancedFormEnabled=true; - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); - protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); + protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); @Override - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); - pageMeta.addTrail().addContent(T_trail); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); + pageMeta.addTrail().addContent(T_trail); pageMeta.addMetadata("javascript", "static").addContent("static/js/editItemUtil.js"); - } + } @Override - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { isAdvancedFormEnabled= DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.submission.restrictstep.enableAdvancedForm", false); - // Get our parameters - UUID bitstreamID = UUID.fromString(parameters.getParameter("bitstreamID", null)); + // Get our parameters + UUID bitstreamID = UUID.fromString(parameters.getParameter("bitstreamID", null)); - // Get the bitstream and all the various formats + // Get the bitstream and all the various formats // Administrator is allowed to see internal formats too. - Bitstream bitstream = bitstreamService.find(context, bitstreamID); - BitstreamFormat currentFormat = bitstream.getFormat(context); + Bitstream bitstream = bitstreamService.find(context, bitstreamID); + BitstreamFormat currentFormat = bitstream.getFormat(context); java.util.List bitstreamFormats = authorizeService.isAdmin(context) ? - bitstreamFormatService.findAll(context) : - bitstreamFormatService.findNonInternal(context); - - boolean primaryBitstream = false; - java.util.List bundles = bitstream.getBundles(); - if (bundles != null && bundles.size() > 0) - { - if (bitstream.equals(bundles.get(0).getPrimaryBitstream())) - { - primaryBitstream = true; - } - } + bitstreamFormatService.findAll(context) : + bitstreamFormatService.findNonInternal(context); - // File name & url - String fileUrl = contextPath + "/bitstream/id/" +bitstream.getID() + "/" + bitstream.getName(); - String fileName = bitstream.getName(); + boolean primaryBitstream = false; + java.util.List bundles = bitstream.getBundles(); + if (bundles != null && bundles.size() > 0) + { + if (bitstream.equals(bundles.get(0).getPrimaryBitstream())) + { + primaryBitstream = true; + } + } + + // File name & url + String fileUrl = contextPath + "/bitstream/id/" +bitstream.getID() + "/" + bitstream.getName(); + String fileName = bitstream.getName(); - // DIVISION: main - Division div = body.addInteractiveDivision("edit-bitstream", contextPath+"/admin/item", Division.METHOD_MULTIPART, "primary administrative item"); - div.setHead(T_head1); + // DIVISION: main + Division div = body.addInteractiveDivision("edit-bitstream", contextPath+"/admin/item", Division.METHOD_MULTIPART, "primary administrative item"); + div.setHead(T_head1); - // LIST: edit form - List edit = div.addList("edit-bitstream-list", List.TYPE_FORM); + // LIST: edit form + List edit = div.addList("edit-bitstream-list", List.TYPE_FORM); edit.addLabel(T_file_label); edit.addItem(null,"break-all").addXref(fileUrl, fileName); @@ -133,84 +135,81 @@ public class EditBitstreamForm extends AbstractDSpaceTransformer bitstreamName.setLabel(T_filename_label); bitstreamName.setHelp(T_filename_help); bitstreamName.setValue(fileName); - - Select primarySelect = edit.addItem().addSelect("primary"); - primarySelect.setLabel(T_primary_label); - primarySelect.addOption(primaryBitstream,"yes",T_primary_option_yes); - primarySelect.addOption(!primaryBitstream,"no",T_primary_option_no); - - Text description = edit.addItem().addText("description"); - description.setLabel(T_description_label); - description.setHelp(T_description_help); - description.setValue(bitstream.getDescription()); + + Select primarySelect = edit.addItem().addSelect("primary"); + primarySelect.setLabel(T_primary_label); + primarySelect.addOption(primaryBitstream,"yes",T_primary_option_yes); + primarySelect.addOption(!primaryBitstream,"no",T_primary_option_no); + + Text description = edit.addItem().addText("description"); + description.setLabel(T_description_label); + description.setHelp(T_description_help); + description.setValue(bitstream.getDescription()); // EMBARGO FIELD // if AdvancedAccessPolicy=false: add Embargo Fields. - if(!isAdvancedFormEnabled){ + if (!isAdvancedFormEnabled) + { AccessStepUtil asu = new AccessStepUtil(context); // if the item is embargoed default value will be displayed. asu.addEmbargoDateDisplayOnly(bitstream, edit); } - edit.addItem(T_para1); + edit.addItem(T_para1); - // System supported formats - Select format = edit.addItem().addSelect("formatID"); - format.setLabel(T_format_label); + // System supported formats + Select format = edit.addItem().addSelect("formatID"); + format.setLabel(T_format_label); // load the options menu, skipping the "Unknown" format since "Not on list" takes its place int unknownFormatID = bitstreamFormatService.findUnknown(context).getID(); - format.addOption(-1,T_format_default); - for (BitstreamFormat bitstreamFormat : bitstreamFormats) - { + format.addOption(-1,T_format_default); + for (BitstreamFormat bitstreamFormat : bitstreamFormats) + { if (bitstreamFormat.getID() == unknownFormatID) { continue; } - String supportLevel = "Unknown"; - if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN) + String supportLevel = "Unknown"; + if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN) { supportLevel = "known"; } - else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED) + else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED) { supportLevel = "Supported"; } - String name = bitstreamFormat.getShortDescription()+" ("+supportLevel+")"; + String name = bitstreamFormat.getShortDescription()+" ("+supportLevel+")"; if (bitstreamFormat.isInternal()) { name += " (Internal)"; } - int id = bitstreamFormat.getID(); + int id = bitstreamFormat.getID(); - format.addOption(id,name); - } - if (currentFormat != null) - { - format.setOptionSelected(currentFormat.getID()); - } - else - { - format.setOptionSelected(-1); - } + format.addOption(id,name); + } + if (currentFormat != null) + { + format.setOptionSelected(currentFormat.getID()); + } + else + { + format.setOptionSelected(-1); + } - edit.addItem(T_para2); + edit.addItem(T_para2); - // User supplied format - Text userFormat = edit.addItem().addText("user_format"); - userFormat.setLabel(T_user_label); - userFormat.setHelp(T_user_help); - userFormat.setValue(bitstream.getUserFormatDescription()); + // User supplied format + Text userFormat = edit.addItem().addText("user_format"); + userFormat.setLabel(T_user_label); + userFormat.setHelp(T_user_help); + userFormat.setValue(bitstream.getUserFormatDescription()); + // ITEM: form actions + org.dspace.app.xmlui.wing.element.Item actions = edit.addItem(); + actions.addButton("submit_save").setValue(T_submit_save); + actions.addButton("submit_cancel").setValue(T_submit_cancel); - - - // ITEM: form actions - org.dspace.app.xmlui.wing.element.Item actions = edit.addItem(); - actions.addButton("submit_save").setValue(T_submit_save); - actions.addButton("submit_cancel").setValue(T_submit_cancel); - - div.addHidden("administrative-continue").setValue(knot.getId()); - - } + div.addHidden("administrative-continue").setValue(knot.getId()); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemBitstreamsForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemBitstreamsForm.java index 7f1c4a5f5a..cba858b063 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemBitstreamsForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemBitstreamsForm.java @@ -25,44 +25,44 @@ import java.sql.SQLException; import java.util.*; /** - * Show a list of the item's bitstreams allowing the user to delete them, + * Show a list of the item's bitstreams allowing the user to delete them, * edit them, or upload new bitstreams. - * + * * @author Jay Paz * @author Scott Phillips */ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { - - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); - private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); - private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); - private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); - private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); - private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); - private static final Message T_title = message("xmlui.administrative.item.EditItemBitstreamsForm.title"); - private static final Message T_trail = message("xmlui.administrative.item.EditItemBitstreamsForm.trail"); - private static final Message T_head1 = message("xmlui.administrative.item.EditItemBitstreamsForm.head1"); - private static final Message T_column1 = message("xmlui.administrative.item.EditItemBitstreamsForm.column1"); - private static final Message T_column2 = message("xmlui.administrative.item.EditItemBitstreamsForm.column2"); - private static final Message T_column3 = message("xmlui.administrative.item.EditItemBitstreamsForm.column3"); - private static final Message T_column4 = message("xmlui.administrative.item.EditItemBitstreamsForm.column4"); - private static final Message T_column5 = message("xmlui.administrative.item.EditItemBitstreamsForm.column5"); - private static final Message T_column6 = message("xmlui.administrative.item.EditItemBitstreamsForm.column6"); - private static final Message T_column7 = message("xmlui.administrative.item.EditItemBitstreamsForm.column7"); - private static final Message T_bundle_label = message("xmlui.administrative.item.EditItemBitstreamsForm.bundle_label"); - private static final Message T_primary_label = message("xmlui.administrative.item.EditItemBitstreamsForm.primary_label"); - private static final Message T_view_link = message("xmlui.administrative.item.EditItemBitstreamsForm.view_link"); - private static final Message T_submit_add = message("xmlui.administrative.item.EditItemBitstreamsForm.submit_add"); - private static final Message T_submit_delete = message("xmlui.administrative.item.EditItemBitstreamsForm.submit_delete"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); + private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); + private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); + private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); + private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); + private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); - private static final Message T_no_upload = message("xmlui.administrative.item.EditItemBitstreamsForm.no_upload"); - private static final Message T_no_remove = message("xmlui.administrative.item.EditItemBitstreamsForm.no_remove"); + private static final Message T_title = message("xmlui.administrative.item.EditItemBitstreamsForm.title"); + private static final Message T_trail = message("xmlui.administrative.item.EditItemBitstreamsForm.trail"); + private static final Message T_head1 = message("xmlui.administrative.item.EditItemBitstreamsForm.head1"); + private static final Message T_column1 = message("xmlui.administrative.item.EditItemBitstreamsForm.column1"); + private static final Message T_column2 = message("xmlui.administrative.item.EditItemBitstreamsForm.column2"); + private static final Message T_column3 = message("xmlui.administrative.item.EditItemBitstreamsForm.column3"); + private static final Message T_column4 = message("xmlui.administrative.item.EditItemBitstreamsForm.column4"); + private static final Message T_column5 = message("xmlui.administrative.item.EditItemBitstreamsForm.column5"); + private static final Message T_column6 = message("xmlui.administrative.item.EditItemBitstreamsForm.column6"); + private static final Message T_column7 = message("xmlui.administrative.item.EditItemBitstreamsForm.column7"); + private static final Message T_bundle_label = message("xmlui.administrative.item.EditItemBitstreamsForm.bundle_label"); + private static final Message T_primary_label = message("xmlui.administrative.item.EditItemBitstreamsForm.primary_label"); + private static final Message T_view_link = message("xmlui.administrative.item.EditItemBitstreamsForm.view_link"); + private static final Message T_submit_add = message("xmlui.administrative.item.EditItemBitstreamsForm.submit_add"); + private static final Message T_submit_delete = message("xmlui.administrative.item.EditItemBitstreamsForm.submit_delete"); + + private static final Message T_no_upload = message("xmlui.administrative.item.EditItemBitstreamsForm.no_upload"); + private static final Message T_no_remove = message("xmlui.administrative.item.EditItemBitstreamsForm.no_remove"); private static final Message T_submit_reorder = message("xmlui.administrative.item.EditItemBitstreamsForm.submit_reorder"); private static final Message T_order_up = message("xmlui.administrative.item.EditItemBitstreamsForm.order_up"); private static final Message T_order_down = message("xmlui.administrative.item.EditItemBitstreamsForm.order_down"); @@ -70,75 +70,78 @@ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } - - - public void addBody(Body body) throws SQLException, WingException - { - // Get our parameters and state - UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); - Item item = itemService.find(context, itemID); - String baseURL = contextPath+"/admin/item?administrative-continue="+knot.getId(); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } - // DIVISION: main div - Division main = body.addInteractiveDivision("edit-item-status", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative item"); - main.setHead(T_option_head); + public void addBody(Body body) + throws SQLException, WingException + { + // Get our parameters and state + UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); + Item item = itemService.find(context, itemID); + String baseURL = contextPath + "/admin/item?administrative-continue=" + knot.getId(); - - - // LIST: options - List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); - options.addItem().addXref(baseURL+"&submit_status",T_option_status); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_bitstreams",T_option_bitstreams); - options.addItem().addXref(baseURL+"&submit_metadata",T_option_metadata); - options.addItem().addXref(baseURL + "&view_item", T_option_view); - options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); - - - // TABLE: Bitstream summary - Table files = main.addTable("editItemBitstreams", 1, 1); + // DIVISION: main div + Division main = body.addInteractiveDivision("edit-item-status", + contextPath + "/admin/item", Division.METHOD_POST, + "primary administrative item"); + main.setHead(T_option_head); - files.setHead(T_head1); - Row header = files.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column1); - header.addCellContent(T_column2); - header.addCellContent(T_column3); - header.addCellContent(T_column4); - header.addCellContent(T_column5); - header.addCellContent(T_column6); - header.addCellContent(T_column7); + // LIST: options + List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); + options.addItem().addXref(baseURL + "&submit_status",T_option_status); + options.addItem().addHighlight("bold").addXref(baseURL + "&submit_bitstreams",T_option_bitstreams); + options.addItem().addXref(baseURL+"&submit_metadata",T_option_metadata); + options.addItem().addXref(baseURL + "&view_item", T_option_view); + options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); - java.util.List bundles = item.getBundles(); + + // TABLE: Bitstream summary + Table files = main.addTable("editItemBitstreams", 1, 1); + + files.setHead(T_head1); + + Row header = files.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column1); + header.addCellContent(T_column2); + header.addCellContent(T_column3); + header.addCellContent(T_column4); + header.addCellContent(T_column5); + header.addCellContent(T_column6); + header.addCellContent(T_column7); + + java.util.List bundles = item.getBundles(); boolean showBitstreamUpdateOrderButton = false; - for (Bundle bundle : bundles) - { + for (Bundle bundle : bundles) + { + Cell bundleCell = files.addRow("bundle_head_" + bundle.getID(), Row.ROLE_DATA, "").addCell(1, 5); + bundleCell.addContent(T_bundle_label.parameterize(bundle.getName())); - Cell bundleCell = files.addRow("bundle_head_" + bundle.getID(), Row.ROLE_DATA, "").addCell(1, 5); - bundleCell.addContent(T_bundle_label.parameterize(bundle.getName())); - - java.util.List bitstreams = bundle.getBitstreams(); + java.util.List bitstreams = bundle.getBitstreams(); ArrayList bitstreamIdOrder = new ArrayList<>(); for (Bitstream bitstream : bitstreams) { bitstreamIdOrder.add(bitstream.getID()); } - for (int bitstreamIndex = 0; bitstreamIndex < bitstreams.size(); bitstreamIndex++) { + for (int bitstreamIndex = 0; bitstreamIndex < bitstreams.size(); bitstreamIndex++) + { Bitstream bitstream = bitstreams.get(bitstreamIndex); boolean primary = (bitstream.equals(bundle.getPrimaryBitstream())); String name = bitstream.getName(); - if (name != null && name.length() > 50) { + if (name != null && name.length() > 50) + { // If the fiel name is too long the shorten it so that it will display nicely. String shortName = name.substring(0, 15); shortName += " ... "; @@ -149,7 +152,8 @@ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { String description = bitstream.getDescription(); String format = null; BitstreamFormat bitstreamFormat = bitstream.getFormat(context); - if (bitstreamFormat != null) { + if (bitstreamFormat != null) + { format = bitstreamFormat.getShortDescription(); } String editURL = contextPath + "/admin/item?administrative-continue=" + knot.getId() + "&bitstreamID=" + bitstream.getID() + "&submit_edit"; @@ -160,11 +164,13 @@ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { CheckBox remove = row.addCell().addCheckBox("remove"); remove.setLabel("remove"); remove.addOption(bundle.getID() + "/" + bitstream.getID()); - if (!authorizeService.authorizeActionBoolean(context, item, Constants.REMOVE)) { + if (!authorizeService.authorizeActionBoolean(context, item, Constants.REMOVE)) + { remove.setDisabled(); } - if (authorizeService.authorizeActionBoolean(context, bitstream, Constants.WRITE)) { + if (authorizeService.authorizeActionBoolean(context, bitstream, Constants.WRITE)) + { // The user can edit the bitstream give them a link. Cell cell = row.addCell(); cell.addXref(editURL, name); @@ -174,7 +180,9 @@ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { row.addCell(null,null,"break-all").addXref(editURL, description); row.addCell().addXref(editURL, format); - } else { + } + else + { // The user can't edit the bitstream just show them it. Cell cell = row.addCell(); cell.addContent(name); @@ -197,13 +205,15 @@ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { cell.addHidden("order_" + bitstream.getID()).setValue(String.valueOf(bitstreamIndex + 1)); showBitstreamUpdateOrderButton = true; Button upButton = cell.addButton("submit_order_" + bundle.getID() + "_" + bitstream.getID() + "_up", ((bitstreamIndex == 0) ? "disabled" : "") + " icon-button arrowUp "); - if((bitstreamIndex == 0)){ + if ((bitstreamIndex == 0)) + { upButton.setDisabled(); } upButton.setValue(T_order_up); upButton.setHelp(T_order_up); Button downButton = cell.addButton("submit_order_" + bundle.getID() + "_" + bitstream.getID() + "_down", (bitstreamIndex == (bitstreams.size() - 1) ? "disabled" : "") + " icon-button arrowDown "); - if(bitstreamIndex == (bitstreams.size() - 1)){ + if (bitstreamIndex == (bitstreams.size() - 1)) + { downButton.setDisabled(); } downButton.setValue(T_order_down); @@ -213,55 +223,57 @@ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { cell.addHidden(bundle.getID() + "_" + bitstream.getID() + "_up_value").setValue(retrieveOrderUpButtonValue((java.util.List) bitstreamIdOrder.clone(), bitstreamIndex)); String characters = retrieveOrderDownButtonValue((java.util.List) bitstreamIdOrder.clone(), bitstreamIndex); cell.addHidden(bundle.getID() + "_" + bitstream.getID() + "_down_value").setValue(characters); - }else{ + } + else + { row.addCell().addContent(String.valueOf(bitstreamIndex)); } } - } + } - if (authorizeService.authorizeActionBoolean(context, item, Constants.ADD)) - { - Cell cell = files.addRow().addCell(1, 5); - cell.addXref(contextPath+"/admin/item?administrative-continue="+knot.getId()+"&submit_add",T_submit_add); - } - else - { - Cell cell = files.addRow().addCell(1, 5); - cell.addHighlight("fade").addContent(T_no_upload); - } + if (authorizeService.authorizeActionBoolean(context, item, Constants.ADD)) + { + Cell cell = files.addRow().addCell(1, 5); + cell.addXref(contextPath + "/admin/item?administrative-continue=" + + knot.getId() + "&submit_add",T_submit_add); + } + else + { + Cell cell = files.addRow().addCell(1, 5); + cell.addHighlight("fade").addContent(T_no_upload); + } - - - // PARA: actions - Para actions = main.addPara("editItemActionsP","editItemActionsP" ); - if (showBitstreamUpdateOrderButton) { + + // PARA: actions + Para actions = main.addPara("editItemActionsP","editItemActionsP" ); + if (showBitstreamUpdateOrderButton) + { //Add a button to submit the new order (this button is hidden & will be displayed by the javascript) //Should javascript be disabled for some reason this button isn't used. actions.addButton("submit_update_order", "hidden").setValue(T_submit_reorder); } // Only System Administrators can delete bitstreams - if (authorizeService.authorizeActionBoolean(context, item, Constants.REMOVE)) + if (authorizeService.authorizeActionBoolean(context, item, Constants.REMOVE)) { actions.addButton("submit_delete").setValue(T_submit_delete); } - else - { - Button button = actions.addButton("submit_delete"); - button.setValue(T_submit_delete); - button.setDisabled(); - - main.addPara().addHighlight("fade").addContent(T_no_remove); - } - actions.addButton("submit_return").setValue(T_submit_return); + else + { + Button button = actions.addButton("submit_delete"); + button.setValue(T_submit_delete); + button.setDisabled(); + main.addPara().addHighlight("fade").addContent(T_no_remove); + } + actions.addButton("submit_return").setValue(T_submit_return); - main.addHidden("administrative-continue").setValue(knot.getId()); - - } + main.addHidden("administrative-continue").setValue(knot.getId()); + } private String retrieveOrderUpButtonValue(java.util.List bitstreamIdOrder, int bitstreamIndex) { - if(0 != bitstreamIndex){ + if (0 != bitstreamIndex) + { //We don't have the first button, so create a value where the current bitstreamId moves one up UUID temp = bitstreamIdOrder.get(bitstreamIndex); bitstreamIdOrder.set(bitstreamIndex, bitstreamIdOrder.get(bitstreamIndex - 1)); @@ -272,7 +284,8 @@ public class EditItemBitstreamsForm extends AbstractDSpaceTransformer { } private String retrieveOrderDownButtonValue(java.util.List bitstreamIdOrder, int bitstreamIndex) { - if(bitstreamIndex < (bitstreamIdOrder.size()) -1){ + if (bitstreamIndex < (bitstreamIdOrder.size()) -1) + { //We don't have the first button, so create a value where the current bitstreamId moves one up UUID temp = bitstreamIdOrder.get(bitstreamIndex); bitstreamIdOrder.set(bitstreamIndex, bitstreamIdOrder.get(bitstreamIndex + 1)); diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemMetadataForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemMetadataForm.java index 28a579d8e4..c2a90f94c4 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemMetadataForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemMetadataForm.java @@ -40,81 +40,84 @@ import java.util.UUID; */ public class EditItemMetadataForm extends AbstractDSpaceTransformer { - - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_update = message("xmlui.general.update"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_template_head = message("xmlui.administrative.item.general.template_head"); - private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); - private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); - private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); - private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); - private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); - private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); - private static final Message T_title = message("xmlui.administrative.item.EditItemMetadataForm.title"); - private static final Message T_trail = message("xmlui.administrative.item.EditItemMetadataForm.trail"); - private static final Message T_head1 = message("xmlui.administrative.item.EditItemMetadataForm.head1"); - private static final Message T_name_label = message("xmlui.administrative.item.EditItemMetadataForm.name_label"); - private static final Message T_value_label = message("xmlui.administrative.item.EditItemMetadataForm.value_label"); - private static final Message T_lang_label = message("xmlui.administrative.item.EditItemMetadataForm.lang_label"); - private static final Message T_submit_add = message("xmlui.administrative.item.EditItemMetadataForm.submit_add"); - private static final Message T_para1 = message("xmlui.administrative.item.EditItemMetadataForm.para1"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_update = message("xmlui.general.update"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_template_head = message("xmlui.administrative.item.general.template_head"); + private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); + private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); + private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); + private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); + private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); + private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); - - private static final Message T_head2 = message("xmlui.administrative.item.EditItemMetadataForm.head2"); - private static final Message T_column1 = message("xmlui.administrative.item.EditItemMetadataForm.column1"); - private static final Message T_column2 = message("xmlui.administrative.item.EditItemMetadataForm.column2"); - private static final Message T_column3 = message("xmlui.administrative.item.EditItemMetadataForm.column3"); - private static final Message T_column4 = message("xmlui.administrative.item.EditItemMetadataForm.column4"); - private static final Message T_unlock = message("xmlui.authority.confidence.unlock.help"); - - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - protected ChoiceAuthorityService choiceAuthorityService = ContentAuthorityServiceFactory.getInstance().getChoiceAuthorityService(); - protected MetadataAuthorityService metadataAuthorityService = ContentAuthorityServiceFactory.getInstance().getMetadataAuthorityService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException, SQLException { - Item item = itemService.find(context, UUID.fromString(parameters.getParameter("itemID", null))); - Collection owner = item.getOwningCollection(); - UUID collectionID = (owner == null) ? null : owner.getID(); - - pageMeta.addMetadata("choice", "collection").addContent(String.valueOf(collectionID)); - pageMeta.addMetadata("title").addContent(T_title); + private static final Message T_title = message("xmlui.administrative.item.EditItemMetadataForm.title"); + private static final Message T_trail = message("xmlui.administrative.item.EditItemMetadataForm.trail"); + private static final Message T_head1 = message("xmlui.administrative.item.EditItemMetadataForm.head1"); + private static final Message T_name_label = message("xmlui.administrative.item.EditItemMetadataForm.name_label"); + private static final Message T_value_label = message("xmlui.administrative.item.EditItemMetadataForm.value_label"); + private static final Message T_lang_label = message("xmlui.administrative.item.EditItemMetadataForm.lang_label"); + private static final Message T_submit_add = message("xmlui.administrative.item.EditItemMetadataForm.submit_add"); + private static final Message T_para1 = message("xmlui.administrative.item.EditItemMetadataForm.para1"); - pageMeta.addMetadata("stylesheet", "screen", "datatables", true).addContent("../../static/Datatables/DataTables-1.8.0/media/css/datatables.css"); - pageMeta.addMetadata("javascript", "static", "datatables", true).addContent("static/Datatables/DataTables-1.8.0/media/js/jquery.dataTables.min.js"); - pageMeta.addMetadata("stylesheet", "screen", "person-lookup", true).addContent("../../static/css/authority/person-lookup.css"); - pageMeta.addMetadata("javascript", null, "person-lookup", true).addContent("../../static/js/person-lookup.js"); + private static final Message T_head2 = message("xmlui.administrative.item.EditItemMetadataForm.head2"); + private static final Message T_column1 = message("xmlui.administrative.item.EditItemMetadataForm.column1"); + private static final Message T_column2 = message("xmlui.administrative.item.EditItemMetadataForm.column2"); + private static final Message T_column3 = message("xmlui.administrative.item.EditItemMetadataForm.column3"); + private static final Message T_column4 = message("xmlui.administrative.item.EditItemMetadataForm.column4"); + private static final Message T_unlock = message("xmlui.authority.confidence.unlock.help"); + + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected ChoiceAuthorityService choiceAuthorityService = ContentAuthorityServiceFactory.getInstance().getChoiceAuthorityService(); + protected MetadataAuthorityService metadataAuthorityService = ContentAuthorityServiceFactory.getInstance().getMetadataAuthorityService(); + + public void addPageMeta(PageMeta pageMeta) + throws WingException, SQLException + { + Item item = itemService.find(context, UUID.fromString(parameters.getParameter("itemID", null))); + Collection owner = item.getOwningCollection(); + UUID collectionID = (owner == null) ? null : owner.getID(); + + pageMeta.addMetadata("choice", "collection").addContent(String.valueOf(collectionID)); + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } + pageMeta.addMetadata("stylesheet", "screen", "datatables", true).addContent("../../static/Datatables/DataTables-1.8.0/media/css/datatables.css"); + pageMeta.addMetadata("javascript", "static", "datatables", true).addContent("static/Datatables/DataTables-1.8.0/media/js/jquery.dataTables.min.js"); + pageMeta.addMetadata("stylesheet", "screen", "person-lookup", true).addContent("../../static/css/authority/person-lookup.css"); + pageMeta.addMetadata("javascript", null, "person-lookup", true).addContent("../../static/js/person-lookup.js"); - /** - * Add either the simple Ajax response document or the full - * document with header and full edit item form based on the - * mode parameter. Mode parameter values are set in the Flowscipt - * and can be either 'ajax' or 'normal'. - */ - @SuppressWarnings("unchecked") // the cast is correct - public void addBody(Body body) throws SQLException, WingException - { - // Get our parameters and state - UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); - Item item = itemService.find(context, itemID); - java.util.List values = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); - Collections.sort(values, new DCValueComparator()); - String baseURL = contextPath+"/admin/item?administrative-continue="+knot.getId(); - Request request = ObjectModelHelper.getRequest(objectModel); - String previousFieldID = request.getParameter("field"); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } + + /** + * Add either the simple Ajax response document or the full + * document with header and full edit item form based on the + * mode parameter. Mode parameter values are set in the Flowscipt + * and can be either 'ajax' or 'normal'. + */ + @SuppressWarnings("unchecked") // the cast is correct + public void addBody(Body body) + throws SQLException, WingException + { + // Get our parameters and state + UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); + Item item = itemService.find(context, itemID); + java.util.List values = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); + Collections.sort(values, new DCValueComparator()); + String baseURL = contextPath + "/admin/item?administrative-continue=" + knot.getId(); + + Request request = ObjectModelHelper.getRequest(objectModel); + String previousFieldID = request.getParameter("field"); // Metadata editing is the only type of editing available for a template item. boolean editingTemplateItem = false; @@ -130,7 +133,7 @@ public class EditItemMetadataForm extends AbstractDSpaceTransformer { } // DIVISION: main - Division main = body.addInteractiveDivision("edit-item-status", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative item"); + Division main = body.addInteractiveDivision("edit-item-status", contextPath + "/admin/item", Division.METHOD_POST,"primary administrative item"); if (templateCollection != null && editingTemplateItem) { main.setHead(T_template_head.parameterize(templateCollection.getName())); @@ -145,170 +148,172 @@ public class EditItemMetadataForm extends AbstractDSpaceTransformer { // LIST: options if (!editingTemplateItem) { - List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); - options.addItem().addXref(baseURL+"&submit_status",T_option_status); - options.addItem().addXref(baseURL+"&submit_bitstreams",T_option_bitstreams); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_metadata",T_option_metadata); - options.addItem().addXref(baseURL + "&view_item", T_option_view); - options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); + List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); + options.addItem().addXref(baseURL + "&submit_status",T_option_status); + options.addItem().addXref(baseURL + "&submit_bitstreams",T_option_bitstreams); + options.addItem().addHighlight("bold").addXref(baseURL + "&submit_metadata",T_option_metadata); + options.addItem().addXref(baseURL + "&view_item", T_option_view); + options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); } // LIST: add new metadata List addForm = main.addList("addItemMetadata",List.TYPE_FORM); addForm.setHead(T_head1); - Select addName = addForm.addItem().addSelect("field"); - addName.setLabel(T_name_label); - java.util.List fields = metadataFieldService.findAll(context); - for (MetadataField field : fields) - { - int fieldID = field.getID(); - MetadataSchema schema = field.getMetadataSchema(); - String name = schema.getName() +"."+field.getElement(); - if (field.getQualifier() != null) - { - name += "." + field.getQualifier(); - } + Select addName = addForm.addItem().addSelect("field"); + addName.setLabel(T_name_label); + java.util.List fields = metadataFieldService.findAll(context); + for (MetadataField field : fields) + { + int fieldID = field.getID(); + MetadataSchema schema = field.getMetadataSchema(); + String name = schema.getName() + "." + field.getElement(); + if (field.getQualifier() != null) + { + name += "." + field.getQualifier(); + } - addName.addOption(fieldID, name); + addName.addOption(fieldID, name); + } + if (previousFieldID != null) + { + addName.setOptionSelected(previousFieldID); + } + + + Composite addComposite = addForm.addItem().addComposite("value"); + addComposite.setLabel(T_value_label); + TextArea addValue = addComposite.addTextArea("value"); + Text addLang = addComposite.addText("language"); + + addValue.setSize(4, 35); + addLang.setLabel(T_lang_label); + addLang.setSize(6); + + addForm.addItem().addButton("submit_add").setValue(T_submit_add); + + + // PARA: Disclaimer + main.addPara(T_para1); + + + Para actions = main.addPara(null,"edit-metadata-actions top" ); + actions.addButton("submit_update").setValue(T_submit_update); + actions.addButton("submit_return").setValue(T_submit_return); + + + // TABLE: Metadata + main.addHidden("scope").setValue("*"); + int index = 1; + Table table = main.addTable("editItemMetadata",1,1); + table.setHead(T_head2); + + Row header = table.addRow(Row.ROLE_HEADER); + header.addCell().addContent(T_column1); + header.addCell().addContent(T_column2); + header.addCell().addContent(T_column3); + header.addCell().addContent(T_column4); + + for (MetadataValue value : values) + { + String name = value.getMetadataField().toString('_'); + + Row row = table.addRow(name,Row.ROLE_DATA,"metadata-value"); + + CheckBox remove = row.addCell().addCheckBox("remove_" + index); + remove.setLabel("remove"); + remove.addOption(index); + + Cell cell = row.addCell(); + cell.addContent(name.replaceAll("_", ". ")); + cell.addHidden("name_"+index).setValue(name); + + // value entry cell: + Cell mdCell = row.addCell(); + String fieldKey = metadataAuthorityService.makeFieldKey( + value.getMetadataField().getMetadataSchema().getName(), + value.getMetadataField().getElement(), + value.getMetadataField().getQualifier()); + + // put up just a selector when preferred choice presentation is select: + if (choiceAuthorityService.isChoicesConfigured(fieldKey) && + Params.PRESENTATION_SELECT.equals(choiceAuthorityService.getPresentation(fieldKey))) + { + Select mdSelect = mdCell.addSelect("value_" + index); + mdSelect.setSize(1); + Choices cs = choiceAuthorityService.getMatches(fieldKey, value.getValue(), owner, 0, 0, null); + if (cs.defaultSelected < 0) + { + mdSelect.addOption(true, value.getValue(), value.getValue()); + } + for (int i = 0; i < cs.values.length; ++i) + { + mdSelect.addOption(i == cs.defaultSelected, cs.values[i].value, cs.values[i].label); + } } - if (previousFieldID != null) + else { - addName.setOptionSelected(previousFieldID); - } - - - Composite addComposite = addForm.addItem().addComposite("value"); - addComposite.setLabel(T_value_label); - TextArea addValue = addComposite.addTextArea("value"); - Text addLang = addComposite.addText("language"); - - addValue.setSize(4, 35); - addLang.setLabel(T_lang_label); - addLang.setSize(6); - - addForm.addItem().addButton("submit_add").setValue(T_submit_add); - - - - - // PARA: Disclaimer - main.addPara(T_para1); - - - Para actions = main.addPara(null,"edit-metadata-actions top" ); - actions.addButton("submit_update").setValue(T_submit_update); - actions.addButton("submit_return").setValue(T_submit_return); - - - - // TABLE: Metadata - main.addHidden("scope").setValue("*"); - int index = 1; - Table table = main.addTable("editItemMetadata",1,1); - table.setHead(T_head2); - - Row header = table.addRow(Row.ROLE_HEADER); - header.addCell().addContent(T_column1); - header.addCell().addContent(T_column2); - header.addCell().addContent(T_column3); - header.addCell().addContent(T_column4); - - for(MetadataValue value : values) - { - String name = value.getMetadataField().toString('_'); - - Row row = table.addRow(name,Row.ROLE_DATA,"metadata-value"); - - CheckBox remove = row.addCell().addCheckBox("remove_"+index); - remove.setLabel("remove"); - remove.addOption(index); - - Cell cell = row.addCell(); - cell.addContent(name.replaceAll("_", ". ")); - cell.addHidden("name_"+index).setValue(name); - - // value entry cell: - Cell mdCell = row.addCell(); - String fieldKey = metadataAuthorityService.makeFieldKey(value.getMetadataField().getMetadataSchema().getName(), value.getMetadataField().getElement(), value.getMetadataField().getQualifier()); - - // put up just a selector when preferred choice presentation is select: - if (choiceAuthorityService.isChoicesConfigured(fieldKey) && - Params.PRESENTATION_SELECT.equals(choiceAuthorityService.getPresentation(fieldKey))) + TextArea mdValue = mdCell.addTextArea("value_" + index); + mdValue.setSize(4,35); + mdValue.setValue(value.getValue()); + boolean isAuth = metadataAuthorityService.isAuthorityControlled(fieldKey); + if (isAuth) + { + mdValue.setAuthorityControlled(); + mdValue.setAuthorityRequired(metadataAuthorityService.isAuthorityRequired(fieldKey)); + Value authValue = mdValue.setAuthorityValue((value.getAuthority() == null)?"":value.getAuthority(), Choices.getConfidenceText(value.getConfidence())); + // add the "unlock" button to auth field + Button unlock = authValue.addButton("authority_unlock_"+index,"ds-authority-lock"); + unlock.setHelp(T_unlock); + } + if (choiceAuthorityService.isChoicesConfigured(fieldKey)) + { + mdValue.setChoices(fieldKey); + if (Params.PRESENTATION_AUTHORLOOKUP.equals(choiceAuthorityService.getPresentation(fieldKey))) { - Select mdSelect = mdCell.addSelect("value_"+index); - mdSelect.setSize(1); - Choices cs = choiceAuthorityService.getMatches(fieldKey, value.getValue(), owner, 0, 0, null); - if (cs.defaultSelected < 0) - { - mdSelect.addOption(true, value.getValue(), value.getValue()); - } - for (int i = 0; i < cs.values.length; ++i) - { - mdSelect.addOption(i == cs.defaultSelected, cs.values[i].value, cs.values[i].label); - } + mdValue.setChoicesPresentation(Params.PRESENTATION_AUTHORLOOKUP); } else { - TextArea mdValue = mdCell.addTextArea("value_"+index); - mdValue.setSize(4,35); - mdValue.setValue(value.getValue()); - boolean isAuth = metadataAuthorityService.isAuthorityControlled(fieldKey); - if (isAuth) - { - mdValue.setAuthorityControlled(); - mdValue.setAuthorityRequired(metadataAuthorityService.isAuthorityRequired(fieldKey)); - Value authValue = mdValue.setAuthorityValue((value.getAuthority() == null)?"":value.getAuthority(), Choices.getConfidenceText(value.getConfidence())); - // add the "unlock" button to auth field - Button unlock = authValue.addButton("authority_unlock_"+index,"ds-authority-lock"); - unlock.setHelp(T_unlock); - } - if (choiceAuthorityService.isChoicesConfigured(fieldKey)) - { - mdValue.setChoices(fieldKey); - if(Params.PRESENTATION_AUTHORLOOKUP.equals(choiceAuthorityService.getPresentation(fieldKey))){ - mdValue.setChoicesPresentation(Params.PRESENTATION_AUTHORLOOKUP); - }else{ - mdValue.setChoicesPresentation(Params.PRESENTATION_LOOKUP); - } - mdValue.setChoicesClosed(choiceAuthorityService.isClosed(fieldKey)); - } + mdValue.setChoicesPresentation(Params.PRESENTATION_LOOKUP); } - Text mdLang = row.addCell().addText("language_"+index); - mdLang.setSize(6); - mdLang.setValue(value.getLanguage()); - - // Tick the index counter; - index++; + mdValue.setChoicesClosed(choiceAuthorityService.isClosed(fieldKey)); + } } + Text mdLang = row.addCell().addText("language_"+index); + mdLang.setSize(6); + mdLang.setValue(value.getLanguage()); - - - - // PARA: actions - actions = main.addPara(null,"edit-metadata-actions bottom" ); - actions.addButton("submit_update").setValue(T_submit_update); - actions.addButton("submit_return").setValue(T_submit_return); - - - main.addHidden("administrative-continue").setValue(knot.getId()); + // Tick the index counter; + index++; } + // PARA: actions + actions = main.addPara(null,"edit-metadata-actions bottom" ); + actions.addButton("submit_update").setValue(T_submit_update); + actions.addButton("submit_return").setValue(T_submit_return); - /** - * Compare two metadata element's name so that they may be sorted. - */ - static class DCValueComparator implements Comparator, Serializable { - public int compare(Object arg0, Object arg1) { - final MetadataValue o1 = (MetadataValue)arg0; - final MetadataValue o2 = (MetadataValue)arg1; - MetadataField o1Field = o1.getMetadataField(); - MetadataField o2Field = o2.getMetadataField(); - final String s1 = o1Field.getMetadataSchema().getName() + o1Field.getElement() + (o1Field.getQualifier()==null?"":("." + o1Field.getQualifier())); - final String s2 = o2Field.getMetadataSchema().getName() + o2Field.getElement() + (o2Field.getQualifier()==null?"":("." + o2Field.getQualifier())); - return s1.compareTo(s2); - } + main.addHidden("administrative-continue").setValue(knot.getId()); + } + + + /** + * Compare two metadata element's name so that they may be sorted. + */ + static class DCValueComparator implements Comparator, Serializable { + public int compare(Object arg0, Object arg1) { + final MetadataValue o1 = (MetadataValue)arg0; + final MetadataValue o2 = (MetadataValue)arg1; + MetadataField o1Field = o1.getMetadataField(); + MetadataField o2Field = o2.getMetadataField(); + final String s1 = o1Field.getMetadataSchema().getName() + + o1Field.getElement() + (o1Field.getQualifier() == null + ? "" : ("." + o1Field.getQualifier())); + final String s2 = o2Field.getMetadataSchema().getName() + + o2Field.getElement() + (o2Field.getQualifier() == null + ? "" : ("." + o2Field.getQualifier())); + return s1.compareTo(s2); } - + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemStatusForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemStatusForm.java index 1eef17f0e1..dde5795bbe 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemStatusForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/EditItemStatusForm.java @@ -30,49 +30,49 @@ import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.core.Constants; /** - * Display basic meta-meta information about the item and allow the user to change + * Display basic meta-meta information about the item and allow the user to change * its state such as withdraw or reinstate, possibly even completely deleting the item! - * + * * @author Jay Paz * @author Scott Phillips */ public class EditItemStatusForm extends AbstractDSpaceTransformer { - - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); - private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); - private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); - private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); - private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); - private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); - - private static final Message T_title = message("xmlui.administrative.item.EditItemStatusForm.title"); - private static final Message T_trail = message("xmlui.administrative.item.EditItemStatusForm.trail"); - private static final Message T_para1 = message("xmlui.administrative.item.EditItemStatusForm.para1"); - private static final Message T_label_id = message("xmlui.administrative.item.EditItemStatusForm.label_id"); - private static final Message T_label_handle = message("xmlui.administrative.item.EditItemStatusForm.label_handle"); - private static final Message T_label_modified = message("xmlui.administrative.item.EditItemStatusForm.label_modified"); - private static final Message T_label_in = message("xmlui.administrative.item.EditItemStatusForm.label_in"); - private static final Message T_label_page = message("xmlui.administrative.item.EditItemStatusForm.label_page"); - private static final Message T_label_auth = message("xmlui.administrative.item.EditItemStatusForm.label_auth"); - private static final Message T_label_withdraw = message("xmlui.administrative.item.EditItemStatusForm.label_withdraw"); - private static final Message T_label_reinstate = message("xmlui.administrative.item.EditItemStatusForm.label_reinstate"); - private static final Message T_label_move = message("xmlui.administrative.item.EditItemStatusForm.label_move"); - private static final Message T_label_delete = message("xmlui.administrative.item.EditItemStatusForm.label_delete"); - private static final Message T_submit_authorizations = message("xmlui.administrative.item.EditItemStatusForm.submit_authorizations"); - private static final Message T_submit_withdraw = message("xmlui.administrative.item.EditItemStatusForm.submit_withdraw"); - private static final Message T_submit_reinstate = message("xmlui.administrative.item.EditItemStatusForm.submit_reinstate"); - private static final Message T_submit_move = message("xmlui.administrative.item.EditItemStatusForm.submit_move"); - private static final Message T_submit_delete = message("xmlui.administrative.item.EditItemStatusForm.submit_delete"); - private static final Message T_na = message("xmlui.administrative.item.EditItemStatusForm.na"); - - private static final Message T_not_allowed = message("xmlui.administrative.item.EditItemStatusForm.not_allowed"); - private static final Message T_collectionadmins_only = message("xmlui.administrative.item.EditItemStatusForm.collection_admins_only"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); + private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); + private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); + private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); + private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); + private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); + + + private static final Message T_title = message("xmlui.administrative.item.EditItemStatusForm.title"); + private static final Message T_trail = message("xmlui.administrative.item.EditItemStatusForm.trail"); + private static final Message T_para1 = message("xmlui.administrative.item.EditItemStatusForm.para1"); + private static final Message T_label_id = message("xmlui.administrative.item.EditItemStatusForm.label_id"); + private static final Message T_label_handle = message("xmlui.administrative.item.EditItemStatusForm.label_handle"); + private static final Message T_label_modified = message("xmlui.administrative.item.EditItemStatusForm.label_modified"); + private static final Message T_label_in = message("xmlui.administrative.item.EditItemStatusForm.label_in"); + private static final Message T_label_page = message("xmlui.administrative.item.EditItemStatusForm.label_page"); + private static final Message T_label_auth = message("xmlui.administrative.item.EditItemStatusForm.label_auth"); + private static final Message T_label_withdraw = message("xmlui.administrative.item.EditItemStatusForm.label_withdraw"); + private static final Message T_label_reinstate = message("xmlui.administrative.item.EditItemStatusForm.label_reinstate"); + private static final Message T_label_move = message("xmlui.administrative.item.EditItemStatusForm.label_move"); + private static final Message T_label_delete = message("xmlui.administrative.item.EditItemStatusForm.label_delete"); + private static final Message T_submit_authorizations = message("xmlui.administrative.item.EditItemStatusForm.submit_authorizations"); + private static final Message T_submit_withdraw = message("xmlui.administrative.item.EditItemStatusForm.submit_withdraw"); + private static final Message T_submit_reinstate = message("xmlui.administrative.item.EditItemStatusForm.submit_reinstate"); + private static final Message T_submit_move = message("xmlui.administrative.item.EditItemStatusForm.submit_move"); + private static final Message T_submit_delete = message("xmlui.administrative.item.EditItemStatusForm.submit_delete"); + private static final Message T_na = message("xmlui.administrative.item.EditItemStatusForm.na"); + + private static final Message T_not_allowed = message("xmlui.administrative.item.EditItemStatusForm.not_allowed"); + private static final Message T_collectionadmins_only = message("xmlui.administrative.item.EditItemStatusForm.collection_admins_only"); private static final Message T_label_private = message("xmlui.administrative.item.EditItemStatusForm.label_private"); @@ -80,160 +80,158 @@ public class EditItemStatusForm extends AbstractDSpaceTransformer { private static final Message T_submit_private = message("xmlui.administrative.item.EditItemStatusForm.submit_private"); private static final Message T_submit_public = message("xmlui.administrative.item.EditItemStatusForm.submit_public"); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } - - public void addBody(Body body) throws SQLException, WingException - { - // Get our parameters and state - UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); - Item item = itemService.find(context, itemID); - String baseURL = contextPath+"/admin/item?administrative-continue="+knot.getId(); - - - // DIVISION: main - Division main = body.addInteractiveDivision("edit-item-status", contextPath+"/admin/item", Division.METHOD_POST,"primary administrative edit-item-status"); - main.setHead(T_option_head); - - - - - // LIST: options - List options = main.addList("options",List.TYPE_SIMPLE,"horizontal"); - options.addItem().addHighlight("bold").addXref(baseURL+"&submit_status",T_option_status); - options.addItem().addXref(baseURL+"&submit_bitstreams",T_option_bitstreams); - options.addItem().addXref(baseURL+"&submit_metadata",T_option_metadata); - options.addItem().addXref(baseURL + "&view_item", T_option_view); - options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); - - - - - // PARA: Helpful instructions - main.addPara(T_para1); - - - + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - - // LIST: Item meta-meta information - List itemInfo = main.addList("item-info"); - - itemInfo.addLabel(T_label_id); - itemInfo.addItem(String.valueOf(item.getID())); - - itemInfo.addLabel(T_label_handle); - itemInfo.addItem(item.getHandle()==null?"None":item.getHandle()); - - itemInfo.addLabel(T_label_modified); - itemInfo.addItem(item.getLastModified().toString()); - - itemInfo.addLabel(T_label_in); - - List subList = itemInfo.addList("collections", List.TYPE_SIMPLE); - java.util.List collections = item.getCollections(); - for(Collection collection : collections) { - subList.addItem(collection.getName()); - } - - itemInfo.addLabel(T_label_page); - if(item.getHandle()==null){ - itemInfo.addItem(T_na); - } - else - { - itemInfo.addItem().addXref(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.url") + "/handle/" + item.getHandle(),DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.url") + "/handle/" + item.getHandle()); - } - - itemInfo.addLabel(T_label_auth); - try - { - AuthorizeUtil.authorizeManageItemPolicy(context, item); - itemInfo.addItem().addButton("submit_authorization").setValue(T_submit_authorizations); - } - catch (AuthorizeException authex) - { - addNotAllowedButton(itemInfo.addItem(), "submit_authorization", T_submit_authorizations); - } - - if(!item.isWithdrawn()) - { - itemInfo.addLabel(T_label_withdraw); - try - { - AuthorizeUtil.authorizeWithdrawItem(context, item); - itemInfo.addItem().addButton("submit_withdraw").setValue(T_submit_withdraw); - } - catch (AuthorizeException authex) - { - addNotAllowedButton(itemInfo.addItem(), "submit_withdraw", T_submit_withdraw); - } - } - else - { - itemInfo.addLabel(T_label_reinstate); - try - { - AuthorizeUtil.authorizeReinstateItem(context, item); - itemInfo.addItem().addButton("submit_reinstate").setValue(T_submit_reinstate); - } - catch (AuthorizeException authex) - { - addNotAllowedButton(itemInfo.addItem(), "submit_reinstate", T_submit_reinstate); - } - } - - itemInfo.addLabel(T_label_move); - addCollectionAdminOnlyButton(itemInfo.addItem(), item.getOwningCollection(), "submit_move", T_submit_move); + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); + + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } + + public void addBody(Body body) + throws SQLException, WingException + { + // Get our parameters and state + UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); + Item item = itemService.find(context, itemID); + String baseURL = contextPath + "/admin/item?administrative-continue=" + + knot.getId(); + + + // DIVISION: main + Division main = body.addInteractiveDivision("edit-item-status", + contextPath + "/admin/item", Division.METHOD_POST, + "primary administrative edit-item-status"); + main.setHead(T_option_head); + + // LIST: options + List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); + options.addItem().addHighlight("bold").addXref(baseURL+"&submit_status", T_option_status); + options.addItem().addXref(baseURL+"&submit_bitstreams", T_option_bitstreams); + options.addItem().addXref(baseURL+"&submit_metadata", T_option_metadata); + options.addItem().addXref(baseURL + "&view_item", T_option_view); + options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); + + // PARA: Helpful instructions + main.addPara(T_para1); + + // LIST: Item meta-meta information + List itemInfo = main.addList("item-info"); + + itemInfo.addLabel(T_label_id); + itemInfo.addItem(String.valueOf(item.getID())); + + itemInfo.addLabel(T_label_handle); + itemInfo.addItem(item.getHandle() == null ? "None" : item.getHandle()); + + itemInfo.addLabel(T_label_modified); + itemInfo.addItem(item.getLastModified().toString()); + + itemInfo.addLabel(T_label_in); + + List subList = itemInfo.addList("collections", List.TYPE_SIMPLE); + java.util.List collections = item.getCollections(); + for (Collection collection : collections) + { + subList.addItem(collection.getName()); + } + + itemInfo.addLabel(T_label_page); + if (item.getHandle()==null) + { + itemInfo.addItem(T_na); + } + else + { + itemInfo.addItem().addXref(DSpaceServicesFactory.getInstance() + .getConfigurationService().getProperty("dspace.url") + "/handle/" + + item.getHandle(),DSpaceServicesFactory.getInstance(). + getConfigurationService().getProperty("dspace.url") + + "/handle/" + item.getHandle()); + } + + itemInfo.addLabel(T_label_auth); + try + { + AuthorizeUtil.authorizeManageItemPolicy(context, item); + itemInfo.addItem().addButton("submit_authorization").setValue(T_submit_authorizations); + } + catch (AuthorizeException authex) + { + addNotAllowedButton(itemInfo.addItem(), "submit_authorization", T_submit_authorizations); + } + + if (!item.isWithdrawn()) + { + itemInfo.addLabel(T_label_withdraw); + try + { + AuthorizeUtil.authorizeWithdrawItem(context, item); + itemInfo.addItem().addButton("submit_withdraw").setValue(T_submit_withdraw); + } + catch (AuthorizeException authex) + { + addNotAllowedButton(itemInfo.addItem(), "submit_withdraw", T_submit_withdraw); + } + } + else + { + itemInfo.addLabel(T_label_reinstate); + try + { + AuthorizeUtil.authorizeReinstateItem(context, item); + itemInfo.addItem().addButton("submit_reinstate").setValue(T_submit_reinstate); + } + catch (AuthorizeException authex) + { + addNotAllowedButton(itemInfo.addItem(), "submit_reinstate", T_submit_reinstate); + } + } + + itemInfo.addLabel(T_label_move); + addCollectionAdminOnlyButton(itemInfo.addItem(), item.getOwningCollection(), "submit_move", T_submit_move); privateOrPublicAccess(item, itemInfo); + itemInfo.addLabel(T_label_delete); + if (authorizeService.authorizeActionBoolean(context, item, Constants.DELETE)) + { + itemInfo.addItem().addButton("submit_delete").setValue(T_submit_delete); + } + else + { + addNotAllowedButton(itemInfo.addItem(), "submit_delete", T_submit_delete); + } - itemInfo.addLabel(T_label_delete); - if (authorizeService.authorizeActionBoolean(context, item, Constants.DELETE)) - { - itemInfo.addItem().addButton("submit_delete").setValue(T_submit_delete); - } - else - { - addNotAllowedButton(itemInfo.addItem(), "submit_delete", T_submit_delete); - } - - - - - // PARA: main actions - main.addPara().addButton("submit_return").setValue(T_submit_return); - - main.addHidden("administrative-continue").setValue(knot.getId()); - } + // PARA: main actions + main.addPara().addButton("submit_return").setValue(T_submit_return); - private void privateOrPublicAccess(Item item, List itemInfo) throws WingException, SQLException { - if(item.isDiscoverable()) + main.addHidden("administrative-continue").setValue(knot.getId()); + } + + private void privateOrPublicAccess(Item item, List itemInfo) + throws WingException, SQLException { + if (item.isDiscoverable()) { itemInfo.addLabel(T_label_private); - if (authorizeService.authorizeActionBoolean(context, item, + if (authorizeService.authorizeActionBoolean(context, item, Constants.WRITE)) - { - itemInfo.addItem().addButton("submit_private") - .setValue(T_submit_private); - } - else - { - addNotAllowedButton(itemInfo.addItem(), "submit_private", - T_submit_private); - } + { + itemInfo.addItem().addButton("submit_private") + .setValue(T_submit_private); + } + else + { + addNotAllowedButton(itemInfo.addItem(), "submit_private", + T_submit_private); + } } else { @@ -250,33 +248,35 @@ public class EditItemStatusForm extends AbstractDSpaceTransformer { } /** - * Add a disabled button with a "not allowed" notice - * @param item - * @param buttonName - * @param buttonLabel - * @throws WingException - * @throws SQLException - */ - private void addNotAllowedButton(org.dspace.app.xmlui.wing.element.Item item, String buttonName, Message buttonLabel) throws WingException, SQLException - { - Button button = item.addButton(buttonName); - button.setValue(buttonLabel); - button.setDisabled(); - item.addHighlight("fade").addContent(T_not_allowed); - } - - private void addCollectionAdminOnlyButton(org.dspace.app.xmlui.wing.element.Item item, Collection collection, String buttonName, Message buttonLabel) throws WingException, SQLException - { - Button button = item.addButton(buttonName); - button.setValue(buttonLabel); + * Add a disabled button with a "not allowed" notice + * @param item + * @param buttonName + * @param buttonLabel + * @throws WingException + * @throws SQLException + * An exception that provides information on a database access error or other errors. + */ + private void addNotAllowedButton(org.dspace.app.xmlui.wing.element.Item item, String buttonName, Message buttonLabel) + throws WingException, SQLException + { + Button button = item.addButton(buttonName); + button.setValue(buttonLabel); + button.setDisabled(); + item.addHighlight("fade").addContent(T_not_allowed); + } + + private void addCollectionAdminOnlyButton(org.dspace.app.xmlui.wing.element.Item item, Collection collection, String buttonName, Message buttonLabel) + throws WingException, SQLException + { + Button button = item.addButton(buttonName); + button.setValue(buttonLabel); - if (!authorizeService.isAdmin(context, collection)) - { - // Only admins can create or delete - button.setDisabled(); - item.addHighlight("fade").addContent(T_collectionadmins_only); - } - } - + if (!authorizeService.isAdmin(context, collection)) + { + // Only admins can create or delete + button.setDisabled(); + item.addHighlight("fade").addContent(T_collectionadmins_only); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/FindItemForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/FindItemForm.java index 2e8d121b24..fd2772c7b6 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/FindItemForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/FindItemForm.java @@ -21,65 +21,69 @@ import org.xml.sax.SAXException; /** * Query the user for an item's identifier. - * + * * @author Jay Paz */ public class FindItemForm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - - private static final Message T_title = message("xmlui.administrative.item.FindItemForm.title"); - private static final Message T_head1 = message("xmlui.administrative.item.FindItemForm.head1"); - private static final Message T_identifier_label = message("xmlui.administrative.item.FindItemForm.identifier_label"); - private static final Message T_identifier_error = message("xmlui.administrative.item.FindItemForm.identifier_error"); - private static final Message T_find = message("xmlui.administrative.item.FindItemForm.find"); - - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_item_trail); - pageMeta.addMetadata("title").addContent(T_title); - } + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - - public void addBody(Body body) throws SAXException, WingException - { - // Get our parameters and state; - String identifier = parameters.getParameter("identifier",null); - - String errorString = parameters.getParameter("errors",null); - ArrayList errors = new ArrayList(); - if (errorString != null) + private static final Message T_title = message("xmlui.administrative.item.FindItemForm.title"); + private static final Message T_head1 = message("xmlui.administrative.item.FindItemForm.head1"); + private static final Message T_identifier_label = message("xmlui.administrative.item.FindItemForm.identifier_label"); + private static final Message T_identifier_error = message("xmlui.administrative.item.FindItemForm.identifier_error"); + private static final Message T_find = message("xmlui.administrative.item.FindItemForm.find"); + + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_item_trail); + pageMeta.addMetadata("title").addContent(T_title); + } + + + public void addBody(Body body) + throws SAXException, WingException + { + // Get our parameters and state; + String identifier = parameters.getParameter("identifier",null); + + String errorString = parameters.getParameter("errors",null); + ArrayList errors = new ArrayList(); + if (errorString != null) { - for (String error : errorString.split(",")) + for (String error : errorString.split(",")) { - errors.add(error); + errors.add(error); } } - - // DIVISION: find-item - Division findItem = body.addInteractiveDivision("find-item",contextPath + "/admin/item", Division.METHOD_GET,"primary administrative item"); - findItem.setHead(T_head1); - - List form = findItem.addList("find-item-form", List.TYPE_FORM); - - Text id = form.addItem().addText("identifier"); + + // DIVISION: find-item + Division findItem = body.addInteractiveDivision("find-item", + contextPath + "/admin/item", Division.METHOD_GET, + "primary administrative item"); + findItem.setHead(T_head1); + + List form = findItem.addList("find-item-form", List.TYPE_FORM); + + Text id = form.addItem().addText("identifier"); id.setAutofocus("autofocus"); - id.setLabel(T_identifier_label); - if (identifier != null) + id.setLabel(T_identifier_label); + if (identifier != null) { id.setValue(identifier); } - if (errors.contains("identifier")) + if (errors.contains("identifier")) { id.addError(T_identifier_error); } - - form.addItem().addButton("submit_find").setValue(T_find); - - findItem.addHidden("administrative-continue").setValue(knot.getId()); - } + + form.addItem().addButton("submit_find").setValue(T_find); + + findItem.addHidden("administrative-continue").setValue(knot.getId()); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/MoveItemForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/MoveItemForm.java index 03dc591598..122762531f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/MoveItemForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/MoveItemForm.java @@ -35,18 +35,18 @@ import org.dspace.app.util.CollectionDropDown; */ public class MoveItemForm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); - - private static final Message T_title = message("xmlui.administrative.item.MoveItemForm.title"); - private static final Message T_trail = message("xmlui.administrative.item.MoveItemForm.trail"); - private static final Message T_head1 = message("xmlui.administrative.item.MoveItemForm.head1"); - private static final Message T_collection = message("xmlui.administrative.item.MoveItemForm.collection"); - private static final Message T_collection_help = message("xmlui.administrative.item.MoveItemForm.collection_help"); - private static final Message T_collection_default = message("xmlui.administrative.item.MoveItemForm.collection_default"); - private static final Message T_submit_move = message("xmlui.administrative.item.MoveItemForm.submit_move"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); + + private static final Message T_title = message("xmlui.administrative.item.MoveItemForm.title"); + private static final Message T_trail = message("xmlui.administrative.item.MoveItemForm.trail"); + private static final Message T_head1 = message("xmlui.administrative.item.MoveItemForm.head1"); + private static final Message T_collection = message("xmlui.administrative.item.MoveItemForm.collection"); + private static final Message T_collection_help = message("xmlui.administrative.item.MoveItemForm.collection_help"); + private static final Message T_collection_default = message("xmlui.administrative.item.MoveItemForm.collection_default"); + private static final Message T_submit_move = message("xmlui.administrative.item.MoveItemForm.submit_move"); private static final Message T_submit_inherit = message("xmlui.administrative.item.MoveItemForm.inherit_policies"); private static final Message T_submit_inherit_help = message("xmlui.administrative.item.MoveItemForm.inherit_policies_help"); @@ -54,24 +54,27 @@ public class MoveItemForm extends AbstractDSpaceTransformer { protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); + + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } - public void addBody(Body body) throws WingException, SQLException - { + public void addBody(Body body) + throws WingException, SQLException + { // Get our parameters and state UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); Item item = itemService.find(context, itemID); // DIVISION: Main - Division main = body.addInteractiveDivision("move-item", contextPath+"/admin/item", Division.METHOD_POST, "primary administrative item"); + Division main = body.addInteractiveDivision("move-item", + contextPath + "/admin/item", Division.METHOD_POST, + "primary administrative item"); main.setHead(T_head1.parameterize(item.getHandle())); java.util.List collections = collectionService.findAuthorizedOptimized(context, Constants.ADD); @@ -82,7 +85,8 @@ public class MoveItemForm extends AbstractDSpaceTransformer { select.setHelp(T_collection_help); Collection owningCollection = item.getOwningCollection(); - if (owningCollection == null) { + if (owningCollection == null) + { select.addOption("",T_collection_default); } @@ -97,7 +101,9 @@ public class MoveItemForm extends AbstractDSpaceTransformer { // Only add the item if it isn't already the owner if (!itemService.isOwningCollection(item, collection)) { - select.addOption(collection.equals(owningCollection), collection.getID().toString(), CollectionDropDown.collectionPath(context, collection)); + select.addOption(collection.equals(owningCollection), + collection.getID().toString(), + CollectionDropDown.collectionPath(context, collection)); } } @@ -107,8 +113,8 @@ public class MoveItemForm extends AbstractDSpaceTransformer { inheritPolicies.setHelp(T_submit_inherit_help); inheritPolicies.addOption("inheritPolicies"); actions.addButton("submit_move").setValue(T_submit_move); - actions.addButton("submit_cancel").setValue(T_submit_cancel); + actions.addButton("submit_cancel").setValue(T_submit_cancel); - main.addHidden("administrative-continue").setValue(knot.getId()); - } + main.addHidden("administrative-continue").setValue(knot.getId()); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ViewItem.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ViewItem.java index 73c569a159..af58705d0c 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ViewItem.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/item/ViewItem.java @@ -30,88 +30,90 @@ import org.dspace.content.service.ItemService; * Display basic meta-meta information about the item and allow the user to * change its state such as withdraw or reinstate, possibly even completely * deleting the item! - * + * * @author Jay Paz * @author Scott Phillips */ public class ViewItem extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); + private static final Message T_option_head = message("xmlui.administrative.item.general.option_head"); - private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); + private static final Message T_option_status = message("xmlui.administrative.item.general.option_status"); - private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); + private static final Message T_option_bitstreams = message("xmlui.administrative.item.general.option_bitstreams"); - private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); + private static final Message T_option_metadata = message("xmlui.administrative.item.general.option_metadata"); - private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); - - private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); + private static final Message T_option_view = message("xmlui.administrative.item.general.option_view"); - private static final Message T_title = message("xmlui.administrative.item.ViewItem.title"); + private static final Message T_option_curate = message("xmlui.administrative.item.general.option_curate"); - private static final Message T_trail = message("xmlui.administrative.item.ViewItem.trail"); + private static final Message T_title = message("xmlui.administrative.item.ViewItem.title"); - private static final Message T_head_parent_collections = message("xmlui.ArtifactBrowser.ItemViewer.head_parent_collections"); - private static final Message T_show_simple = - message("xmlui.ArtifactBrowser.ItemViewer.show_simple"); - - private static final Message T_show_full = - message("xmlui.ArtifactBrowser.ItemViewer.show_full"); + private static final Message T_trail = message("xmlui.administrative.item.ViewItem.trail"); - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + private static final Message T_head_parent_collections = message("xmlui.ArtifactBrowser.ItemViewer.head_parent_collections"); - public void addPageMeta(PageMeta pageMeta) throws WingException { - pageMeta.addMetadata("title").addContent(T_title); + private static final Message T_show_simple = message("xmlui.ArtifactBrowser.ItemViewer.show_simple"); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } + private static final Message T_show_full = message("xmlui.ArtifactBrowser.ItemViewer.show_full"); - public void addBody(Body body) throws SQLException, WingException { - // Get our parameters and state - Request request = ObjectModelHelper.getRequest(objectModel); - String show = request.getParameter("show"); - boolean showFullItem = false; - if (show != null && show.length() > 0) - { - showFullItem = true; - } - - UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); - Item item = itemService.find(context, itemID); - String baseURL = contextPath + "/admin/item?administrative-continue=" - + knot.getId() ; - - String link = baseURL + "&view_item" + (showFullItem?"":"&show=full"); - String tabLink = baseURL + "&view_item" + (!showFullItem?"":"&show=full"); - // DIVISION: main - Division main = body.addInteractiveDivision("edit-item-status", - contextPath + "/admin/item", Division.METHOD_POST, - "primary administrative edit-item-status"); - main.setHead(T_option_head); - - // LIST: options - List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); - options.addItem().addXref( - baseURL + "&submit_status", T_option_status); - options.addItem().addXref(baseURL + "&submit_bitstreams", - T_option_bitstreams); - options.addItem().addXref(baseURL + "&submit_metadata", - T_option_metadata); - options.addItem().addHighlight("bold").addXref(tabLink, T_option_view); - options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); - - // item - - Para showfullPara = main.addPara(null, "item-view-toggle item-view-toggle-top"); + + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + + public void addPageMeta(PageMeta pageMeta) throws WingException { + pageMeta.addMetadata("title").addContent(T_title); + + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item", T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } + + public void addBody(Body body) + throws SQLException, WingException + { + // Get our parameters and state + Request request = ObjectModelHelper.getRequest(objectModel); + String show = request.getParameter("show"); + boolean showFullItem = false; + if (show != null && show.length() > 0) + { + showFullItem = true; + } + + UUID itemID = UUID.fromString(parameters.getParameter("itemID", null)); + Item item = itemService.find(context, itemID); + String baseURL = contextPath + "/admin/item?administrative-continue=" + + knot.getId() ; + + String link = baseURL + "&view_item" + (showFullItem?"":"&show=full"); + String tabLink = baseURL + "&view_item" + (!showFullItem?"":"&show=full"); + // DIVISION: main + Division main = body.addInteractiveDivision("edit-item-status", + contextPath + "/admin/item", Division.METHOD_POST, + "primary administrative edit-item-status"); + main.setHead(T_option_head); + + // LIST: options + List options = main.addList("options", List.TYPE_SIMPLE, "horizontal"); + options.addItem().addXref( + baseURL + "&submit_status", T_option_status); + options.addItem().addXref(baseURL + "&submit_bitstreams", + T_option_bitstreams); + options.addItem().addXref(baseURL + "&submit_metadata", + T_option_metadata); + options.addItem().addHighlight("bold").addXref(tabLink, T_option_view); + options.addItem().addXref(baseURL + "&submit_curate", T_option_curate); + + // item + + Para showfullPara = main.addPara(null, "item-view-toggle item-view-toggle-top"); if (showFullItem) { @@ -124,22 +126,22 @@ public class ViewItem extends AbstractDSpaceTransformer { showfullPara.addXref(link).addContent(T_show_full); } - ReferenceSet referenceSet; - referenceSet = main.addReferenceSet("collection-viewer", - showFullItem?ReferenceSet.TYPE_DETAIL_VIEW:ReferenceSet.TYPE_SUMMARY_VIEW); - // Reference the actual Item - ReferenceSet appearsInclude = referenceSet.addReference(item) - .addReferenceSet(ReferenceSet.TYPE_DETAIL_LIST, null, "hierarchy"); - appearsInclude.setHead(T_head_parent_collections); + ReferenceSet referenceSet; + referenceSet = main.addReferenceSet("collection-viewer", + showFullItem?ReferenceSet.TYPE_DETAIL_VIEW:ReferenceSet.TYPE_SUMMARY_VIEW); + // Reference the actual Item + ReferenceSet appearsInclude = referenceSet.addReference(item) + .addReferenceSet(ReferenceSet.TYPE_DETAIL_LIST, null, "hierarchy"); + appearsInclude.setHead(T_head_parent_collections); - // Reference all collections the item appears in. - for (Collection collection : item.getCollections()) { - appearsInclude.addReference(collection); - } - - showfullPara = main.addPara(null, "item-view-toggle item-view-toggle-bottom"); + // Reference all collections the item appears in. + for (Collection collection : item.getCollections()) { + appearsInclude.addReference(collection); + } - if (showFullItem) + showfullPara = main.addPara(null, "item-view-toggle item-view-toggle-bottom"); + + if (showFullItem) { showfullPara.addXref(link).addContent(T_show_simple); } @@ -147,5 +149,5 @@ public class ViewItem extends AbstractDSpaceTransformer { { showfullPara.addXref(link).addContent(T_show_full); } - } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/BrowseItemForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/BrowseItemForm.java index 4f760ed84b..e0e6a5842e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/BrowseItemForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/BrowseItemForm.java @@ -38,157 +38,160 @@ import org.xml.sax.SAXException; /** * List all items in this collection that are mapped from other collections. - * + * * @author Scott Phillips */ public class BrowseItemForm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); - - private static final Message T_title = message("xmlui.administrative.mapper.BrowseItemForm.title"); - private static final Message T_trail = message("xmlui.administrative.mapper.BrowseItemForm.trail"); - private static final Message T_head1 = message("xmlui.administrative.mapper.BrowseItemForm.head1"); - private static final Message T_submit_unmap = message("xmlui.administrative.mapper.BrowseItemForm.submit_unmap"); - private static final Message T_column1 = message("xmlui.administrative.mapper.BrowseItemForm.column1"); - private static final Message T_column2 = message("xmlui.administrative.mapper.BrowseItemForm.column2"); - private static final Message T_column3 = message("xmlui.administrative.mapper.BrowseItemForm.column3"); - private static final Message T_column4 = message("xmlui.administrative.mapper.BrowseItemForm.column4"); - - private static final Message T_no_remove = message("xmlui.administrative.mapper.BrowseItemForm.no_remove"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + private static final Message T_title = message("xmlui.administrative.mapper.BrowseItemForm.title"); + private static final Message T_trail = message("xmlui.administrative.mapper.BrowseItemForm.trail"); + private static final Message T_head1 = message("xmlui.administrative.mapper.BrowseItemForm.head1"); + private static final Message T_submit_unmap = message("xmlui.administrative.mapper.BrowseItemForm.submit_unmap"); + private static final Message T_column1 = message("xmlui.administrative.mapper.BrowseItemForm.column1"); + private static final Message T_column2 = message("xmlui.administrative.mapper.BrowseItemForm.column2"); + private static final Message T_column3 = message("xmlui.administrative.mapper.BrowseItemForm.column3"); + private static final Message T_column4 = message("xmlui.administrative.mapper.BrowseItemForm.column4"); + + private static final Message T_no_remove = message("xmlui.administrative.mapper.BrowseItemForm.no_remove"); + + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_mapper_trail); - pageMeta.addTrail().addContent(T_trail); - } + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - - public void addBody(Body body) throws SAXException, WingException, SQLException - { - // Get our parameters and state; - UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); - Collection collection = collectionService.find(context,collectionID); - - List items = getMappedItems(collection); - - // DIVISION: browse-items - Division div = body.addInteractiveDivision("browse-items",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper"); - div.setHead(T_head1); - - if (authorizeService.authorizeActionBoolean(context, collection, Constants.REMOVE)) - { - Para actions = div.addPara(); - actions.addButton("submit_unmap").setValue(T_submit_unmap); - actions.addButton("submit_return").setValue(T_submit_return); - } - else - { - Para actions = div.addPara(); - Button button = actions.addButton("submit_unmap"); - button.setValue(T_submit_unmap); - button.setDisabled(); - actions.addButton("submit_return").setValue(T_submit_return); - - div.addPara().addHighlight("fade").addContent(T_no_remove); - } - - Table table = div.addTable("browse-items-table",1,1); - - Row header = table.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column1); - header.addCellContent(T_column2); - header.addCellContent(T_column3); - header.addCellContent(T_column4); - - for (Item item : items) - { - String itemID = String.valueOf(item.getID()); - Collection owningCollection = item.getOwningCollection(); - String owning = owningCollection.getName(); - String author = "unknown"; - List dcAuthors = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "contributor", Item.ANY, Item.ANY); - if (dcAuthors != null && dcAuthors.size() >= 1) + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); + + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_mapper_trail); + pageMeta.addTrail().addContent(T_trail); + } + + + public void addBody(Body body) + throws SAXException, WingException, SQLException + { + // Get our parameters and state; + UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); + Collection collection = collectionService.find(context,collectionID); + + List items = getMappedItems(collection); + + // DIVISION: browse-items + Division div = body.addInteractiveDivision("browse-items", + contextPath + "/admin/mapper", Division.METHOD_GET, + "primary administrative mapper"); + div.setHead(T_head1); + + if (authorizeService.authorizeActionBoolean(context, collection, Constants.REMOVE)) + { + Para actions = div.addPara(); + actions.addButton("submit_unmap").setValue(T_submit_unmap); + actions.addButton("submit_return").setValue(T_submit_return); + } + else + { + Para actions = div.addPara(); + Button button = actions.addButton("submit_unmap"); + button.setValue(T_submit_unmap); + button.setDisabled(); + actions.addButton("submit_return").setValue(T_submit_return); + + div.addPara().addHighlight("fade").addContent(T_no_remove); + } + + Table table = div.addTable("browse-items-table",1,1); + + Row header = table.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column1); + header.addCellContent(T_column2); + header.addCellContent(T_column3); + header.addCellContent(T_column4); + + for (Item item : items) + { + String itemID = String.valueOf(item.getID()); + Collection owningCollection = item.getOwningCollection(); + String owning = owningCollection.getName(); + String author = "unknown"; + List dcAuthors = itemService.getMetadata( + item, MetadataSchema.DC_SCHEMA, "contributor", Item.ANY, Item.ANY); + if (dcAuthors != null && dcAuthors.size() >= 1) { author = dcAuthors.get(0).getValue(); } - - String title = "untitled"; - List dcTitles = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "title", null, Item.ANY); - if (dcTitles != null && dcTitles.size() >= 1) + + String title = "untitled"; + List dcTitles = itemService.getMetadata( + item, MetadataSchema.DC_SCHEMA, "title", null, Item.ANY); + if (dcTitles != null && dcTitles.size() >= 1) { title = dcTitles.get(0).getValue(); } - String url = contextPath+"/handle/"+item.getHandle(); - - Row row = table.addRow(); - - CheckBox select = row.addCell().addCheckBox("itemID"); - select.setLabel("Select"); - select.addOption(itemID); - - row.addCellContent(owning); - row.addCell().addXref(url,author); - row.addCell().addXref(url,title); - } - - if (authorizeService.authorizeActionBoolean(context, collection, Constants.REMOVE)) - { - Para actions = div.addPara(); - actions.addButton("submit_unmap").setValue(T_submit_unmap); - actions.addButton("submit_return").setValue(T_submit_return); - } - else - { - Para actions = div.addPara(); - Button button = actions.addButton("submit_unmap"); - button.setValue(T_submit_unmap); - button.setDisabled(); - actions.addButton("submit_return").setValue(T_submit_return); - - div.addPara().addHighlight("fade").addContent(T_no_remove); - } - - - - div.addHidden("administrative-continue").setValue(knot.getId()); - } - - - /** - * Get a list of all items that are mapped from other collections. - * - * @param collection The collection to look in. - */ - private List getMappedItems(Collection collection) throws SQLException - { + String url = contextPath+"/handle/"+item.getHandle(); - ArrayList items = new ArrayList(); - - // get all items from that collection + Row row = table.addRow(); + + CheckBox select = row.addCell().addCheckBox("itemID"); + select.setLabel("Select"); + select.addOption(itemID); + + row.addCellContent(owning); + row.addCell().addXref(url,author); + row.addCell().addXref(url,title); + } + + if (authorizeService.authorizeActionBoolean(context, collection, Constants.REMOVE)) + { + Para actions = div.addPara(); + actions.addButton("submit_unmap").setValue(T_submit_unmap); + actions.addButton("submit_return").setValue(T_submit_return); + } + else + { + Para actions = div.addPara(); + Button button = actions.addButton("submit_unmap"); + button.setValue(T_submit_unmap); + button.setDisabled(); + actions.addButton("submit_return").setValue(T_submit_return); + + div.addPara().addHighlight("fade").addContent(T_no_remove); + } + + div.addHidden("administrative-continue").setValue(knot.getId()); + } + + + /** + * Get a list of all items that are mapped from other collections. + * + * @param collection The collection to look in. + */ + private List getMappedItems(Collection collection) + throws SQLException + { + ArrayList items = new ArrayList(); + + // get all items from that collection Iterator iterator = itemService.findByCollection(context, collection); - while (iterator.hasNext()) - { - Item item = iterator.next(); + while (iterator.hasNext()) + { + Item item = iterator.next(); - if (! itemService.isOwningCollection(item, collection)) - { - items.add(item); - } - } + if (! itemService.isOwningCollection(item, collection)) + { + items.add(item); + } + } return items; - } - + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/MapperMain.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/MapperMain.java index e81816d910..fba5d6ff2e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/MapperMain.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/MapperMain.java @@ -32,129 +32,132 @@ import org.dspace.core.Constants; import org.xml.sax.SAXException; /** - * Manage the mapping of items into this collection, allow the user to - * search for new items to import or browse a list of currently mapped + * Manage the mapping of items into this collection, allow the user to + * search for new items to import or browse a list of currently mapped * items. - * + * * @author Scott Phillips */ public class MapperMain extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); - - private static final Message T_title = message("xmlui.administrative.mapper.MapperMain.title"); - private static final Message T_head1 = message("xmlui.administrative.mapper.MapperMain.head1"); - private static final Message T_para1 = message("xmlui.administrative.mapper.MapperMain.para1"); - private static final Message T_para2 = message("xmlui.administrative.mapper.MapperMain.para2"); - private static final Message T_stat_label = message("xmlui.administrative.mapper.MapperMain.stat_label"); - private static final Message T_stat_info = message("xmlui.administrative.mapper.MapperMain.stat_info"); - private static final Message T_search_label = message("xmlui.administrative.mapper.MapperMain.search_label"); - private static final Message T_submit_search = message("xmlui.administrative.mapper.MapperMain.submit_search"); - private static final Message T_submit_browse = message("xmlui.administrative.mapper.MapperMain.submit_browse"); - - private static final Message T_no_add = message("xmlui.administrative.mapper.MapperMain.no_add"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); + + private static final Message T_title = message("xmlui.administrative.mapper.MapperMain.title"); + private static final Message T_head1 = message("xmlui.administrative.mapper.MapperMain.head1"); + private static final Message T_para1 = message("xmlui.administrative.mapper.MapperMain.para1"); + private static final Message T_para2 = message("xmlui.administrative.mapper.MapperMain.para2"); + private static final Message T_stat_label = message("xmlui.administrative.mapper.MapperMain.stat_label"); + private static final Message T_stat_info = message("xmlui.administrative.mapper.MapperMain.stat_info"); + private static final Message T_search_label = message("xmlui.administrative.mapper.MapperMain.search_label"); + private static final Message T_submit_search = message("xmlui.administrative.mapper.MapperMain.submit_search"); + private static final Message T_submit_browse = message("xmlui.administrative.mapper.MapperMain.submit_browse"); + + private static final Message T_no_add = message("xmlui.administrative.mapper.MapperMain.no_add"); - protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_mapper_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - - public void addBody(Body body) throws SAXException, WingException, SQLException { - // Get our parameters and state; - UUID collectionID = UUID.fromString(parameters.getParameter("collectionID",null)); - Collection collection = collectionService.find(context,collectionID); - - int[] counts = getNumberOfMappedAndUnmappedItems(collection); - int count_native = counts[0]; - int count_import = counts[1]; - - - - - // DIVISION: manage-mapper - Division div = body.addInteractiveDivision("manage-mapper",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper"); - div.setHead(T_head1); - - div.addPara(T_para1.parameterize(collection.getName())); - - div.addPara(T_para2); - - - // LIST: Author search form - List form = div.addList("mapper-form"); - - form.addLabel(T_stat_label); - form.addItem(T_stat_info.parameterize(count_import,count_native+count_import)); - - form.addLabel(T_search_label); - org.dspace.app.xmlui.wing.element.Item queryItem = form.addItem(); - Text query = queryItem.addText("query"); - Button button = queryItem.addButton("submit_author"); - button.setValue(T_submit_search); - if (!authorizeService.authorizeActionBoolean(context, collection, Constants.ADD)) - { - query.setDisabled(); - button.setDisabled(); - queryItem.addHighlight("fade").addContent(T_no_add); - } - - // PARA: actions - Para actions = div.addPara(); - actions.addButton("submit_browse").setValue(T_submit_browse); - actions.addButton("submit_return").setValue(T_submit_return); - - - div.addHidden("administrative-continue").setValue(knot.getId()); - } - - /** - * Count the number of unmapped and mapped items in this collection - * - * @param collection The collection to count from. - * @return a two integer array of native items and imported items. - */ - private int[] getNumberOfMappedAndUnmappedItems(Collection collection) throws SQLException - { - int count_native = 0; - int count_import = 0; - - // get all items from that collection + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_mapper_trail); + } + + + public void addBody(Body body) + throws SAXException, WingException, SQLException + { + // Get our parameters and state; + UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); + Collection collection = collectionService.find(context,collectionID); + + int[] counts = getNumberOfMappedAndUnmappedItems(collection); + int count_native = counts[0]; + int count_import = counts[1]; + + + // DIVISION: manage-mapper + Division div = body.addInteractiveDivision("manage-mapper", + contextPath + "/admin/mapper", Division.METHOD_GET, + "primary administrative mapper"); + div.setHead(T_head1); + + div.addPara(T_para1.parameterize(collection.getName())); + + div.addPara(T_para2); + + + // LIST: Author search form + List form = div.addList("mapper-form"); + + form.addLabel(T_stat_label); + form.addItem(T_stat_info.parameterize(count_import,count_native+count_import)); + + form.addLabel(T_search_label); + org.dspace.app.xmlui.wing.element.Item queryItem = form.addItem(); + Text query = queryItem.addText("query"); + Button button = queryItem.addButton("submit_author"); + button.setValue(T_submit_search); + if (!authorizeService.authorizeActionBoolean(context, collection, Constants.ADD)) + { + query.setDisabled(); + button.setDisabled(); + queryItem.addHighlight("fade").addContent(T_no_add); + } + + // PARA: actions + Para actions = div.addPara(); + actions.addButton("submit_browse").setValue(T_submit_browse); + actions.addButton("submit_return").setValue(T_submit_return); + + + div.addHidden("administrative-continue").setValue(knot.getId()); + } + + /** + * Count the number of unmapped and mapped items in this collection + * + * @param collection The collection to count from. + * @return a two integer array of native items and imported items. + */ + private int[] getNumberOfMappedAndUnmappedItems(Collection collection) + throws SQLException + { + int count_native = 0; + int count_import = 0; + + // get all items from that collection Iterator iterator = itemService.findByCollection(context, collection); - // iterate through the items in this collection, and count how many - // are native, and how many are imports, and which collections they - // came from - while (iterator.hasNext()) - { - Item item = iterator.next(); + // iterate through the items in this collection, and count how many + // are native, and how many are imports, and which collections they + // came from + while (iterator.hasNext()) + { + Item item = iterator.next(); - if (itemService.isOwningCollection(item, collection)) - { - count_native++; - } - else - { - count_import++; - } - } + if (itemService.isOwningCollection(item, collection)) + { + count_native++; + } + else + { + count_import++; + } + } int[] counts = new int[2]; counts[0] = count_native; counts[1] = count_import; return counts; - } - + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java index f15cc284a3..d76ef973ac 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java @@ -35,101 +35,107 @@ import org.xml.sax.SAXException; /** * Search for items from other collections to map into this collection. - * + * * @author Scott Phillips */ public class SearchItemForm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); - private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); - - private static final Message T_title = message("xmlui.administrative.mapper.SearchItemForm.title"); - private static final Message T_trail = message("xmlui.administrative.mapper.SearchItemForm.trail"); - private static final Message T_head1 = message("xmlui.administrative.mapper.SearchItemForm.head1"); - private static final Message T_submit_map = message("xmlui.administrative.mapper.SearchItemForm.submit_map"); - private static final Message T_column1 = message("xmlui.administrative.mapper.SearchItemForm.column1"); - private static final Message T_column2 = message("xmlui.administrative.mapper.SearchItemForm.column2"); - private static final Message T_column3 = message("xmlui.administrative.mapper.SearchItemForm.column3"); - private static final Message T_column4 = message("xmlui.administrative.mapper.SearchItemForm.column4"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); + private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail"); + + private static final Message T_title = message("xmlui.administrative.mapper.SearchItemForm.title"); + private static final Message T_trail = message("xmlui.administrative.mapper.SearchItemForm.trail"); + private static final Message T_head1 = message("xmlui.administrative.mapper.SearchItemForm.head1"); + private static final Message T_submit_map = message("xmlui.administrative.mapper.SearchItemForm.submit_map"); + private static final Message T_column1 = message("xmlui.administrative.mapper.SearchItemForm.column1"); + private static final Message T_column2 = message("xmlui.administrative.mapper.SearchItemForm.column2"); + private static final Message T_column3 = message("xmlui.administrative.mapper.SearchItemForm.column3"); + private static final Message T_column4 = message("xmlui.administrative.mapper.SearchItemForm.column4"); private static final Logger log = LoggerFactory.getLogger(SearchItemForm.class); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); @Override - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_mapper_trail); - pageMeta.addTrail().addContent(T_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); + + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_mapper_trail); + pageMeta.addTrail().addContent(T_trail); + } + - @Override - public void addBody(Body body) throws SAXException, WingException, SQLException, IOException - { - // Get our parameters and state; - UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); - Collection collection = collectionService.find(context,collectionID); - - String query = decodeFromURL(parameters.getParameter("query",null)); - java.util.List items = performSearch(collection,query); - - - - // DIVISION: manage-mapper - Division div = body.addInteractiveDivision("search-items",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper"); - div.setHead(T_head1.parameterize(query)); - - Para actions = div.addPara(); - actions.addButton("submit_map").setValue(T_submit_map); - actions.addButton("submit_cancel").setValue(T_submit_cancel); - - Table table = div.addTable("search-items-table",1,1); - - Row header = table.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column1); - header.addCellContent(T_column2); - header.addCellContent(T_column3); - header.addCellContent(T_column4); - - for (Item item : items) - { - String itemID = String.valueOf(item.getID()); - Collection owningCollection = item.getOwningCollection(); - String owning = "unknown"; - if (owningCollection != null) - owning = owningCollection.getName(); - String author = "unknown"; - List dcCreators = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "creator", Item.ANY, Item.ANY); - if (dcCreators != null && dcCreators.size() >= 1) + public void addBody(Body body) + throws SAXException, WingException, SQLException, IOException + { + // Get our parameters and state; + UUID collectionID = UUID.fromString(parameters.getParameter("collectionID", null)); + Collection collection = collectionService.find(context,collectionID); + + String query = decodeFromURL(parameters.getParameter("query",null)); + java.util.List items = performSearch(collection,query); + + + // DIVISION: manage-mapper + Division div = body.addInteractiveDivision("search-items", + contextPath + "/admin/mapper", Division.METHOD_GET, + "primary administrative mapper"); + div.setHead(T_head1.parameterize(query)); + + Para actions = div.addPara(); + actions.addButton("submit_map").setValue(T_submit_map); + actions.addButton("submit_cancel").setValue(T_submit_cancel); + + Table table = div.addTable("search-items-table",1,1); + + Row header = table.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column1); + header.addCellContent(T_column2); + header.addCellContent(T_column3); + header.addCellContent(T_column4); + + for (Item item : items) + { + String itemID = String.valueOf(item.getID()); + Collection owningCollection = item.getOwningCollection(); + String owning = "unknown"; + if (owningCollection != null) + owning = owningCollection.getName(); + String author = "unknown"; + List dcCreators = itemService.getMetadata( + item, MetadataSchema.DC_SCHEMA, "creator", Item.ANY, Item.ANY); + if (dcCreators != null && dcCreators.size() >= 1) { author = dcCreators.get(0).getValue(); } else { - // Do a fallback look for contributors - List dcContributors = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "contributor", Item.ANY, Item.ANY); - if (dcContributors != null && dcContributors.size() >= 1) - { - author = dcContributors.get(0).getValue(); - } - } - - String title = "untitled"; - List dcTitles = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "title", null, Item.ANY); - if (dcTitles != null && dcTitles.size() >= 1) + // Do a fallback look for contributors + List dcContributors = itemService.getMetadata( + item, MetadataSchema.DC_SCHEMA, "contributor", Item.ANY, Item.ANY); + if (dcContributors != null && dcContributors.size() >= 1) + { + author = dcContributors.get(0).getValue(); + } + } + + String title = "untitled"; + List dcTitles = itemService.getMetadata( + item, MetadataSchema.DC_SCHEMA, "title", null, Item.ANY); + if (dcTitles != null && dcTitles.size() >= 1) { title = dcTitles.get(0).getValue(); } - String url = contextPath+"/handle/"+item.getHandle(); - - Row row = table.addRow(); + String url = contextPath+"/handle/"+item.getHandle(); + + Row row = table.addRow(); boolean canBeMapped = true; List collections = item.getCollections(); @@ -152,42 +158,42 @@ public class SearchItemForm extends AbstractDSpaceTransformer { row.addCell().addContent(""); } - row.addCellContent(owning); - row.addCell().addXref(url,author); - row.addCell().addXref(url,title); - } - - actions = div.addPara(); - actions.addButton("submit_map").setValue(T_submit_map); - actions.addButton("submit_cancel").setValue(T_submit_cancel); - - - - - div.addHidden("administrative-continue").setValue(knot.getId()); - } - - - /** - * Search the repository for items in other collections that can be mapped into this one. - * - * @param collection The collection to map into - * @param query The search query. - */ - private java.util.List performSearch(Collection collection, String query) throws SQLException, IOException - { + row.addCellContent(owning); + row.addCell().addXref(url,author); + row.addCell().addXref(url,title); + } + + actions = div.addPara(); + actions.addButton("submit_map").setValue(T_submit_map); + actions.addButton("submit_cancel").setValue(T_submit_cancel); + + div.addHidden("administrative-continue").setValue(knot.getId()); + } + + + /** + * Search the repository for items in other collections that can be mapped into this one. + * + * @param collection The collection to map into + * @param query The search query. + */ + private java.util.List performSearch(Collection collection, String query) + throws SQLException, IOException + { // Which search provider do we use? SearchRequestProcessor processor = null; try { processor = (SearchRequestProcessor) CoreServiceFactory.getInstance().getPluginService() .getSinglePlugin(SearchRequestProcessor.class); - } catch (PluginConfigurationError e) { + } + catch (PluginConfigurationError e) + { log.warn("{} not properly configured. Please configure the {} plugin. {}", - new Object[] { - SearchItemForm.class.getName(), - SearchRequestProcessor.class.getName(), - e.getMessage() - }); + new Object[] { + SearchItemForm.class.getName(), + SearchRequestProcessor.class.getName(), + e.getMessage() + }); } if (processor == null) { // Discovery is the default search provider since DSpace 4.0 @@ -203,9 +209,9 @@ public class SearchItemForm extends AbstractDSpaceTransformer { { if (resultDSO instanceof Item) { - Item item = (Item) resultDSO; + Item item = (Item) resultDSO; - if (!itemService.isOwningCollection(item, collection)) + if (!itemService.isOwningCollection(item, collection)) { items.add(item); } @@ -214,5 +220,4 @@ public class SearchItemForm extends AbstractDSpaceTransformer { return items; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportConfirm.java index 9fe49f798b..b126f51f83 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportConfirm.java @@ -37,21 +37,21 @@ import org.dspace.app.bulkedit.BulkEditChange; * ported from org.dspace.app.webui.servlet.MetadataImportServlet * * Display summary of committed changes - * + * * @author Kim Shepherd */ public class MetadataImportConfirm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); private static final Message T_changes = message("xmlui.administrative.metadataimport.general.changes"); private static final Message T_new_item = message("xmlui.administrative.metadataimport.general.new_item"); private static final Message T_no_changes = message("xmlui.administrative.metadataimport.general.no_changes"); - private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); - private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); + private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); + private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); private static final Message T_success = message("xmlui.administrative.metadataimport.MetadataImportConfirm.success"); private static final Message T_changes_committed = message("xmlui.administrative.metadataimport.MetadataImportConfirm.changes_committed"); @@ -65,23 +65,25 @@ public class MetadataImportConfirm extends AbstractDSpaceTransformer { private static final Message T_item_withdrawn = message("xmlui.administrative.metadataimport.MetadataImportConfirm.item_withdrawn"); private static final Message T_item_reinstated = message("xmlui.administrative.metadataimport.MetadataImportConfirm.item_reinstated"); - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - - public void addBody(Body body) throws SAXException, WingException, SQLException - { - // Get list of changes + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_trail); + } - Request request = ObjectModelHelper.getRequest(objectModel); + + public void addBody(Body body) + throws SAXException, WingException, SQLException + { + // Get list of changes + + Request request = ObjectModelHelper.getRequest(objectModel); ArrayList changes = null; - if(request.getAttribute("changes") != null) + if (request.getAttribute("changes") != null) { changes = ((ArrayList)request.getAttribute("changes")); } @@ -91,175 +93,173 @@ public class MetadataImportConfirm extends AbstractDSpaceTransformer { changes = new ArrayList(); } - // DIVISION: metadata-import - Division div = body.addInteractiveDivision("metadata-import",contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART,"primary administrative"); - div.setHead(T_head1); - Para para = div.addPara(); - para.addContent(T_success); - para.addContent(" " + changes.size() + " "); - para.addContent(T_changes); + // DIVISION: metadata-import + Division div = body.addInteractiveDivision("metadata-import", + contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART, + "primary administrative"); + div.setHead(T_head1); + Para para = div.addPara(); + para.addContent(T_success); + para.addContent(" " + changes.size() + " "); + para.addContent(T_changes); - if(changes.size() > 0) { - Table mdchanges = div.addTable("metadata-changes", changes.size(), 2); + if (changes.size() > 0) { + Table mdchanges = div.addTable("metadata-changes", changes.size(), 2); - // Display the changes - for (BulkEditChange change : changes) + // Display the changes + for (BulkEditChange change : changes) + { + // Get the changes + List adds = change.getAdds(); + List removes = change.getRemoves(); + List newCollections = change.getNewMappedCollections(); + List oldCollections = change.getOldMappedCollections(); + + if ((adds.size() > 0) || (removes.size() > 0) || + (newCollections.size() > 0) || (oldCollections.size() > 0) || + (change.getNewOwningCollection() != null) || (change.getOldOwningCollection() != null) || + (change.isDeleted()) || (change.isWithdrawn()) || (change.isReinstated())) + { + Row headerrow = mdchanges.addRow(Row.ROLE_HEADER); + // Show the item + if (!change.isNewItem()) { - // Get the changes - List adds = change.getAdds(); - List removes = change.getRemoves(); - List newCollections = change.getNewMappedCollections(); - List oldCollections = change.getOldMappedCollections(); + Item i = change.getItem(); + Cell cell = headerrow.addCell(); + cell.addContent(T_changes_committed); + cell.addContent(" " + i.getID() + " (" + i.getHandle() + ")"); + } + else + { + headerrow.addCellContent(T_new_item); + } + headerrow.addCell(); + } - if ((adds.size() > 0) || (removes.size() > 0) || - (newCollections.size() > 0) || (oldCollections.size() > 0) || - (change.getNewOwningCollection() != null) || (change.getOldOwningCollection() != null) || - (change.isDeleted()) || (change.isWithdrawn()) || (change.isReinstated())) - { - Row headerrow = mdchanges.addRow(Row.ROLE_HEADER); - // Show the item - if (!change.isNewItem()) - { - Item i = change.getItem(); - Cell cell = headerrow.addCell(); - cell.addContent(T_changes_committed); - cell.addContent(" " + i.getID() + " (" + i.getHandle() + ")"); - } - else - { - headerrow.addCellContent(T_new_item); - } - headerrow.addCell(); - } + // Show actions + if (change.isDeleted()) + { + Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-delete"); - // Show actions - if (change.isDeleted()) - { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-delete"); + Cell cell = mdrow.addCell(); + cell.addContent(T_item_deleted); + mdrow.addCellContent(""); + } + if (change.isWithdrawn()) + { + Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-withdraw"); - Cell cell = mdrow.addCell(); - cell.addContent(T_item_deleted); - mdrow.addCellContent(""); - } - if (change.isWithdrawn()) - { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-withdraw"); + Cell cell = mdrow.addCell(); + cell.addContent(T_item_withdrawn); + mdrow.addCellContent(""); + } + if (change.isReinstated()) + { + Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-reinstate"); - Cell cell = mdrow.addCell(); - cell.addContent(T_item_withdrawn); - mdrow.addCellContent(""); - } - if (change.isReinstated()) - { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-reinstate"); + Cell cell = mdrow.addCell(); + cell.addContent(T_item_reinstated); + mdrow.addCellContent(""); + } - Cell cell = mdrow.addCell(); - cell.addContent(T_item_reinstated); - mdrow.addCellContent(""); - } - - // Show new owning collection - if (change.getNewOwningCollection() != null) - { - Collection c = change.getNewOwningCollection(); - if (c != null) - { - String cHandle = c.getHandle(); - String cName = c.getName(); - Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); - colrow.addCellContent(T_collection_newowner); - colrow.addCellContent(cHandle + " (" + cName + ")"); - } - } - - // Show old owning collection - if (change.getOldOwningCollection() != null) - { - Collection c = change.getOldOwningCollection(); - if (c != null) - { - String cHandle = c.getHandle(); - String cName = c.getName(); - Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); - colrow.addCellContent(T_collection_oldowner); - colrow.addCellContent(cHandle + " (" + cName + ")"); - } - } - - // Show new mapped collections - for (Collection c : newCollections) - { - String cHandle = c.getHandle(); - String cName = c.getName(); - Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); - colrow.addCellContent(T_collection_mapped); - colrow.addCellContent(cHandle + " (" + cName + ")"); - } - - // Show old mapped collections - for (Collection c : oldCollections) - { - String cHandle = c.getHandle(); - String cName = c.getName(); - Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); - colrow.addCellContent(T_collection_unmapped); - colrow.addCellContent(cHandle + " (" + cName + ")"); - } - - // Show additions - for (BulkEditMetadataValue dcv : adds) - { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); - String md = dcv.getSchema() + "." + dcv.getElement(); - if (dcv.getQualifier() != null) - { - md += "." + dcv.getQualifier(); - } - if (dcv.getLanguage() != null) - { - md += "[" + dcv.getLanguage() + "]"; - } - - Cell cell = mdrow.addCell(); - cell.addContent(T_item_addition); - cell.addContent(" (" + md + ")"); - mdrow.addCellContent(dcv.getValue()); - } - - // Show removals - for (BulkEditMetadataValue dcv : removes) - { - Row mdrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); - String md = dcv.getSchema() + "." + dcv.getElement(); - if (dcv.getQualifier() != null) - { - md += "." + dcv.getQualifier(); - } - if (dcv.getLanguage() != null) - { - md += "[" + dcv.getLanguage() + "]"; - } - - Cell cell = mdrow.addCell(); - cell.addContent(T_item_deletion); - cell.addContent(" (" + md + ")"); - mdrow.addCellContent(dcv.getValue()); - } + // Show new owning collection + if (change.getNewOwningCollection() != null) + { + Collection c = change.getNewOwningCollection(); + if (c != null) + { + String cHandle = c.getHandle(); + String cName = c.getName(); + Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); + colrow.addCellContent(T_collection_newowner); + colrow.addCellContent(cHandle + " (" + cName + ")"); } } - else + + // Show old owning collection + if (change.getOldOwningCollection() != null) { - Para nochanges = div.addPara(); - nochanges.addContent(T_no_changes); + Collection c = change.getOldOwningCollection(); + if (c != null) + { + String cHandle = c.getHandle(); + String cName = c.getName(); + Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); + colrow.addCellContent(T_collection_oldowner); + colrow.addCellContent(cHandle + " (" + cName + ")"); + } } - Para actions = div.addPara(); - Button cancel = actions.addButton("submit_return"); - cancel.setValue(T_submit_return); - - div.addHidden("administrative-continue").setValue(knot.getId()); - } - - + // Show new mapped collections + for (Collection c : newCollections) + { + String cHandle = c.getHandle(); + String cName = c.getName(); + Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); + colrow.addCellContent(T_collection_mapped); + colrow.addCellContent(cHandle + " (" + cName + ")"); + } + // Show old mapped collections + for (Collection c : oldCollections) + { + String cHandle = c.getHandle(); + String cName = c.getName(); + Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); + colrow.addCellContent(T_collection_unmapped); + colrow.addCellContent(cHandle + " (" + cName + ")"); + } + + // Show additions + for (BulkEditMetadataValue dcv : adds) + { + Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); + String md = dcv.getSchema() + "." + dcv.getElement(); + if (dcv.getQualifier() != null) + { + md += "." + dcv.getQualifier(); + } + if (dcv.getLanguage() != null) + { + md += "[" + dcv.getLanguage() + "]"; + } + + Cell cell = mdrow.addCell(); + cell.addContent(T_item_addition); + cell.addContent(" (" + md + ")"); + mdrow.addCellContent(dcv.getValue()); + } + + // Show removals + for (BulkEditMetadataValue dcv : removes) + { + Row mdrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); + String md = dcv.getSchema() + "." + dcv.getElement(); + if (dcv.getQualifier() != null) + { + md += "." + dcv.getQualifier(); + } + if (dcv.getLanguage() != null) + { + md += "[" + dcv.getLanguage() + "]"; + } + + Cell cell = mdrow.addCell(); + cell.addContent(T_item_deletion); + cell.addContent(" (" + md + ")"); + mdrow.addCellContent(dcv.getValue()); + } + } + } + else + { + Para nochanges = div.addPara(); + nochanges.addContent(T_no_changes); + } + Para actions = div.addPara(); + Button cancel = actions.addButton("submit_return"); + cancel.setValue(T_submit_return); + + div.addHidden("administrative-continue").setValue(knot.getId()); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportMain.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportMain.java index f087828425..b3699c3616 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportMain.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportMain.java @@ -30,40 +30,38 @@ import org.xml.sax.SAXException; public class MetadataImportMain extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); - private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); - private static final Message T_submit_upload = message("xmlui.administrative.metadataimport.MetadataImportMain.submit_upload"); - private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); - - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_trail); - } + private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); + private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); + private static final Message T_submit_upload = message("xmlui.administrative.metadataimport.MetadataImportMain.submit_upload"); + private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); - - public void addBody(Body body) throws SAXException, WingException, SQLException - { + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - // DIVISION: metadata-import - Division div = body.addInteractiveDivision("metadata-import",contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART,"primary administrative"); - div.setHead(T_head1); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_trail); + } - Para file = div.addPara(); - file.addFile("file"); - Para actions = div.addPara(); - Button button = actions.addButton("submit_upload"); - button.setValue(T_submit_upload); + public void addBody(Body body) + throws SAXException, WingException, SQLException + { + // DIVISION: metadata-import + Division div = body.addInteractiveDivision("metadata-import",contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART,"primary administrative"); + div.setHead(T_head1); - div.addHidden("administrative-continue").setValue(knot.getId()); - } - - + Para file = div.addPara(); + file.addFile("file"); + Para actions = div.addPara(); + Button button = actions.addButton("submit_upload"); + button.setValue(T_submit_upload); + + div.addHidden("administrative-continue").setValue(knot.getId()); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportUpload.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportUpload.java index c671e9652d..1b99301d9a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportUpload.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/metadataimport/MetadataImportUpload.java @@ -43,18 +43,18 @@ import org.dspace.app.bulkedit.BulkEditChange; public class MetadataImportUpload extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_return = message("xmlui.general.return"); - private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); - private static final Message T_no_changes = message("xmlui.administrative.metadataimport.general.no_changes"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_return = message("xmlui.general.return"); + private static final Message T_trail = message("xmlui.administrative.metadataimport.general.trail"); + private static final Message T_no_changes = message("xmlui.administrative.metadataimport.general.no_changes"); private static final Message T_new_item = message("xmlui.administrative.metadataimport.general.new_item"); - private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); - private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); + private static final Message T_title = message("xmlui.administrative.metadataimport.general.title"); + private static final Message T_head1 = message("xmlui.administrative.metadataimport.general.head1"); - private static final Message T_para = message("xmlui.administrative.metadataimport.MetadataImportUpload.hint"); + private static final Message T_para = message("xmlui.administrative.metadataimport.MetadataImportUpload.hint"); private static final Message T_submit_confirm = message("xmlui.administrative.metadataimport.MetadataImportUpload.submit_confirm"); - private static final Message T_changes_pending = message("xmlui.administrative.metadataimport.MetadataImportUpload.changes_pending"); + private static final Message T_changes_pending = message("xmlui.administrative.metadataimport.MetadataImportUpload.changes_pending"); private static final Message T_item_addition = message("xmlui.administrative.metadataimport.MetadataImportUpload.item_add"); private static final Message T_item_deletion = message("xmlui.administrative.metadataimport.MetadataImportUpload.item_remove"); private static final Message T_collection_newowner = message("xmlui.administrative.metadataimport.MetadataImportUpload.collection_newowner"); @@ -65,36 +65,39 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { private static final Message T_item_withdraw = message("xmlui.administrative.metadataimport.MetadataImportUpload.item_withdraw"); private static final Message T_item_reinstate = message("xmlui.administrative.metadataimport.MetadataImportUpload.item_reinstate"); - public void addPageMeta(PageMeta pageMeta) throws WingException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - - public void addBody(Body body) throws SAXException, WingException, SQLException - { - // Get list of changes + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_trail); + } - Request request = ObjectModelHelper.getRequest(objectModel); + + public void addBody(Body body) + throws SAXException, WingException, SQLException + { + // Get list of changes + + Request request = ObjectModelHelper.getRequest(objectModel); ArrayList changes = null; int num_changes = 0; - if(request.getAttribute("changes") != null) + if (request.getAttribute("changes") != null) { changes = ((ArrayList)request.getAttribute("changes")); num_changes = changes.size(); } - // DIVISION: metadata-import - Division div = body.addInteractiveDivision("metadata-import",contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART,"primary administrative"); - div.setHead(T_head1); - - if(num_changes > 0) - { + // DIVISION: metadata-import + Division div = body.addInteractiveDivision("metadata-import", + contextPath + "/admin/metadataimport", Division.METHOD_MULTIPART, + "primary administrative"); + div.setHead(T_head1); + if (num_changes > 0) + { div.addPara(T_para); Table mdchanges = div.addTable("metadata-changes", num_changes, 2); @@ -132,7 +135,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { // Show actions if (change.isDeleted()) { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-delete"); + Row mdrow = mdchanges.addRow("addition", Row.ROLE_DATA, "item-delete"); Cell cell = mdrow.addCell(); cell.addContent(T_item_delete); @@ -140,7 +143,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { } if (change.isWithdrawn()) { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-withdraw"); + Row mdrow = mdchanges.addRow("addition", Row.ROLE_DATA, "item-withdraw"); Cell cell = mdrow.addCell(); cell.addContent(T_item_withdraw); @@ -148,7 +151,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { } if (change.isReinstated()) { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"item-reinstate"); + Row mdrow = mdchanges.addRow("addition", Row.ROLE_DATA, "item-reinstate"); Cell cell = mdrow.addCell(); cell.addContent(T_item_reinstate); @@ -163,7 +166,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { { String cHandle = c.getHandle(); String cName = c.getName(); - Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); + Row colrow = mdchanges.addRow("addition", Row.ROLE_DATA, "metadata-addition"); colrow.addCellContent(T_collection_newowner); colrow.addCellContent(cHandle + " (" + cName + ")"); } @@ -177,7 +180,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { { String cHandle = c.getHandle(); String cName = c.getName(); - Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); + Row colrow = mdchanges.addRow("deletion", Row.ROLE_DATA, "metadata-deletion"); colrow.addCellContent(T_collection_oldowner); colrow.addCellContent(cHandle + " (" + cName + ")"); } @@ -188,7 +191,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { { String cHandle = c.getHandle(); String cName = c.getName(); - Row colrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); + Row colrow = mdchanges.addRow("addition", Row.ROLE_DATA, "metadata-addition"); colrow.addCellContent(T_collection_mapped); colrow.addCellContent(cHandle + " (" + cName + ")"); } @@ -198,7 +201,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { { String cHandle = c.getHandle(); String cName = c.getName(); - Row colrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); + Row colrow = mdchanges.addRow("deletion", Row.ROLE_DATA, "metadata-deletion"); colrow.addCellContent(T_collection_unmapped); colrow.addCellContent(cHandle + " (" + cName + ")"); } @@ -206,7 +209,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { // Show additions for (BulkEditMetadataValue dcv : adds) { - Row mdrow = mdchanges.addRow("addition",Row.ROLE_DATA,"metadata-addition"); + Row mdrow = mdchanges.addRow("addition", Row.ROLE_DATA, "metadata-addition"); String md = dcv.getSchema() + "." + dcv.getElement(); if (dcv.getQualifier() != null) { @@ -226,7 +229,7 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { // Show removals for (BulkEditMetadataValue dcv : removes) { - Row mdrow = mdchanges.addRow("deletion",Row.ROLE_DATA,"metadata-deletion"); + Row mdrow = mdchanges.addRow("deletion", Row.ROLE_DATA, "metadata-deletion"); String md = dcv.getSchema() + "." + dcv.getElement(); if (dcv.getQualifier() != null) { @@ -258,9 +261,6 @@ public class MetadataImportUpload extends AbstractDSpaceTransformer { cancel.setValue(T_submit_return); } - - div.addHidden("administrative-continue").setValue(knot.getId()); - } - + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteBitstreamFormatsConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteBitstreamFormatsConfirm.java index 402c17e1d8..d270194a5f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteBitstreamFormatsConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteBitstreamFormatsConfirm.java @@ -27,94 +27,96 @@ import org.dspace.content.service.BitstreamFormatService; /** * Confirm the deletion of bitstream formats by listing to-be-deleted * formats and asking the user for confirmation. - * + * * @author Scott Phillips */ -public class DeleteBitstreamFormatsConfirm extends AbstractDSpaceTransformer +public class DeleteBitstreamFormatsConfirm extends AbstractDSpaceTransformer { - - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - private static final Message T_submit_delete = - message("xmlui.general.delete"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); - private static final Message T_title = - message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.title"); - private static final Message T_format_registry_trail = - message("xmlui.administrative.registries.general.format_registry_trail"); - private static final Message T_trail = - message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.trail"); - private static final Message T_head = - message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.head"); - private static final Message T_para1 = - message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.para1"); - private static final Message T_column1 = - message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column1"); - private static final Message T_column2 = - message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column2"); - private static final Message T_column3 = - message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column3"); + + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + private static final Message T_submit_delete = + message("xmlui.general.delete"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); + private static final Message T_title = + message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.title"); + private static final Message T_format_registry_trail = + message("xmlui.administrative.registries.general.format_registry_trail"); + private static final Message T_trail = + message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.trail"); + private static final Message T_head = + message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.head"); + private static final Message T_para1 = + message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.para1"); + private static final Message T_column1 = + message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column1"); + private static final Message T_column2 = + message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column2"); + private static final Message T_column3 = + message("xmlui.administrative.registries.DeleteBitstreamFormatsConfirm.column3"); - protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); + protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); - - - public void addPageMeta(PageMeta pageMeta) throws WingException + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/format-registry",T_format_registry_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - String idsString = parameters.getParameter("formatIDs", null); - - ArrayList formats = new ArrayList(); - for (String id : idsString.split(",")) - { - BitstreamFormat format = bitstreamFormatService.find(context,Integer.valueOf(id)); - formats.add(format); - } - - // DIVISION: bitstream-format-confirm-delete - Division deleted = body.addInteractiveDivision("bitstream-format-confirm-delete",contextPath+"/admin/format-registry",Division.METHOD_POST,"primary administrative format-registry"); - deleted.setHead(T_head); - deleted.addPara(T_para1); - - Table table = deleted.addTable("format-confirm-delete",formats.size() + 1, 3); + + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + String idsString = parameters.getParameter("formatIDs", null); + + ArrayList formats = new ArrayList(); + for (String id : idsString.split(",")) + { + BitstreamFormat format = bitstreamFormatService.find(context,Integer.valueOf(id)); + formats.add(format); + } + + // DIVISION: bitstream-format-confirm-delete + Division deleted = body.addInteractiveDivision( + "bitstream-format-confirm-delete", contextPath + "/admin/format-registry", + Division.METHOD_POST, "primary administrative format-registry"); + deleted.setHead(T_head); + deleted.addPara(T_para1); + + Table table = deleted.addTable("format-confirm-delete",formats.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); - - for (BitstreamFormat format : formats) - { - if (format == null) + + for (BitstreamFormat format : formats) + { + if (format == null) { continue; } - - String formatID = String.valueOf(format.getID()); - String mimetype = format.getMIMEType(); - String name = format.getShortDescription(); - - Row row = table.addRow(); - row.addCell().addContent(formatID); - row.addCell().addContent(mimetype); - row.addCell().addContent(name); - } - Para buttons = deleted.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_delete); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - deleted.addHidden("administrative-continue").setValue(knot.getId()); + String formatID = String.valueOf(format.getID()); + String mimetype = format.getMIMEType(); + String name = format.getShortDescription(); + + Row row = table.addRow(); + row.addCell().addContent(formatID); + row.addCell().addContent(mimetype); + row.addCell().addContent(name); + } + Para buttons = deleted.addPara(); + buttons.addButton("submit_confirm").setValue(T_submit_delete); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + deleted.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataFieldsConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataFieldsConfirm.java index 74e8d4e6c3..138dba1642 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataFieldsConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataFieldsConfirm.java @@ -23,113 +23,117 @@ import java.util.ArrayList; /** * Prompt the user with a list of to-be-deleted metadata fields and * ask the user if they are sure they want them deleted. - * + * * @author Scott Phillips */ -public class DeleteMetadataFieldsConfirm extends AbstractDSpaceTransformer +public class DeleteMetadataFieldsConfirm extends AbstractDSpaceTransformer { - - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - private static final Message T_submit_delete = - message("xmlui.general.delete"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); - private static final Message T_title = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.title"); - private static final Message T_metadata_registry_trail = - message("xmlui.administrative.registries.general.metadata_registry_trail"); - private static final Message T_trail = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.trail"); - private static final Message T_head = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.head"); - private static final Message T_para1 = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.para1"); - private static final Message T_warning = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.warning"); - private static final Message T_para2 = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.para2"); - private static final Message T_column1 = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column1"); - private static final Message T_column2 = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column2"); - private static final Message T_column3 = - message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column3"); - protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + private static final Message T_submit_delete = + message("xmlui.general.delete"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); + private static final Message T_title = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.title"); + private static final Message T_metadata_registry_trail = + message("xmlui.administrative.registries.general.metadata_registry_trail"); + private static final Message T_trail = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.trail"); + private static final Message T_head = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.head"); + private static final Message T_para1 = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.para1"); + private static final Message T_warning = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.warning"); + private static final Message T_para2 = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.para2"); + private static final Message T_column1 = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column1"); + private static final Message T_column2 = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column2"); + private static final Message T_column3 = + message("xmlui.administrative.registries.DeleteMetadataFieldsConfirm.column3"); - - public void addPageMeta(PageMeta pageMeta) throws WingException + protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); + + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - String idsString = parameters.getParameter("fieldIDs", null); - - ArrayList fields = new ArrayList(); - for (String id : idsString.split(",")) - { - MetadataField field = metadataFieldService.find(context,Integer.valueOf(id)); - fields.add(field); - } - - // DIVISION: metadata-field-confirm-delete - Division deleted = body.addInteractiveDivision("metadata-field-confirm-delete",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); - deleted.setHead(T_head); - deleted.addPara(T_para1); - Para warning = deleted.addPara(); - warning.addHighlight("bold").addContent(T_warning); - warning.addContent(T_para2); - - Table table = deleted.addTable("field-confirm-delete",fields.size() + 1, 3); + + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + String idsString = parameters.getParameter("fieldIDs", null); + + ArrayList fields = new ArrayList(); + for (String id : idsString.split(",")) + { + MetadataField field = metadataFieldService.find(context,Integer.valueOf(id)); + fields.add(field); + } + + // DIVISION: metadata-field-confirm-delete + Division deleted = body.addInteractiveDivision( + "metadata-field-confirm-delete", contextPath + "/admin/metadata-registry", + Division.METHOD_POST, "primary administrative metadata-registry"); + deleted.setHead(T_head); + deleted.addPara(T_para1); + Para warning = deleted.addPara(); + warning.addHighlight("bold").addContent(T_warning); + warning.addContent(T_para2); + + Table table = deleted.addTable("field-confirm-delete", fields.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); - - for (MetadataField field : fields) - { - if (field == null) + + for (MetadataField field : fields) + { + if (field == null) { continue; } - - String fieldID = String.valueOf(field.getID()); - String fieldEelement = field.getElement(); - String fieldQualifier = field.getQualifier(); - - MetadataSchema schema = field.getMetadataSchema(); - String schemaName = schema.getName(); - - StringBuilder fieldName = new StringBuilder() - .append(schemaName) - .append(".") - .append(fieldEelement); - if (fieldQualifier != null && fieldQualifier.length() > 0) + String fieldID = String.valueOf(field.getID()); + String fieldEelement = field.getElement(); + String fieldQualifier = field.getQualifier(); + + MetadataSchema schema = field.getMetadataSchema(); + String schemaName = schema.getName(); + + StringBuilder fieldName = new StringBuilder() + .append(schemaName) + .append(".") + .append(fieldEelement); + + if (fieldQualifier != null && fieldQualifier.length() > 0) { - fieldName.append(".").append(fieldQualifier); + fieldName.append(".").append(fieldQualifier); } - - String fieldScopeNote = field.getScopeNote(); - - Row row = table.addRow(); - row.addCell().addContent(fieldID); - row.addCell().addContent(fieldName.toString()); - row.addCell().addContent(fieldScopeNote); - } - Para buttons = deleted.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_delete); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - deleted.addHidden("administrative-continue").setValue(knot.getId()); + + String fieldScopeNote = field.getScopeNote(); + + Row row = table.addRow(); + row.addCell().addContent(fieldID); + row.addCell().addContent(fieldName.toString()); + row.addCell().addContent(fieldScopeNote); + } + Para buttons = deleted.addPara(); + buttons.addButton("submit_confirm").setValue(T_submit_delete); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + deleted.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataSchemaConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataSchemaConfirm.java index bd9dc386bd..6869fa38e0 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataSchemaConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/DeleteMetadataSchemaConfirm.java @@ -21,88 +21,92 @@ import java.util.ArrayList; /** * Prompt the user to determin if they really want to delete the displayed schemas. - * + * * @author Scott Phillips */ -public class DeleteMetadataSchemaConfirm extends AbstractDSpaceTransformer +public class DeleteMetadataSchemaConfirm extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - private static final Message T_title = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.title"); - private static final Message T_metadata_registry_trail = - message("xmlui.administrative.registries.general.metadata_registry_trail"); - private static final Message T_trail = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.trail"); - private static final Message T_head = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.head"); - private static final Message T_para1 = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.para1"); - private static final Message T_warning = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.warning"); - private static final Message T_para2 = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.para2"); - private static final Message T_column1 = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column1"); - private static final Message T_column2 = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column2"); - private static final Message T_column3 = - message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column3"); - private static final Message T_submit_delete = - message("xmlui.general.delete"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + private static final Message T_title = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.title"); + private static final Message T_metadata_registry_trail = + message("xmlui.administrative.registries.general.metadata_registry_trail"); + private static final Message T_trail = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.trail"); + private static final Message T_head = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.head"); + private static final Message T_para1 = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.para1"); + private static final Message T_warning = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.warning"); + private static final Message T_para2 = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.para2"); + private static final Message T_column1 = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column1"); + private static final Message T_column2 = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column2"); + private static final Message T_column3 = + message("xmlui.administrative.registries.DeleteMetadataSchemaConfirm.column3"); + private static final Message T_submit_delete = + message("xmlui.general.delete"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); - protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); + protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - String idsString = parameters.getParameter("schemaIDs", null); - - ArrayList schemas = new ArrayList(); - for (String id : idsString.split(",")) - { - MetadataSchema schema = metadataSchemaService.find(context,Integer.valueOf(id)); - schemas.add(schema); - } - - // DIVISION: metadata-schema-confirm-delete - Division deleted = body.addInteractiveDivision("metadata-schema-confirm-delete",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); - deleted.setHead(T_head); - deleted.addPara(T_para1); - Para warning = deleted.addPara(); - warning.addHighlight("bold").addContent(T_warning); - warning.addContent(T_para2); - - Table table = deleted.addTable("schema-confirm-delete",schemas.size() + 1, 3); + + + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + String idsString = parameters.getParameter("schemaIDs", null); + + ArrayList schemas = new ArrayList(); + for (String id : idsString.split(",")) + { + MetadataSchema schema = metadataSchemaService.find(context,Integer.valueOf(id)); + schemas.add(schema); + } + + // DIVISION: metadata-schema-confirm-delete + Division deleted = body.addInteractiveDivision( + "metadata-schema-confirm-delete", contextPath + "/admin/metadata-registry", + Division.METHOD_POST, "primary administrative metadata-registry"); + deleted.setHead(T_head); + deleted.addPara(T_para1); + Para warning = deleted.addPara(); + warning.addHighlight("bold").addContent(T_warning); + warning.addContent(T_para2); + + Table table = deleted.addTable("schema-confirm-delete",schemas.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); - - for (MetadataSchema schema : schemas) - { - Row row = table.addRow(); - row.addCell().addContent(schema.getID()); - row.addCell().addContent(schema.getNamespace()); - row.addCell().addContent(schema.getName()); - } - Para buttons = deleted.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_delete); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - deleted.addHidden("administrative-continue").setValue(knot.getId()); + + for (MetadataSchema schema : schemas) + { + Row row = table.addRow(); + row.addCell().addContent(schema.getID()); + row.addCell().addContent(schema.getNamespace()); + row.addCell().addContent(schema.getName()); + } + Para buttons = deleted.addPara(); + buttons.addButton("submit_confirm").setValue(T_submit_delete); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + deleted.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditBitstreamFormat.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditBitstreamFormat.java index e33ee524cd..9aff500921 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditBitstreamFormat.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditBitstreamFormat.java @@ -30,96 +30,98 @@ import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.service.BitstreamFormatService; /** - * Enable the user to edit a bitstream format's metadata. - * + * Enable the user to edit a bitstream format's metadata. + * * @author Scott Phillips */ -public class EditBitstreamFormat extends AbstractDSpaceTransformer -{ - - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - private static final Message T_title = - message("xmlui.administrative.registries.EditBitstreamFormat.title"); - private static final Message T_format_registry_trail = - message("xmlui.administrative.registries.general.format_registry_trail"); - private static final Message T_trail = - message("xmlui.administrative.registries.EditBitstreamFormat.trail"); - private static final Message T_head1 = - message("xmlui.administrative.registries.EditBitstreamFormat.head1"); - private static final Message T_head2 = - message("xmlui.administrative.registries.EditBitstreamFormat.head2"); - private static final Message T_para1 = - message("xmlui.administrative.registries.EditBitstreamFormat.para1"); - private static final Message T_name = - message("xmlui.administrative.registries.EditBitstreamFormat.name"); - private static final Message T_name_help = - message("xmlui.administrative.registries.EditBitstreamFormat.name_help"); - private static final Message T_name_error = - message("xmlui.administrative.registries.EditBitstreamFormat.name_error"); - private static final Message T_mimetype = - message("xmlui.administrative.registries.EditBitstreamFormat.mimetype"); - private static final Message T_mimetype_help = - message("xmlui.administrative.registries.EditBitstreamFormat.mimetype_help"); - private static final Message T_description = - message("xmlui.administrative.registries.EditBitstreamFormat.description"); - private static final Message T_support = - message("xmlui.administrative.registries.EditBitstreamFormat.support"); - private static final Message T_support_help = - message("xmlui.administrative.registries.EditBitstreamFormat.support_help"); - private static final Message T_support_0 = - message("xmlui.administrative.registries.EditBitstreamFormat.support_0"); - private static final Message T_support_1 = - message("xmlui.administrative.registries.EditBitstreamFormat.support_1"); - private static final Message T_support_2 = - message("xmlui.administrative.registries.EditBitstreamFormat.support_2"); - private static final Message T_internal = - message("xmlui.administrative.registries.EditBitstreamFormat.internal"); - private static final Message T_internal_help = - message("xmlui.administrative.registries.EditBitstreamFormat.internal_help"); - private static final Message T_extensions = - message("xmlui.administrative.registries.EditBitstreamFormat.extensions"); - private static final Message T_extensions_help = - message("xmlui.administrative.registries.EditBitstreamFormat.extensions_help"); - private static final Message T_submit_save = - message("xmlui.general.save"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); +public class EditBitstreamFormat extends AbstractDSpaceTransformer +{ - protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + private static final Message T_title = + message("xmlui.administrative.registries.EditBitstreamFormat.title"); + private static final Message T_format_registry_trail = + message("xmlui.administrative.registries.general.format_registry_trail"); + private static final Message T_trail = + message("xmlui.administrative.registries.EditBitstreamFormat.trail"); + private static final Message T_head1 = + message("xmlui.administrative.registries.EditBitstreamFormat.head1"); + private static final Message T_head2 = + message("xmlui.administrative.registries.EditBitstreamFormat.head2"); + private static final Message T_para1 = + message("xmlui.administrative.registries.EditBitstreamFormat.para1"); + private static final Message T_name = + message("xmlui.administrative.registries.EditBitstreamFormat.name"); + private static final Message T_name_help = + message("xmlui.administrative.registries.EditBitstreamFormat.name_help"); + private static final Message T_name_error = + message("xmlui.administrative.registries.EditBitstreamFormat.name_error"); + private static final Message T_mimetype = + message("xmlui.administrative.registries.EditBitstreamFormat.mimetype"); + private static final Message T_mimetype_help = + message("xmlui.administrative.registries.EditBitstreamFormat.mimetype_help"); + private static final Message T_description = + message("xmlui.administrative.registries.EditBitstreamFormat.description"); + private static final Message T_support = + message("xmlui.administrative.registries.EditBitstreamFormat.support"); + private static final Message T_support_help = + message("xmlui.administrative.registries.EditBitstreamFormat.support_help"); + private static final Message T_support_0 = + message("xmlui.administrative.registries.EditBitstreamFormat.support_0"); + private static final Message T_support_1 = + message("xmlui.administrative.registries.EditBitstreamFormat.support_1"); + private static final Message T_support_2 = + message("xmlui.administrative.registries.EditBitstreamFormat.support_2"); + private static final Message T_internal = + message("xmlui.administrative.registries.EditBitstreamFormat.internal"); + private static final Message T_internal_help = + message("xmlui.administrative.registries.EditBitstreamFormat.internal_help"); + private static final Message T_extensions = + message("xmlui.administrative.registries.EditBitstreamFormat.extensions"); + private static final Message T_extensions_help = + message("xmlui.administrative.registries.EditBitstreamFormat.extensions_help"); + private static final Message T_submit_save = + message("xmlui.general.save"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); - public void addPageMeta(PageMeta pageMeta) throws WingException + protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); + + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/format-registry",T_format_registry_trail); + pageMeta.addTrailLink(contextPath + "/admin/format-registry", T_format_registry_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException - { - // Get our parameters & state - int formatID = parameters.getParameterAsInteger("formatID",-1); - BitstreamFormat format = null; - - if (formatID >= 0) + + + public void addBody(Body body) + throws WingException, SQLException + { + // Get our parameters & state + int formatID = parameters.getParameterAsInteger("formatID", -1); + BitstreamFormat format = null; + + if (formatID >= 0) { - format = bitstreamFormatService.find(context, formatID); + format = bitstreamFormatService.find(context, formatID); } - - String errorString = parameters.getParameter("errors",null); - ArrayList errors = new ArrayList(); - if (errorString != null) + + String errorString = parameters.getParameter("errors", null); + ArrayList errors = new ArrayList(); + if (errorString != null) { for (String error : errorString.split(",")) { errors.add(error); } } - - Request request = ObjectModelHelper.getRequest(objectModel); + + Request request = ObjectModelHelper.getRequest(objectModel); String mimetypeValue = request.getParameter("mimetype"); String nameValue = request.getParameter("short_description"); String descriptionValue = request.getParameter("description"); @@ -130,115 +132,112 @@ public class EditBitstreamFormat extends AbstractDSpaceTransformer // Remove leading periods from file extensions. for (int i = 0; i < extensionValues.size(); i++) { - if (extensionValues.get(i).startsWith(".")) + if (extensionValues.get(i).startsWith(".")) { extensionValues.set(i, extensionValues.get(i).substring(1)); } } - + if (format != null) { - if (mimetypeValue == null) + if (mimetypeValue == null) { mimetypeValue = format.getMIMEType(); } - if (nameValue == null) + if (nameValue == null) { nameValue = format.getShortDescription(); } - if (descriptionValue == null) + if (descriptionValue == null) { descriptionValue = format.getDescription(); } - if (supportLevelValue == null) + if (supportLevelValue == null) { supportLevelValue = String.valueOf(format.getSupportLevel()); } - if (request.getParameter("mimetype") == null) + if (request.getParameter("mimetype") == null) { internalValue = format.isInternal() ? "true" : null; } - if (request.getParameter("extensions") == null) + if (request.getParameter("extensions") == null) { extensionValues = format.getExtensions(); } } - - - - + + // DIVISION: edit-bitstream-format - Division main = body.addInteractiveDivision("edit-bitstream-format",contextPath+"/admin/format-registry",Division.METHOD_POST,"primary administrative format-registry"); - if (formatID == -1) + Division main = body.addInteractiveDivision("edit-bitstream-format", + contextPath + "/admin/format-registry", Division.METHOD_POST, + "primary administrative format-registry"); + if (formatID == -1) { main.setHead(T_head1); } - else + else { main.setHead(T_head2.parameterize(nameValue)); } - main.addPara(T_para1); - - List form = main.addList("edit-bitstream-format",List.TYPE_FORM); - - Text name = form.addItem().addText("short_description"); - name.setRequired(); - name.setLabel(T_name); - name.setHelp(T_name_help); - name.setValue(nameValue); - name.setSize(35); - if (errors.contains("short_description")) + main.addPara(T_para1); + + List form = main.addList("edit-bitstream-format",List.TYPE_FORM); + + Text name = form.addItem().addText("short_description"); + name.setRequired(); + name.setLabel(T_name); + name.setHelp(T_name_help); + name.setValue(nameValue); + name.setSize(35); + if (errors.contains("short_description")) { name.addError(T_name_error); } - - Text mimeType = form.addItem().addText("mimetype"); - mimeType.setLabel(T_mimetype); - mimeType.setHelp(T_mimetype_help); - mimeType.setValue(mimetypeValue); - mimeType.setSize(35); - - // Do not allow anyone to change the name of the unknown format. - if (format != null && format.getID() == 1) + + Text mimeType = form.addItem().addText("mimetype"); + mimeType.setLabel(T_mimetype); + mimeType.setHelp(T_mimetype_help); + mimeType.setValue(mimetypeValue); + mimeType.setSize(35); + + // Do not allow anyone to change the name of the unknown format. + if (format != null && format.getID() == 1) { name.setDisabled(); } - TextArea description = form.addItem().addTextArea("description"); - description.setLabel(T_description); - description.setValue(descriptionValue); - description.setSize(3, 35); - - Select supportLevel = form.addItem().addSelect("support_level"); - supportLevel.setLabel(T_support); - supportLevel.setHelp(T_support_help); - supportLevel.addOption(0,T_support_0); - supportLevel.addOption(1,T_support_1); - supportLevel.addOption(2,T_support_2); - supportLevel.setOptionSelected(supportLevelValue); - - CheckBox internal = form.addItem().addCheckBox("internal"); - internal.setLabel(T_internal); - internal.setHelp(T_internal_help); - internal.addOption((internalValue != null),"true"); - - Text extensions = form.addItem().addText("extensions"); - extensions.setLabel(T_extensions); - extensions.setHelp(T_extensions_help); - extensions.enableAddOperation(); - extensions.enableDeleteOperation(); - for (String extensionValue : extensionValues) - { - extensions.addInstance().setValue(extensionValue); - } - - Item actions = form.addItem(); - actions.addButton("submit_save").setValue(T_submit_save); - actions.addButton("submit_cancel").setValue(T_submit_cancel); - - - main.addHidden("administrative-continue").setValue(knot.getId()); - + TextArea description = form.addItem().addTextArea("description"); + description.setLabel(T_description); + description.setValue(descriptionValue); + description.setSize(3, 35); + + Select supportLevel = form.addItem().addSelect("support_level"); + supportLevel.setLabel(T_support); + supportLevel.setHelp(T_support_help); + supportLevel.addOption(0,T_support_0); + supportLevel.addOption(1,T_support_1); + supportLevel.addOption(2,T_support_2); + supportLevel.setOptionSelected(supportLevelValue); + + CheckBox internal = form.addItem().addCheckBox("internal"); + internal.setLabel(T_internal); + internal.setHelp(T_internal_help); + internal.addOption((internalValue != null),"true"); + + Text extensions = form.addItem().addText("extensions"); + extensions.setLabel(T_extensions); + extensions.setHelp(T_extensions_help); + extensions.enableAddOperation(); + extensions.enableDeleteOperation(); + for (String extensionValue : extensionValues) + { + extensions.addInstance().setValue(extensionValue); + } + + Item actions = form.addItem(); + actions.addButton("submit_save").setValue(T_submit_save); + actions.addButton("submit_cancel").setValue(T_submit_cancel); + + main.addHidden("administrative-continue").setValue(knot.getId()); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditMetadataSchema.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditMetadataSchema.java index 5490c4e48a..f67275f77e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditMetadataSchema.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/EditMetadataSchema.java @@ -27,364 +27,369 @@ import java.util.ArrayList; * the schema, prompt the user to add a new field. If a current * field is selected then the field may be updated in the same * place where new field addition would be. - * + * * @author Scott Phillips */ -public class EditMetadataSchema extends AbstractDSpaceTransformer -{ - - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - private static final Message T_title = - message("xmlui.administrative.registries.EditMetadataSchema.title"); - private static final Message T_metadata_registry_trail = - message("xmlui.administrative.registries.general.metadata_registry_trail"); - private static final Message T_trail = - message("xmlui.administrative.registries.EditMetadataSchema.trail"); - private static final Message T_head1 = - message("xmlui.administrative.registries.EditMetadataSchema.head1"); - private static final Message T_para1 = - message("xmlui.administrative.registries.EditMetadataSchema.para1"); - private static final Message T_head2 = - message("xmlui.administrative.registries.EditMetadataSchema.head2"); - private static final Message T_column1 = - message("xmlui.administrative.registries.EditMetadataSchema.column1"); - private static final Message T_column2 = - message("xmlui.administrative.registries.EditMetadataSchema.column2"); - private static final Message T_column3 = - message("xmlui.administrative.registries.EditMetadataSchema.column3"); - private static final Message T_column4 = - message("xmlui.administrative.registries.EditMetadataSchema.column4"); - private static final Message T_empty = - message("xmlui.administrative.registries.EditMetadataSchema.empty"); - private static final Message T_submit_return = - message("xmlui.general.return"); - private static final Message T_submit_delete = - message("xmlui.administrative.registries.EditMetadataSchema.submit_delete"); - private static final Message T_submit_move = - message("xmlui.administrative.registries.EditMetadataSchema.submit_move"); - private static final Message T_head3 = - message("xmlui.administrative.registries.EditMetadataSchema.head3"); - private static final Message T_name = - message("xmlui.administrative.registries.EditMetadataSchema.name"); - private static final Message T_note = - message("xmlui.administrative.registries.EditMetadataSchema.note"); - private static final Message T_note_help = - message("xmlui.administrative.registries.EditMetadataSchema.note_help"); - private static final Message T_submit_add = - message("xmlui.administrative.registries.EditMetadataSchema.submit_add"); - private static final Message T_head4 = - message("xmlui.administrative.registries.EditMetadataSchema.head4"); - private static final Message T_submit_update = - message("xmlui.administrative.registries.EditMetadataSchema.submit_update"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); - private static final Message T_error = - message("xmlui.administrative.registries.EditMetadataSchema.error"); - private static final Message T_error_duplicate_field = - message("xmlui.administrative.registries.EditMetadataSchema.error_duplicate_field"); - private static final Message T_error_element_empty = - message("xmlui.administrative.registries.EditMetadataSchema.error_element_empty"); - private static final Message T_error_element_badchar = - message("xmlui.administrative.registries.EditMetadataSchema.error_element_badchar"); - private static final Message T_error_element_tolong = - message("xmlui.administrative.registries.EditMetadataSchema.error_element_tolong"); - private static final Message T_error_qualifier_tolong = - message("xmlui.administrative.registries.EditMetadataSchema.error_qualifier_tolong"); - private static final Message T_error_qualifier_badchar = - message("xmlui.administrative.registries.EditMetadataSchema.error_qualifier_badchar"); +public class EditMetadataSchema extends AbstractDSpaceTransformer +{ + + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + private static final Message T_title = + message("xmlui.administrative.registries.EditMetadataSchema.title"); + private static final Message T_metadata_registry_trail = + message("xmlui.administrative.registries.general.metadata_registry_trail"); + private static final Message T_trail = + message("xmlui.administrative.registries.EditMetadataSchema.trail"); + private static final Message T_head1 = + message("xmlui.administrative.registries.EditMetadataSchema.head1"); + private static final Message T_para1 = + message("xmlui.administrative.registries.EditMetadataSchema.para1"); + private static final Message T_head2 = + message("xmlui.administrative.registries.EditMetadataSchema.head2"); + private static final Message T_column1 = + message("xmlui.administrative.registries.EditMetadataSchema.column1"); + private static final Message T_column2 = + message("xmlui.administrative.registries.EditMetadataSchema.column2"); + private static final Message T_column3 = + message("xmlui.administrative.registries.EditMetadataSchema.column3"); + private static final Message T_column4 = + message("xmlui.administrative.registries.EditMetadataSchema.column4"); + private static final Message T_empty = + message("xmlui.administrative.registries.EditMetadataSchema.empty"); + private static final Message T_submit_return = + message("xmlui.general.return"); + private static final Message T_submit_delete = + message("xmlui.administrative.registries.EditMetadataSchema.submit_delete"); + private static final Message T_submit_move = + message("xmlui.administrative.registries.EditMetadataSchema.submit_move"); + private static final Message T_head3 = + message("xmlui.administrative.registries.EditMetadataSchema.head3"); + private static final Message T_name = + message("xmlui.administrative.registries.EditMetadataSchema.name"); + private static final Message T_note = + message("xmlui.administrative.registries.EditMetadataSchema.note"); + private static final Message T_note_help = + message("xmlui.administrative.registries.EditMetadataSchema.note_help"); + private static final Message T_submit_add = + message("xmlui.administrative.registries.EditMetadataSchema.submit_add"); + private static final Message T_head4 = + message("xmlui.administrative.registries.EditMetadataSchema.head4"); + private static final Message T_submit_update = + message("xmlui.administrative.registries.EditMetadataSchema.submit_update"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); + private static final Message T_error = + message("xmlui.administrative.registries.EditMetadataSchema.error"); + private static final Message T_error_duplicate_field = + message("xmlui.administrative.registries.EditMetadataSchema.error_duplicate_field"); + private static final Message T_error_element_empty = + message("xmlui.administrative.registries.EditMetadataSchema.error_element_empty"); + private static final Message T_error_element_badchar = + message("xmlui.administrative.registries.EditMetadataSchema.error_element_badchar"); + private static final Message T_error_element_tolong = + message("xmlui.administrative.registries.EditMetadataSchema.error_element_tolong"); + private static final Message T_error_qualifier_tolong = + message("xmlui.administrative.registries.EditMetadataSchema.error_qualifier_tolong"); + private static final Message T_error_qualifier_badchar = + message("xmlui.administrative.registries.EditMetadataSchema.error_qualifier_badchar"); + + protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); + protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); - protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); - protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); - @Override - public void addPageMeta(PageMeta pageMeta) throws WingException + public void addPageMeta(PageMeta pageMeta) + throws WingException { pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/metadata-registry", T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } - - + + @Override - public void addBody(Body body) throws WingException, SQLException - { - // Get our parameters & state - int schemaID = parameters.getParameterAsInteger("schemaID",-1); - int updateID = parameters.getParameterAsInteger("updateID",-1); - int highlightID = parameters.getParameterAsInteger("highlightID",-1); - MetadataSchema schema = metadataSchemaService.find(context,schemaID); - java.util.List fields = metadataFieldService.findAllInSchema(context, schema); - String schemaName = schema.getName(); - String schemaNamespace = schema.getNamespace(); - - String errorString = parameters.getParameter("errors",null); - ArrayList errors = new ArrayList(); - if (errorString != null) - { - for (String error : errorString.split(",")) + public void addBody(Body body) + throws WingException, SQLException + { + // Get our parameters & state + int schemaID = parameters.getParameterAsInteger("schemaID", -1); + int updateID = parameters.getParameterAsInteger("updateID", -1); + int highlightID = parameters.getParameterAsInteger("highlightID", -1); + MetadataSchema schema = metadataSchemaService.find(context, schemaID); + java.util.List fields = metadataFieldService.findAllInSchema(context, schema); + String schemaName = schema.getName(); + String schemaNamespace = schema.getNamespace(); + + String errorString = parameters.getParameter("errors", null); + ArrayList errors = new ArrayList(); + if (errorString != null) + { + for (String error : errorString.split(",")) { - errors.add(error); + errors.add(error); } - } - - + } + + // DIVISION: edit-schema - Division main = body.addInteractiveDivision("metadata-schema-edit",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); - main.setHead(T_head1.parameterize(schemaName)); - main.addPara(T_para1.parameterize(schemaNamespace)); - - - // DIVISION: add or updating a metadata field - if (updateID >= 0) + Division main = body.addInteractiveDivision( + "metadata-schema-edit", contextPath + "/admin/metadata-registry", + Division.METHOD_POST, "primary administrative metadata-registry"); + main.setHead(T_head1.parameterize(schemaName)); + main.addPara(T_para1.parameterize(schemaNamespace)); + + + // DIVISION: add or updating a metadata field + if (updateID >= 0) { // Updating an existing field addUpdateFieldForm(main, schemaName, updateID, errors); } - else + else { // Add a new field addNewFieldForm(main, schemaName, errors); } - - - - // DIVISION: existing fields - Division existingFields = main.addDivision("metadata-schema-edit-existing-fields"); - existingFields.setHead(T_head2); - - Table table = existingFields.addTable("metadata-schema-edit-existing-fields", fields.size()+1, 5); - - Row header = table.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column1); - header.addCellContent(T_column2); - header.addCellContent(T_column3); - header.addCellContent(T_column4); - - for (MetadataField field : fields) - { - String id = String.valueOf(field.getID()); - String fieldElement = field.getElement(); - String fieldQualifier = field.getQualifier(); - - String fieldName = schemaName +"."+ fieldElement; - if (fieldQualifier != null && fieldQualifier.length() > 0) + + + // DIVISION: existing fields + Division existingFields = main.addDivision("metadata-schema-edit-existing-fields"); + existingFields.setHead(T_head2); + + Table table = existingFields.addTable("metadata-schema-edit-existing-fields", fields.size() + 1, 5); + + Row header = table.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column1); + header.addCellContent(T_column2); + header.addCellContent(T_column3); + header.addCellContent(T_column4); + + for (MetadataField field : fields) + { + String id = String.valueOf(field.getID()); + String fieldElement = field.getElement(); + String fieldQualifier = field.getQualifier(); + + String fieldName = schemaName + "." + fieldElement; + if (fieldQualifier != null && fieldQualifier.length() > 0) { fieldName += "." + fieldQualifier; } - - boolean highlight = false; - if (field.getID() == highlightID) + + boolean highlight = false; + if (field.getID() == highlightID) { highlight = true; } - - String fieldScopeNote = field.getScopeNote(); - - String url = contextPath + "/admin/metadata-registry?administrative-continue="+knot.getId()+"&submit_edit&fieldID="+id; - - Row row; - if (highlight) + + String fieldScopeNote = field.getScopeNote(); + + String url = contextPath + "/admin/metadata-registry?administrative-continue=" + + knot.getId() + "&submit_edit&fieldID=" + id; + + Row row; + if (highlight) { row = table.addRow(null, null, "highlight"); } - else + else { row = table.addRow(); } - - CheckBox select = row.addCell().addCheckBox("select_field"); - select.setLabel(id); - select.addOption(id); - - row.addCell().addContent(id); - row.addCell().addXref(url,fieldName); - row.addCell().addContent(fieldScopeNote); - } - - if (fields.size() == 0) - { - // No fields, let the user know. - table.addRow().addCell(1,4).addHighlight("italic").addContent(T_empty); - main.addPara().addButton("submit_return").setValue(T_submit_return); - } - else - { - // Only show the actions if there are fields available to perform them on. - Para actions = main.addPara(); - actions.addButton("submit_delete").setValue(T_submit_delete); - if (metadataSchemaService.findAll(context).size() > 1) + + CheckBox select = row.addCell().addCheckBox("select_field"); + select.setLabel(id); + select.addOption(id); + + row.addCell().addContent(id); + row.addCell().addXref(url,fieldName); + row.addCell().addContent(fieldScopeNote); + } + + if (fields.size() == 0) + { + // No fields, let the user know. + table.addRow().addCell(1,4).addHighlight("italic").addContent(T_empty); + main.addPara().addButton("submit_return").setValue(T_submit_return); + } + else + { + // Only show the actions if there are fields available to perform them on. + Para actions = main.addPara(); + actions.addButton("submit_delete").setValue(T_submit_delete); + if (metadataSchemaService.findAll(context).size() > 1) { actions.addButton("submit_move").setValue(T_submit_move); } - actions.addButton("submit_return").setValue(T_submit_return); - } - - main.addHidden("administrative-continue").setValue(knot.getId()); - - } - - - /** - * Add a form prompting the user to add a new field to the this schema. - * - * @param div The division to add the form too. - * @param schemaName The schemaName currently being operated on. - * @param errors A list of errors from previous attempts at adding new fields. - * @throws org.dspace.app.xmlui.wing.WingException passed through. - */ - public void addNewFieldForm(Division div, String schemaName, java.util.List errors) throws WingException - { - Request request = ObjectModelHelper.getRequest(objectModel); - String elementValue = request.getParameter("newElement"); - String qualifierValue = request.getParameter("newQualifier"); - String noteValue = request.getParameter("newNote"); - - Division newField = div.addDivision("edit-schema-new-field"); - newField.setHead(T_head3); - - List form = newField.addList("edit-schema-new-field-form",List.TYPE_FORM); - addFieldErrors(form, errors); - - form.addLabel(T_name); - Highlight item =form.addItem().addHighlight("big"); - - item.addContent(schemaName+" . "); - Text element = item.addText("newElement"); - item.addContent(" . "); - Text qualifier = item.addText("newQualifier"); - - - element.setSize(15); - element.setValue(elementValue); - - qualifier.setSize(15); - qualifier.setValue(qualifierValue); - - TextArea scopeNote =form.addItem().addTextArea("newNote"); - scopeNote.setLabel(T_note); - scopeNote.setHelp(T_note_help); - scopeNote.setSize(2, 35); - scopeNote.setValue(noteValue); - - form.addItem().addButton("submit_add").setValue(T_submit_add); - } - + actions.addButton("submit_return").setValue(T_submit_return); + } - /** - * Update an existing field by prompting the user for its values. - * - * @param div The division to add the form too. - * @param schemaName The schemaName currently being operated on. - * @param fieldID The id of the field being updated. - * @param errors A list of errors from previous attempts at updating the field. + main.addHidden("administrative-continue").setValue(knot.getId()); + + } + + + /** + * Add a form prompting the user to add a new field to the this schema. + * + * @param div The division to add the form too. + * @param schemaName The schemaName currently being operated on. + * @param errors A list of errors from previous attempts at adding new fields. + * @throws org.dspace.app.xmlui.wing.WingException passed through. + */ + public void addNewFieldForm(Division div, String schemaName, java.util.List errors) + throws WingException + { + Request request = ObjectModelHelper.getRequest(objectModel); + String elementValue = request.getParameter("newElement"); + String qualifierValue = request.getParameter("newQualifier"); + String noteValue = request.getParameter("newNote"); + + Division newField = div.addDivision("edit-schema-new-field"); + newField.setHead(T_head3); + + List form = newField.addList("edit-schema-new-field-form",List.TYPE_FORM); + addFieldErrors(form, errors); + + form.addLabel(T_name); + Highlight item =form.addItem().addHighlight("big"); + + item.addContent(schemaName+" . "); + Text element = item.addText("newElement"); + item.addContent(" . "); + Text qualifier = item.addText("newQualifier"); + + + element.setSize(15); + element.setValue(elementValue); + + qualifier.setSize(15); + qualifier.setValue(qualifierValue); + + TextArea scopeNote =form.addItem().addTextArea("newNote"); + scopeNote.setLabel(T_note); + scopeNote.setHelp(T_note_help); + scopeNote.setSize(2, 35); + scopeNote.setValue(noteValue); + + form.addItem().addButton("submit_add").setValue(T_submit_add); + } + + + /** + * Update an existing field by prompting the user for its values. + * + * @param div The division to add the form too. + * @param schemaName The schemaName currently being operated on. + * @param fieldID The id of the field being updated. + * @param errors A list of errors from previous attempts at updating the field. * @throws org.dspace.app.xmlui.wing.WingException passed through. * @throws java.sql.SQLException passed through. - */ - public void addUpdateFieldForm(Division div, String schemaName, int fieldID, java.util.List errors) throws WingException, SQLException - { - - MetadataField field = metadataFieldService.find(context, fieldID); - - Request request = ObjectModelHelper.getRequest(objectModel); - String elementValue = request.getParameter("updateElement"); - String qualifierValue = request.getParameter("updateQualifier"); - String noteValue = request.getParameter("updateNote"); - - if (elementValue == null) + */ + public void addUpdateFieldForm(Division div, String schemaName, int fieldID, java.util.List errors) + throws WingException, SQLException + { + + MetadataField field = metadataFieldService.find(context, fieldID); + + Request request = ObjectModelHelper.getRequest(objectModel); + String elementValue = request.getParameter("updateElement"); + String qualifierValue = request.getParameter("updateQualifier"); + String noteValue = request.getParameter("updateNote"); + + if (elementValue == null) { elementValue = field.getElement(); } - if (qualifierValue == null) + if (qualifierValue == null) { qualifierValue = field.getQualifier(); } - if (noteValue == null) + if (noteValue == null) { noteValue = field.getScopeNote(); } - - - Division newField = div.addDivision("edit-schema-update-field"); - newField.setHead(T_head4.parameterize(field.getID())); - - List form = newField.addList("edit-schema-update-field-form",List.TYPE_FORM); - - addFieldErrors(form, errors); - - form.addLabel(T_name); - Highlight item =form.addItem().addHighlight("big"); - - item.addContent(schemaName+" . "); - Text element = item.addText("updateElement"); - item.addContent(" . "); - Text qualifier = item.addText("updateQualifier"); - - - element.setSize(13); - element.setValue(elementValue); - - qualifier.setSize(13); - qualifier.setValue(qualifierValue); - - TextArea scopeNote =form.addItem().addTextArea("updateNote"); - scopeNote.setLabel(T_note); - scopeNote.setHelp(T_note_help); - scopeNote.setSize(2, 35); - scopeNote.setValue(noteValue); - - Item actions = form.addItem(); - actions.addButton("submit_update").setValue(T_submit_update); - actions.addButton("submit_cancel").setValue(T_submit_cancel); - - } - - /** - * Determine if there were any special errors and display appropriate - * text. Because of the in-line nature of the element and qualifier - * fields these errors can not be placed on the field. Instead they - * have to be added as separate items above the field. - * - * @param form The form to add errors to. - * @param errors A list of errors. + + Division newField = div.addDivision("edit-schema-update-field"); + newField.setHead(T_head4.parameterize(field.getID())); + + List form = newField.addList("edit-schema-update-field-form",List.TYPE_FORM); + + + addFieldErrors(form, errors); + + form.addLabel(T_name); + Highlight item =form.addItem().addHighlight("big"); + + item.addContent(schemaName+" . "); + Text element = item.addText("updateElement"); + item.addContent(" . "); + Text qualifier = item.addText("updateQualifier"); + + + element.setSize(13); + element.setValue(elementValue); + + qualifier.setSize(13); + qualifier.setValue(qualifierValue); + + TextArea scopeNote =form.addItem().addTextArea("updateNote"); + scopeNote.setLabel(T_note); + scopeNote.setHelp(T_note_help); + scopeNote.setSize(2, 35); + scopeNote.setValue(noteValue); + + Item actions = form.addItem(); + actions.addButton("submit_update").setValue(T_submit_update); + actions.addButton("submit_cancel").setValue(T_submit_cancel); + } + + /** + * Determine if there were any special errors and display appropriate + * text. Because of the in-line nature of the element and qualifier + * fields these errors can not be placed on the field. Instead they + * have to be added as separate items above the field. + * + * @param form The form to add errors to. + * @param errors A list of errors. * @throws org.dspace.app.xmlui.wing.WingException passed through. - */ - public void addFieldErrors(List form, java.util.List errors) throws WingException - { - if (errors.contains("duplicate_field")) - { - form.addLabel(T_error); - form.addItem(T_error_duplicate_field); - } - if (errors.contains("element_empty")) - { - form.addLabel(T_error); - form.addItem(T_error_element_empty); - } - if (errors.contains("element_badchar")) - { - form.addLabel(T_error); - form.addItem(T_error_element_badchar); - } - if (errors.contains("element_tolong")) - { - form.addLabel(T_error); - form.addItem(T_error_element_tolong); - } - if (errors.contains("qualifier_tolong")) - { - form.addLabel(T_error); - form.addItem(T_error_qualifier_tolong); - } - if (errors.contains("qualifier_badchar")) - { - form.addLabel(T_error); - form.addItem(T_error_qualifier_badchar); - } - } - + */ + public void addFieldErrors(List form, java.util.List errors) + throws WingException + { + if (errors.contains("duplicate_field")) + { + form.addLabel(T_error); + form.addItem(T_error_duplicate_field); + } + if (errors.contains("element_empty")) + { + form.addLabel(T_error); + form.addItem(T_error_element_empty); + } + if (errors.contains("element_badchar")) + { + form.addLabel(T_error); + form.addItem(T_error_element_badchar); + } + if (errors.contains("element_tolong")) + { + form.addLabel(T_error); + form.addItem(T_error_element_tolong); + } + if (errors.contains("qualifier_tolong")) + { + form.addLabel(T_error); + form.addItem(T_error_qualifier_tolong); + } + if (errors.contains("qualifier_badchar")) + { + form.addLabel(T_error); + form.addItem(T_error_qualifier_badchar); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/MoveMetadataFields.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/MoveMetadataFields.java index 625913f478..c5c9664c6d 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/MoveMetadataFields.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/administrative/registries/MoveMetadataFields.java @@ -24,118 +24,118 @@ import java.util.List; /** * Show a list of selected fields, and prompt the user to enter a destination schema for these fields. - * + * * @author Scott Phillips */ -public class MoveMetadataFields extends AbstractDSpaceTransformer +public class MoveMetadataFields extends AbstractDSpaceTransformer { - /** Language Strings */ - private static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - private static final Message T_title = - message("xmlui.administrative.registries.MoveMetadataField.title"); - private static final Message T_metadata_registry_trail = - message("xmlui.administrative.registries.general.metadata_registry_trail"); - private static final Message T_trail = - message("xmlui.administrative.registries.MoveMetadataField.trail"); - private static final Message T_head1 = - message("xmlui.administrative.registries.MoveMetadataField.head1"); - private static final Message T_para1 = - message("xmlui.administrative.registries.MoveMetadataField.para1"); - private static final Message T_column1 = - message("xmlui.administrative.registries.MoveMetadataField.column1"); - private static final Message T_column2 = - message("xmlui.administrative.registries.MoveMetadataField.column2"); - private static final Message T_column3 = - message("xmlui.administrative.registries.MoveMetadataField.column3"); - private static final Message T_para2 = - message("xmlui.administrative.registries.MoveMetadataField.para2"); - private static final Message T_submit_move = - message("xmlui.administrative.registries.MoveMetadataField.submit_move"); - private static final Message T_submit_cancel = - message("xmlui.general.cancel"); + /** Language Strings */ + private static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + private static final Message T_title = + message("xmlui.administrative.registries.MoveMetadataField.title"); + private static final Message T_metadata_registry_trail = + message("xmlui.administrative.registries.general.metadata_registry_trail"); + private static final Message T_trail = + message("xmlui.administrative.registries.MoveMetadataField.trail"); + private static final Message T_head1 = + message("xmlui.administrative.registries.MoveMetadataField.head1"); + private static final Message T_para1 = + message("xmlui.administrative.registries.MoveMetadataField.para1"); + private static final Message T_column1 = + message("xmlui.administrative.registries.MoveMetadataField.column1"); + private static final Message T_column2 = + message("xmlui.administrative.registries.MoveMetadataField.column2"); + private static final Message T_column3 = + message("xmlui.administrative.registries.MoveMetadataField.column3"); + private static final Message T_para2 = + message("xmlui.administrative.registries.MoveMetadataField.para2"); + private static final Message T_submit_move = + message("xmlui.administrative.registries.MoveMetadataField.submit_move"); + private static final Message T_submit_cancel = + message("xmlui.general.cancel"); - protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); - protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); + protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance().getMetadataSchemaService(); + protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); - - public void addPageMeta(PageMeta pageMeta) throws WingException + + public void addPageMeta(PageMeta pageMeta) throws WingException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/", T_dspace_home); pageMeta.addTrailLink(contextPath + "/admin/metadata-registry",T_metadata_registry_trail); pageMeta.addTrail().addContent(T_trail); } - - - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - // Get all our parameters - List schemas = metadataSchemaService.findAll(context); - String idsString = parameters.getParameter("fieldIDs", null); - - ArrayList fields = new ArrayList(); - for (String id : idsString.split(",")) - { - MetadataField field = metadataFieldService.find(context,Integer.valueOf(id)); - fields.add(field); - } - - - // DIVISION: metadata-field-move - Division moved = body.addInteractiveDivision("metadata-field-move",contextPath+"/admin/metadata-registry",Division.METHOD_POST,"primary administrative metadata-registry"); - moved.setHead(T_head1); - moved.addPara(T_para1); - - Table table = moved.addTable("metadata-field-move",fields.size() + 1, 3); + + + public void addBody(Body body) throws WingException, SQLException, AuthorizeException + { + // Get all our parameters + List schemas = metadataSchemaService.findAll(context); + String idsString = parameters.getParameter("fieldIDs", null); + + ArrayList fields = new ArrayList(); + for (String id : idsString.split(",")) + { + MetadataField field = metadataFieldService.find(context,Integer.valueOf(id)); + fields.add(field); + } + + + // DIVISION: metadata-field-move + Division moved = body.addInteractiveDivision("metadata-field-move", + contextPath + "/admin/metadata-registry", Division.METHOD_POST, + "primary administrative metadata-registry"); + moved.setHead(T_head1); + moved.addPara(T_para1); + + Table table = moved.addTable("metadata-field-move",fields.size() + 1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCell().addContent(T_column1); header.addCell().addContent(T_column2); header.addCell().addContent(T_column3); - - for (MetadataField field : fields) - { - String fieldID = String.valueOf(field.getID()); - String fieldEelement = field.getElement(); - String fieldQualifier = field.getQualifier(); - - MetadataSchema schema = field.getMetadataSchema(); - String schemaName = schema.getName(); - - StringBuilder fieldName = new StringBuilder() - .append(schemaName) - .append(".") - .append(fieldEelement); - if (fieldQualifier != null && fieldQualifier.length() > 0) + for (MetadataField field : fields) + { + String fieldID = String.valueOf(field.getID()); + String fieldEelement = field.getElement(); + String fieldQualifier = field.getQualifier(); + + MetadataSchema schema = field.getMetadataSchema(); + String schemaName = schema.getName(); + + StringBuilder fieldName = new StringBuilder() + .append(schemaName) + .append(".") + .append(fieldEelement); + + if (fieldQualifier != null && fieldQualifier.length() > 0) { - fieldName.append(".").append(fieldQualifier); + fieldName.append(".").append(fieldQualifier); } - - String fieldScopeNote = field.getScopeNote(); - - Row row = table.addRow(); - row.addCell().addContent(fieldID); - row.addCell().addContent(fieldName.toString()); - row.addCell().addContent(fieldScopeNote); - } - Row row = table.addRow(); - Cell cell = row.addCell(1,3); - cell.addContent(T_para2); - Select toSchema = cell.addSelect("to_schema"); - for (MetadataSchema schema : schemas) - { - toSchema.addOption(schema.getID(), schema.getNamespace()); - } - - Para buttons = moved.addPara(); - buttons.addButton("submit_move").setValue(T_submit_move); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); - - - - moved.addHidden("administrative-continue").setValue(knot.getId()); + String fieldScopeNote = field.getScopeNote(); + + Row row = table.addRow(); + row.addCell().addContent(fieldID); + row.addCell().addContent(fieldName.toString()); + row.addCell().addContent(fieldScopeNote); + } + + Row row = table.addRow(); + Cell cell = row.addCell(1,3); + cell.addContent(T_para2); + Select toSchema = cell.addSelect("to_schema"); + for (MetadataSchema schema : schemas) + { + toSchema.addOption(schema.getID(), schema.getNamespace()); + } + + Para buttons = moved.addPara(); + buttons.addButton("submit_move").setValue(T_submit_move); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); + + moved.addHidden("administrative-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CollectionViewer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CollectionViewer.java index e6c26ece01..f858a21276 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CollectionViewer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CollectionViewer.java @@ -33,7 +33,7 @@ import org.xml.sax.SAXException; /** * Display a single collection. This includes a full text search, browse by * list, community display and a list of recent submissions. - * + * * @author Scott Phillips * @author Kevin Van de Velde (kevin at atmire dot com) * @author Mark Diggory (markd at atmire dot com) @@ -45,14 +45,14 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache /** Language Strings */ private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - - public static final Message T_untitled = - message("xmlui.general.untitled"); - + + public static final Message T_untitled = + message("xmlui.general.untitled"); + /** Cached validity object */ private SourceValidity validity; - + /** * Generate the unique caching key. * This key must be unique inside the space of this component. @@ -67,7 +67,7 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache { return "0"; } - + return HashUtil.hash(dso.getHandle()); } catch (SQLException sqle) @@ -80,55 +80,55 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache /** * Generate the cache validity object. - * - * The validity object will include the collection being viewed and + * + * The validity object will include the collection being viewed and * all recently submitted items. This does not include the community / collection * hierarchy, when this changes they will not be reflected in the cache. */ public SourceValidity getValidity() { - if (this.validity == null) - { + if (this.validity == null) + { Collection collection = null; - try - { - DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - - if (dso == null) - { - return null; - } - - if (!(dso instanceof Collection)) - { - return null; - } - - collection = (Collection) dso; - - DSpaceValidity validity = new DSpaceValidity(); - - // Add the actual collection; - validity.add(context, collection); - - this.validity = validity.complete(); - } - catch (Exception e) - { - // Just ignore all errors and return an invalid cache. - } + try + { + DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - } - return this.validity; + if (dso == null) + { + return null; + } + + if (!(dso instanceof Collection)) + { + return null; + } + + collection = (Collection) dso; + + DSpaceValidity validity = new DSpaceValidity(); + + // Add the actual collection; + validity.add(context, collection); + + this.validity = validity.complete(); + } + catch (Exception e) + { + // Just ignore all errors and return an invalid cache. + } + + } + return this.validity; } - - + + /** * Add a page title and trail links. */ - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (!(dso instanceof Collection)) @@ -151,33 +151,35 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache pageMeta.addTrailLink(contextPath + "/",T_dspace_home); HandleUtil.buildHandleTrail(context, collection,pageMeta,contextPath); - + // Add RSS links if available - String[] formats = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("webui.feed.formats"); - if ( formats != null ) - { - for (String format : formats) - { - // Remove the protocol number, i.e. just list 'rss' or' atom' - String[] parts = format.split("_"); - if (parts.length < 1) + String[] formats = DSpaceServicesFactory.getInstance() + .getConfigurationService().getArrayProperty("webui.feed.formats"); + if ( formats != null ) + { + for (String format : formats) + { + // Remove the protocol number, i.e. just list 'rss' or' atom' + String[] parts = format.split("_"); + if (parts.length < 1) { continue; } - - String feedFormat = parts[0].trim()+"+xml"; - - String feedURL = contextPath+"/feed/"+format.trim()+"/"+collection.getHandle(); - pageMeta.addMetadata("feed", feedFormat).addContent(feedURL); - } - } + + String feedFormat = parts[0].trim()+"+xml"; + + String feedURL = contextPath+"/feed/"+format.trim()+"/"+collection.getHandle(); + pageMeta.addMetadata("feed", feedFormat).addContent(feedURL); + } + } } /** * Display a single collection */ - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (!(dso instanceof Collection)) @@ -208,19 +210,19 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache // Add the reference { - Division viewer = home.addDivision("collection-view","secondary"); + Division viewer = home.addDivision("collection-view","secondary"); ReferenceSet mainInclude = viewer.addReferenceSet("collection-view", - ReferenceSet.TYPE_DETAIL_VIEW); + ReferenceSet.TYPE_DETAIL_VIEW); mainInclude.addReference(collection); } } - + /** * Recycle */ - public void recycle() - { + public void recycle() + { // Clear out our item's cache. this.validity = null; super.recycle(); diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityBrowser.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityBrowser.java index 0f01a289f8..c3d13a138a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityBrowser.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityBrowser.java @@ -48,10 +48,10 @@ import org.xml.sax.SAXException; /** * Display a list of Communities and collections. - * + * * This item may be configured so that it will only display up to a specific depth, * and may include or exclude collections from the tree. - * + * *

    The configuration option available: * *

    @@ -67,19 +67,19 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
         /** Language Strings */
         public static final Message T_dspace_home =
             message("xmlui.general.dspace_home");
    -    
    +
         public static final Message T_title =
             message("xmlui.ArtifactBrowser.CommunityBrowser.title");
    -    
    +
         public static final Message T_trail =
             message("xmlui.ArtifactBrowser.CommunityBrowser.trail");
    -    
    +
         public static final Message T_head =
             message("xmlui.ArtifactBrowser.CommunityBrowser.head");
    -    
    +
         public static final Message T_select =
             message("xmlui.ArtifactBrowser.CommunityBrowser.select");
    -    
    +
         /** Should collections be excluded from the list */
         protected boolean excludeCollections = false;
     
    @@ -91,7 +91,7 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
     
         /** Cached version the community / collection hierarchy */
         protected TreeNode root;
    -    
    +
         /** cached validity object */
         private SourceValidity validity;
     
    @@ -111,14 +111,14 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
          */
         @Override
         public void setup(SourceResolver resolver, Map objectModel, String src,
    -            Parameters parameters)
    -            throws ProcessingException, SAXException, IOException
    +        Parameters parameters)
    +        throws ProcessingException, SAXException, IOException
         {
             super.setup(resolver, objectModel, src, parameters);
     
             depth = parameters.getParameterAsInteger("depth", DEFAULT_DEPTH);
             excludeCollections = parameters.getParameterAsBoolean(
    -                "exclude-collections", false);
    +            "exclude-collections", false);
         }
     
         /**
    @@ -129,72 +129,73 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
         @Override
         public Serializable getKey()
         {
    -    	boolean full = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.community-list.render.full", true);
    +        boolean full = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.community-list.render.full", true);
             return HashUtil.hash(depth + "-" + excludeCollections + "-" + (full ? "true" : "false"));
         }
     
         /**
          * Generate the cache validity object.
    -     * 
    -     * The validity object will include a list of all communities 
    +     *
    +     * The validity object will include a list of all communities
          * and collections being browsed along with their logo bitstreams.
          * @return validity.
          */
         @Override
         public SourceValidity getValidity()
         {
    -    	if (validity == null)
    -    	{
    -	        try {
    -	            DSpaceValidity theValidity = new DSpaceValidity();
    -	            
    -	            TreeNode treeRoot = buildTree(communityService.findAllTop(context));
    -	            
    -	            Stack stack = new Stack<>();
    -	            stack.push(treeRoot);
    -	            
    -	            while (!stack.empty())
    -	            {
    -	                TreeNode node = stack.pop();
    -	                
    -	                theValidity.add(context, node.getDSO());
    -	                
    -	                // If we are configured to use collection strengths (i.e. item counts) then include that number in the validity.
    -	                boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    -	                if (showCount)
    -	        		{
    -	                    try
    -	                    {	//try to determine Collection size (i.e. # of items)
    -	                    	
    -	                    	int size = new ItemCounter(context).getCount(node.getDSO());
    -	                    	theValidity.add("size:"+size);
    -	                    }
    -	                    catch(ItemCountException e) { /* ignore */ }
    -	        		}
    -	                
    -	                
    -	                for (TreeNode child : node.getChildren())
    -	                {
    -	                    stack.push(child);
    -	                }
    -	            }
    -	            
    -	            // Check if we are configured to assume validity.
    -	            String assumeCacheValidity = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.community-list.cache");
    -	            if (assumeCacheValidity != null)
    +        if (validity == null)
    +        {
    +            try
    +            {
    +                DSpaceValidity theValidity = new DSpaceValidity();
    +
    +                TreeNode treeRoot = buildTree(communityService.findAllTop(context));
    +
    +                Stack stack = new Stack<>();
    +                stack.push(treeRoot);
    +
    +                while (!stack.empty())
    +                {
    +                    TreeNode node = stack.pop();
    +
    +                    theValidity.add(context, node.getDSO());
    +
    +                    // If we are configured to use collection strengths (i.e. item counts) then include that number in the validity.
    +                    boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    +                    if (showCount)
    +                    {
    +                        try
    +                        {    //try to determine Collection size (i.e. # of items)
    +
    +                            int size = new ItemCounter(context).getCount(node.getDSO());
    +                            theValidity.add("size:"+size);
    +                        }
    +                        catch(ItemCountException e) { /* ignore */ }
    +                    }
    +
    +
    +                    for (TreeNode child : node.getChildren())
    +                    {
    +                        stack.push(child);
    +                    }
    +                }
    +
    +                // Check if we are configured to assume validity.
    +                String assumeCacheValidity = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.community-list.cache");
    +                if (assumeCacheValidity != null)
                     {
                         theValidity.setAssumedValidityDelay(assumeCacheValidity);
                     }
    -	            
    -	            this.validity = theValidity.complete();
    -	        } 
    -	        catch (SQLException sqle) 
    -	        {
    -	            // ignore all errors and return an invalid cache.
    -	        }
    +
    +                this.validity = theValidity.complete();
    +            }
    +            catch (SQLException sqle)
    +            {
    +                // ignore all errors and return an invalid cache.
    +            }
                 log.info(LogManager.getHeader(context, "view_community_list", ""));
    -    	}
    -    	return this.validity;
    +        }
    +        return this.validity;
         }
     
         /**
    @@ -207,9 +208,9 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
          * @throws org.dspace.authorize.AuthorizeException passed through.
          */
         @Override
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
             // Set the page title
             pageMeta.addMetadata("title").addContent(T_title);
    @@ -229,8 +230,9 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
          * @throws org.dspace.authorize.AuthorizeException passed through.
          */
         @Override
    -    public void addBody(Body body) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
             Division division = body.addDivision("comunity-browser", "primary");
             division.setHead(T_head);
    @@ -242,81 +244,83 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
     
             if (full)
             {
    -	        ReferenceSet referenceSet = division.addReferenceSet("community-browser",
    -	                ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
    -	        
    -	        java.util.List rootNodes = treeRoot.getChildrenOfType(Constants.COMMUNITY);
    -	        
    -	        for (TreeNode node : rootNodes)
    -	        {
    -	            buildReferenceSet(referenceSet,node);   
    -	        }
    +            ReferenceSet referenceSet = division.addReferenceSet("community-browser",
    +                ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
    +
    +            java.util.List rootNodes = treeRoot.getChildrenOfType(Constants.COMMUNITY);
    +
    +            for (TreeNode node : rootNodes)
    +            {
    +                buildReferenceSet(referenceSet,node);
    +            }
             }
             else
             {
    -        	List list = division.addList("comunity-browser");
    -        	
    -        	java.util.List rootNodes = treeRoot.getChildrenOfType(Constants.COMMUNITY);
    - 	        
    - 	        for (TreeNode node : rootNodes)
    - 	        {
    - 	            buildList(list,node);   
    - 	        }
    -        	
    +            List list = division.addList("comunity-browser");
    +
    +            java.util.List rootNodes = treeRoot.getChildrenOfType(Constants.COMMUNITY);
    +
    +             for (TreeNode node : rootNodes)
    +             {
    +                 buildList(list,node);
    +             }
    +
             }
    -    } 
    -    
    +    }
    +
         /**
          * Recursively build an includeset of the community / collection hierarchy based upon
          * the given NodeTree.
    -     * 
    +     *
          * @param referenceSet The include set
          * @param node The current node of the hierarchy.
          * @throws org.dspace.app.xmlui.wing.WingException passed through.
          */
    -    public void buildReferenceSet(ReferenceSet referenceSet, TreeNode node) throws WingException
    +    public void buildReferenceSet(ReferenceSet referenceSet, TreeNode node)
    +        throws WingException
         {
             DSpaceObject dso = node.getDSO();
    -        
    +
             Reference objectInclude = referenceSet.addReference(dso);
    -        
    +
             // Add all the sub-collections;
             java.util.List collectionNodes = node.getChildrenOfType(Constants.COLLECTION);
             if (collectionNodes != null && collectionNodes.size() > 0)
             {
                 ReferenceSet collectionSet = objectInclude.addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST);
    -            
    +
                 for (TreeNode collectionNode : collectionNodes)
                 {
                     collectionSet.addReference(collectionNode.getDSO());
                 }
             }
    -        
    +
             // Add all the sub-communities
             java.util.List communityNodes = node.getChildrenOfType(Constants.COMMUNITY);
             if (communityNodes != null && communityNodes.size() > 0)
             {
                 ReferenceSet communitySet = objectInclude.addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST);
    -            
    +
                 for (TreeNode communityNode : communityNodes)
                 {
                     buildReferenceSet(communitySet,communityNode);
                 }
             }
         }
    -    
    +
         /**
          * Recursively build a list of the community / collection hierarchy based upon
          * the given NodeTree.
    -     * 
    +     *
          * @param list The parent list
          * @param node The current node of the hierarchy.
          * @throws org.dspace.app.xmlui.wing.WingException passed through.
          */
    -    public void buildList(List list, TreeNode node) throws WingException
    +    public void buildList(List list, TreeNode node)
    +        throws WingException
         {
             DSpaceObject dso = node.getDSO();
    -        
    +
             String name = null;
             if (dso instanceof Community)
             {
    @@ -326,18 +330,18 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
             {
                 name = ((Collection) dso).getName();
             }
    -        
    +
             String aURL = contextPath + "/handle/"+dso.getHandle();
             list.addItem().addHighlight("bold").addXref(aURL, name);
    -        
    +
             List subList = null;
    -        
    +
             // Add all the sub-collections;
             java.util.List collectionNodes = node.getChildrenOfType(Constants.COLLECTION);
             if (collectionNodes != null && collectionNodes.size() > 0)
             {
    -        	subList = list.addList("sub-list-"+dso.getID());
    -        
    +            subList = list.addList("sub-list-"+dso.getID());
    +
                 for (TreeNode collectionNode : collectionNodes)
                 {
                     String collectionName = ((Collection) collectionNode.getDSO()).getName();
    @@ -350,20 +354,20 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
             java.util.List communityNodes = node.getChildrenOfType(Constants.COMMUNITY);
             if (communityNodes != null && communityNodes.size() > 0)
             {
    -        	if (subList == null)
    +            if (subList == null)
                 {
                     subList = list.addList("sub-list-" + dso.getID());
                 }
    -            
    +
                 for (TreeNode communityNode : communityNodes)
                 {
                     buildList(subList,communityNode);
                 }
             }
         }
    -    
    +
         @Override
    -    public void recycle() 
    +    public void recycle()
         {
             this.root = null;
             this.validity = null;
    @@ -371,19 +375,20 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
         }
     
         /**
    -     * construct a tree structure of communities and collections. The results 
    +     * construct a tree structure of communities and collections. The results
          * of this hierarchy are cached so calling it multiple times is acceptable.
    -     * 
    +     *
          * @param communities The root level communities
          * @return A root level node.
          */
    -    private TreeNode buildTree(java.util.List communities) throws SQLException
    +    private TreeNode buildTree(java.util.List communities)
    +        throws SQLException
         {
             if (root != null)
             {
                 return root;
             }
    -        
    +
             TreeNode newRoot = new TreeNode();
     
             // Setup for breadth-first traversal
    @@ -421,7 +426,7 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
                     }
                 }
             }
    -        
    +
             this.root = newRoot;
             return root;
         }
    @@ -440,8 +445,8 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
             /** All children of this node */
             private final java.util.List children = new ArrayList<>();
     
    -        /** 
    -         * Construct a new root level node 
    +        /**
    +         * Construct a new root level node
              */
             public TreeNode()
             {
    @@ -459,7 +464,7 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
     
             /**
              * Add a child DSpaceObject
    -         * 
    +         *
              * @param dso The child
              * @return A new TreeNode object attached to the tree structure.
              */
    @@ -505,5 +510,4 @@ public class CommunityBrowser extends AbstractDSpaceTransformer implements Cache
                 return results;
             }
         }
    -
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityViewer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityViewer.java
    index 04338729b0..6ff6457b28 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityViewer.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/CommunityViewer.java
    @@ -52,17 +52,16 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
         /** Language Strings */
         private static final Message T_dspace_home =
             message("xmlui.general.dspace_home");
    -    
     
    -    public static final Message T_untitled = 
    -    	message("xmlui.general.untitled");
    +    public static final Message T_untitled =
    +        message("xmlui.general.untitled");
     
         private static final Message T_head_sub_communities =
             message("xmlui.ArtifactBrowser.CommunityViewer.head_sub_communities");
    -    
    +
         private static final Message T_head_sub_collections =
             message("xmlui.ArtifactBrowser.CommunityViewer.head_sub_collections");
    -    
    +
     
         /** Cached validity object */
         private SourceValidity validity;
    @@ -75,16 +74,17 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
          * This key must be unique inside the space of this component.
          */
         public Serializable getKey() {
    -        try {
    +        try
    +        {
                 DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    -            
    +
                 if (dso == null)
                 {
                     return "0";  // no item, something is wrong
                 }
    -            
    +
                 return HashUtil.hash(dso.getHandle());
    -        } 
    +        }
             catch (SQLException sqle)
             {
                 // Ignore all errors and just return that the component is not cachable.
    @@ -94,85 +94,90 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
     
         /**
          * Generate the cache validity object.
    -     * 
    -     * This validity object includes the community being viewed, all 
    -     * sub-communites (one level deep), all sub-collections, and 
    +     *
    +     * This validity object includes the community being viewed, all
    +     * sub-communites (one level deep), all sub-collections, and
          * recently submitted items.
          */
    -    public SourceValidity getValidity() 
    +    public SourceValidity getValidity()
         {
             if (this.validity == null)
    -    	{
    +        {
                 Community community = null;
    -	        try {
    -	            DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    -	            
    -	            if (dso == null)
    +            try {
    +                DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    +
    +                if (dso == null)
                     {
                         return null;
                     }
    -	            
    -	            if (!(dso instanceof Community))
    +
    +                if (!(dso instanceof Community))
                     {
                         return null;
                     }
    -	            
    -	            community = (Community) dso;
    -	            
    -	            DSpaceValidity validity = new DSpaceValidity();
    -	            validity.add(context, community);
    -	            
    -	            List subCommunities = community.getSubcommunities();
    -	            List collections = community.getCollections();
    -	            // Sub communities
    -	            for (Community subCommunity : subCommunities)
    -	            {
    -	                validity.add(context, subCommunity);
    -	                
    -	                // Include the item count in the validity, only if the value is shown.
    -	                boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    -	                if (showCount)
    -	        		{
    -	                    try {	
    -	                    	int size = new ItemCounter(context).getCount(subCommunity);
    -	                    	validity.add("size:"+size);
    -	                    } catch(ItemCountException e) { /* ignore */ }
    -	        		}
    -	            }
    -	            // Sub collections
    -	            for (Collection collection : collections)
    -	            {
    -	                validity.add(context, collection);
    -	                
    -	                // Include the item count in the validity, only if the value is shown.
    -	                boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    -	                if (showCount)
    -	        		{
    -	                    try {
    -	                    	int size = new ItemCounter(context).getCount(collection);
    -	                    	validity.add("size:"+size);
    -	                    } catch(ItemCountException e) { /* ignore */ }
    -	        		}
    -	            }
     
    -	            this.validity = validity.complete();
    -	        } 
    -	        catch (Exception e)
    -	        {
    -	            // Ignore all errors and invalidate the cache.
    -	        }
    +                community = (Community) dso;
     
    -    	}
    +                DSpaceValidity validity = new DSpaceValidity();
    +                validity.add(context, community);
    +
    +                List subCommunities = community.getSubcommunities();
    +                List collections = community.getCollections();
    +                // Sub communities
    +                for (Community subCommunity : subCommunities)
    +                {
    +                    validity.add(context, subCommunity);
    +
    +                    // Include the item count in the validity, only if the value is shown.
    +                    boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    +                    if (showCount)
    +                    {
    +                        try {
    +                            int size = new ItemCounter(context).getCount(subCommunity);
    +                            validity.add("size:"+size);
    +                        } catch(ItemCountException e) { /* ignore */ }
    +                    }
    +                }
    +                // Sub collections
    +                for (Collection collection : collections)
    +                {
    +                    validity.add(context, collection);
    +
    +                    // Include the item count in the validity, only if the value is shown.
    +                    boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    +                    if (showCount)
    +                    {
    +                        try
    +                        {
    +                            int size = new ItemCounter(context).getCount(collection);
    +                            validity.add("size:"+size);
    +                        }
    +                        catch(ItemCountException e)
    +                        {
    +                            /* ignore */
    +                        }
    +                    }
    +                }
    +
    +                this.validity = validity.complete();
    +            }
    +            catch (Exception e)
    +            {
    +                // Ignore all errors and invalidate the cache.
    +            }
    +
    +        }
             return this.validity;
         }
    -    
    -    
    +
    +
         /**
          * Add the community's title and trail links to the page's metadata
          */
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
             DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
             if (!(dso instanceof Community))
    @@ -196,34 +201,36 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
             // Add the trail back to the repository root.
             pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
             HandleUtil.buildHandleTrail(context, community, pageMeta,contextPath);
    -        
    +
             // Add RSS links if available
             String[] formats = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("webui.feed.formats");
    -		if ( formats != null )
    -		{
    -			for (String format : formats)
    -			{
    -				// Remove the protocol number, i.e. just list 'rss' or' atom'
    -				String[] parts = format.split("_");
    -				if (parts.length < 1)
    +        if ( formats != null )
    +        {
    +            for (String format : formats)
    +            {
    +                // Remove the protocol number, i.e. just list 'rss' or' atom'
    +                String[] parts = format.split("_");
    +                if (parts.length < 1)
                     {
                         continue;
                     }
    -				
    -				String feedFormat = parts[0].trim()+"+xml";
    -					
    -				String feedURL = contextPath+"/feed/"+format.trim()+"/"+community.getHandle();
    -				pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    -			}
    -		}
    +
    +                String feedFormat = parts[0].trim()+"+xml";
    +
    +                String feedURL = contextPath+"/feed/"+format.trim()+"/"+community.getHandle();
    +                pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    +            }
    +        }
         }
     
    +
         /**
          * Display a single community (and reference any sub communites or
          * collections)
          */
    -    public void addBody(Body body) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
     
             DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    @@ -257,17 +264,17 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
     
             // Add main reference:
             {
    -        	Division viewer = home.addDivision("community-view","secondary");
    -        	
    +            Division viewer = home.addDivision("community-view","secondary");
    +
                 ReferenceSet referenceSet = viewer.addReferenceSet("community-view",
    -                    ReferenceSet.TYPE_DETAIL_VIEW);
    +                ReferenceSet.TYPE_DETAIL_VIEW);
                 Reference communityInclude = referenceSet.addReference(community);
     
                 // If the community has any children communities also reference them.
                 if (subCommunities != null && subCommunities.size() > 0)
                 {
                     ReferenceSet communityReferenceSet = communityInclude
    -                        .addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
    +                    .addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
     
                     communityReferenceSet.setHead(T_head_sub_communities);
     
    @@ -280,10 +287,9 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
                 if (collections != null && collections.size() > 0)
                 {
                     ReferenceSet communityReferenceSet = communityInclude
    -                        .addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
    +                    .addReferenceSet(ReferenceSet.TYPE_SUMMARY_LIST,null,"hierarchy");
     
                     communityReferenceSet.setHead(T_head_sub_collections);
    -                       
     
                     // Subcollections
                     for (Collection collection : collections)
    @@ -294,7 +300,6 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
                 }
             } // main reference
         }
    -    
     
     
         /**
    @@ -306,6 +311,4 @@ public class CommunityViewer extends AbstractDSpaceTransformer implements Cachea
             this.validity = null;
             super.recycle();
         }
    -
    -
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java
    index 5d91c0c528..d51dbc6af6 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ConfigurableBrowse.java
    @@ -645,7 +645,9 @@ public class ConfigurableBrowse extends AbstractDSpaceTransformer implements
          *
          * @return
          * @throws SQLException
    +     *     An exception that provides information on a database access error or other errors.
          * @throws UIException
    +     *     Error generated by XMLUI.
          */
         private BrowseParams getUserParams() throws SQLException, UIException, ResourceNotFoundException, IllegalArgumentException {
     
    @@ -821,7 +823,9 @@ public class ConfigurableBrowse extends AbstractDSpaceTransformer implements
          *
          * @return
          * @throws SQLException
    +     *     An exception that provides information on a database access error or other errors.
          * @throws UIException
    +     *     Error generated by XMLUI.
          */
         private BrowseInfo getBrowseInfo() throws SQLException, UIException
         {
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FrontPageFeeds.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FrontPageFeeds.java
    index fb1b5deac5..7bdbebd5f8 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FrontPageFeeds.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FrontPageFeeds.java
    @@ -32,16 +32,16 @@ import org.xml.sax.SAXException;
     public class FrontPageFeeds extends AbstractDSpaceTransformer implements CacheableProcessingComponent
     {
         /** Language Strings */
    -    
    +
         public static final Message T_dspace_home =
             message("xmlui.general.dspace_home");
    -	
    -    
    +
    +
         /**
          * Generate the unique caching key.
          * This key must be unique inside the space of this component.
          */
    -    public Serializable getKey() 
    +    public Serializable getKey()
         {
            return "1";
         }
    @@ -49,39 +49,39 @@ public class FrontPageFeeds extends AbstractDSpaceTransformer implements Cacheab
         /**
          * Generate the cache validity object.
          */
    -    public SourceValidity getValidity() 
    +    public SourceValidity getValidity()
         {
             return NOPValidity.SHARED_INSTANCE;
         }
    -    
    +
         /**
          * Add a page title and trail links.
          */
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
    -    	pageMeta.addMetadata("title").addContent(T_dspace_home);
    -    	pageMeta.addTrailLink(contextPath, T_dspace_home);
    -        
    +        pageMeta.addMetadata("title").addContent(T_dspace_home);
    +        pageMeta.addTrailLink(contextPath, T_dspace_home);
    +
             // Add RSS links if available
             String[] formats = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("webui.feed.formats");
    -		if ( formats != null )
    -		{
    -			for (String format : formats)
    -			{
    -				// Remove the protocol number, i.e. just list 'rss' or' atom'
    -				String[] parts = format.split("_");
    -				if (parts.length < 1)
    +        if ( formats != null )
    +        {
    +            for (String format : formats)
    +            {
    +                // Remove the protocol number, i.e. just list 'rss' or' atom'
    +                String[] parts = format.split("_");
    +                if (parts.length < 1)
                     {
                         continue;
                     }
    -				
    -				String feedFormat = parts[0].trim()+"+xml";
    -					
    -				String feedURL = contextPath+"/feed/"+format.trim()+"/site";
    -				pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    -			}
    -		}
    +
    +                String feedFormat = parts[0].trim()+"+xml";
    +
    +                String feedURL = contextPath+"/feed/"+format.trim()+"/site";
    +                pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    +            }
    +        }
         }
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestChangeStatusForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestChangeStatusForm.java
    index a8916d32b8..6774fdb050 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestChangeStatusForm.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestChangeStatusForm.java
    @@ -32,10 +32,10 @@ import org.xml.sax.SAXException;
     
     /**
      * Display to the user a form to request change of permissions of a item.
    - * 
    + *
      * Original Concept, JSPUI version:    Universidade do Minho   at www.uminho.pt
      * Sponsorship of XMLUI version:    Instituto Oceanográfico de España at www.ieo.es
    - * 
    + *
      * @author Adán Román Ruiz at arvo.es (added request item support)
      */
     public class ItemRequestChangeStatusForm extends AbstractDSpaceTransformer implements CacheableProcessingComponent
    @@ -43,40 +43,40 @@ public class ItemRequestChangeStatusForm extends AbstractDSpaceTransformer imple
         /** Language Strings */
         private static final Message T_title =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.title");
    -    
    +
         private static final Message T_dspace_home =
             message("xmlui.general.dspace_home");
    -    
    +
         private static final Message T_trail =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.trail");
    -    
    -    private static final Message T_head = 
    +
    +    private static final Message T_head =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.head");
    -    
    +
         private static final Message T_para1 =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.para1");
    -    
    -    private static final Message T_name = 
    +
    +    private static final Message T_name =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.name");
    -    
    -    private static final Message T_email = 
    +
    +    private static final Message T_email =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.email");
    -    
    -    private static final Message T_name_error = 
    +
    +    private static final Message T_name_error =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.name.error");
    -    
    -    private static final Message T_email_error = 
    +
    +    private static final Message T_email_error =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.email.error");
    -    
    +
         private static final Message T_changeToOpen =
             message("xmlui.ArtifactBrowser.ItemRequestChangeStatusForm.changeToOpen");
    -    
    +
         /**
          * Generate the unique caching key.
          * This key must be unique inside the space of this component.
          */
         public Serializable getKey() {
    -        
    +
             String token = parameters.getParameter("token","");
             String name = parameters.getParameter("name","");
             String email = parameters.getParameter("email","");
    @@ -88,24 +88,25 @@ public class ItemRequestChangeStatusForm extends AbstractDSpaceTransformer imple
         /**
          * Generate the cache validity object.
          */
    -    public SourceValidity getValidity() 
    +    public SourceValidity getValidity()
         {
             return NOPValidity.SHARED_INSTANCE;
         }
    -    
    -    
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    -    {       
    +
    +
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
    +    {
             pageMeta.addMetadata("title").addContent(T_title);
    - 
    +
             pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
             pageMeta.addTrail().addContent(T_trail);
         }
     
    -    public void addBody(Body body) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
     
             Request request = ObjectModelHelper.getRequest(objectModel);
    @@ -114,27 +115,30 @@ public class ItemRequestChangeStatusForm extends AbstractDSpaceTransformer imple
             Division itemRequest = body.addInteractiveDivision("itemRequest-form",
                     request.getRequestURI(),Division.METHOD_POST,"primary");
             itemRequest.setHead(T_head);
    -        
    +
             itemRequest.addPara(T_para1);
    -                
    +
             List form = itemRequest.addList("form",List.TYPE_FORM);
    -        
    +
             Text name = form.addItem().addText("name");
             name.setLabel(T_name);
             name.setValue(parameters.getParameter("name",""));
    -        
    +
             Text mail = form.addItem().addText("email");
             mail.setLabel(T_email);
             mail.setValue(parameters.getParameter("email",""));
    -        
    -        if(request.getParameter("openAccess")!=null){
    -			if(StringUtils.isEmpty(parameters.getParameter("name", ""))){
    -				name.addError(T_name_error);
    -			}
    -			if(StringUtils.isEmpty(parameters.getParameter("email", ""))){
    -				mail.addError(T_email_error);
    -			}
    -		}
    +
    +        if (request.getParameter("openAccess") != null)
    +        {
    +            if (StringUtils.isEmpty(parameters.getParameter("name", "")))
    +            {
    +                name.addError(T_name_error);
    +            }
    +            if (StringUtils.isEmpty(parameters.getParameter("email", "")))
    +            {
    +                mail.addError(T_email_error);
    +            }
    +        }
            // mail.setValue(parameters.getParameter("mail",""));
             form.addItem().addHidden("isSent").setValue("true");
             form.addItem().addButton("openAccess").setValue(T_changeToOpen);
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestForm.java
    index 3105e812e5..ce0a7c5cdc 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestForm.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestForm.java
    @@ -44,10 +44,10 @@ import javax.servlet.http.HttpServletResponse;
     
     /**
      * Display to the user a simple form letting the user to request a protected item.
    - * 
    + *
      * Original Concept, JSPUI version:    Universidade do Minho   at www.uminho.pt
      * Sponsorship of XMLUI version:    Instituto Oceanográfico de España at www.ieo.es
    - * 
    + *
      * @author Adán Román Ruiz at arvo.es (added request item support)
      */
     public class ItemRequestForm extends AbstractDSpaceTransformer implements CacheableProcessingComponent
    @@ -57,16 +57,16 @@ public class ItemRequestForm extends AbstractDSpaceTransformer implements Cachea
         /** Language Strings */
         private static final Message T_title =
             message("xmlui.ArtifactBrowser.ItemRequestForm.title");
    -    
    +
         private static final Message T_dspace_home =
             message("xmlui.general.dspace_home");
    -    
    +
         private static final Message T_trail =
             message("xmlui.ArtifactBrowser.ItemRequestForm.trail");
    -    
    -    private static final Message T_head = 
    +
    +    private static final Message T_head =
             message("xmlui.ArtifactBrowser.ItemRequestForm.head");
    -    
    +
         private static final Message T_para1 =
             message("xmlui.ArtifactBrowser.ItemRequestForm.para1");
     
    @@ -75,53 +75,54 @@ public class ItemRequestForm extends AbstractDSpaceTransformer implements Cachea
     
         private static final Message T_login =
                 message("xmlui.ArtifactBrowser.ItemRequestForm.login");
    -    
    +
         private static final Message T_requesterEmail =
             message("xmlui.ArtifactBrowser.ItemRequestForm.requesterEmail");
     
         private static final Message T_requesterEmail_help =
             message("xmlui.ArtifactBrowser.ItemRequestForm.requesterEmail_help");
    -    
    +
         private static final Message T_requesterEmail_error =
             message("xmlui.ArtifactBrowser.ItemRequestForm.requesterEmail.error");
    -    
    -    private static final Message T_message = 
    +
    +    private static final Message T_message =
             message("xmlui.ArtifactBrowser.ItemRequestForm.message");
    -    
    -    private static final Message T_message_error = 
    +
    +    private static final Message T_message_error =
             message("xmlui.ArtifactBrowser.ItemRequestForm.message.error");
    -    
    -    private static final Message T_requesterName = 
    +
    +    private static final Message T_requesterName =
             message("xmlui.ArtifactBrowser.ItemRequestForm.requesterName");
    -    
    -    private static final Message T_requesterName_error = 
    +
    +    private static final Message T_requesterName_error =
             message("xmlui.ArtifactBrowser.ItemRequestForm.requesterName.error");
    -    
    -    private static final Message T_allFiles = 
    +
    +    private static final Message T_allFiles =
             message("xmlui.ArtifactBrowser.ItemRequestForm.allFiles");
    -    
    -    private static final Message T_files = 
    +
    +    private static final Message T_files =
             message("xmlui.ArtifactBrowser.ItemRequestForm.files");
    -    
    -    private static final Message T_notAllFiles = 
    +
    +    private static final Message T_notAllFiles =
             message("xmlui.ArtifactBrowser.ItemRequestForm.notAllFiles");
    -    
    +
         private static final Message T_submit =
             message("xmlui.ArtifactBrowser.ItemRequestForm.submit");
    -    
    +
         /**
          * Generate the unique caching key.
          * This key must be unique inside the space of this component.
          */
         public Serializable getKey() {
    -    	
    +
             String requesterName = parameters.getParameter("requesterName","");
             String requesterEmail = parameters.getParameter("requesterEmail","");
             String allFiles = parameters.getParameter("allFiles","");
             String message = parameters.getParameter("message","");
             String bitstreamId = parameters.getParameter("bitstreamId","");
    -        
    -       return HashUtil.hash(requesterName + "-" + requesterEmail + "-" + allFiles +"-"+message+"-"+bitstreamId);
    +
    +        return HashUtil.hash(requesterName + "-" + requesterEmail + "-"
    +            + allFiles + "-" + message + "-" + bitstreamId);
         }
     
         protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
    @@ -131,35 +132,37 @@ public class ItemRequestForm extends AbstractDSpaceTransformer implements Cachea
         /**
          * Generate the cache validity object.
          */
    -    public SourceValidity getValidity() 
    +    public SourceValidity getValidity()
         {
             return NOPValidity.SHARED_INSTANCE;
         }
    -    
    -    
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    -    {       
    +
    +
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
    +    {
             pageMeta.addMetadata("title").addContent(T_title);
    - 
    +
             pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
             pageMeta.addTrail().addContent(T_trail);
         }
     
    -	public void addBody(Body body) throws SAXException, WingException,
    -			UIException, SQLException, IOException, AuthorizeException {
    -		
    -		DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    -		if (!(dso instanceof Item)) {
    -			return;
    -		}
    -		Request request = ObjectModelHelper.getRequest(objectModel);
    -		Item item = (Item) dso;
    -		// Build the item viewer division.
    -		Division itemRequest = body.addInteractiveDivision("itemRequest-form",
    -				request.getRequestURI(), Division.METHOD_POST, "primary");
    -		itemRequest.setHead(T_head);
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
    +    {
    +        DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    +        if (!(dso instanceof Item))
    +        {
    +            return;
    +        }
    +        Request request = ObjectModelHelper.getRequest(objectModel);
    +        Item item = (Item) dso;
    +        // Build the item viewer division.
    +        Division itemRequest = body.addInteractiveDivision("itemRequest-form",
    +                request.getRequestURI(), Division.METHOD_POST, "primary");
    +        itemRequest.setHead(T_head);
     
             // add a login link if user !loggedIn
             if (context.getCurrentUser() == null)
    @@ -176,68 +179,81 @@ public class ItemRequestForm extends AbstractDSpaceTransformer implements Cachea
     
                 // Interrupt this request
                 AuthenticationUtil.interruptRequest(objectModel, header, message, characters);
    -        } else {
    +        }
    +        else
    +        {
                 //If user has read permissions to bitstream, redirect them to bitstream, instead of restrict page
    -            try {
    +            try
    +            {
                     UUID bitstreamID = UUID.fromString(parameters.getParameter("bitstreamId"));
                     Bitstream bitstream = bitstreamService.find(context, bitstreamID);
     
    -                if(authorizeService.authorizeActionBoolean(context, bitstream, Constants.READ)) {
    -                    String redirectURL = request.getContextPath() + "/bitstream/handle/" + item.getHandle() + "/"
    -                            + bitstream.getName() + "?sequence=" + bitstream.getSequenceID();
    +                if (authorizeService.authorizeActionBoolean(context, bitstream, Constants.READ))
    +                {
    +                    String redirectURL = request.getContextPath()
    +                        + "/bitstream/handle/" + item.getHandle() + "/"
    +                        + bitstream.getName() + "?sequence=" + bitstream.getSequenceID();
     
                         HttpServletResponse httpResponse = (HttpServletResponse)
    -                            objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
    +                        objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
                         httpResponse.sendRedirect(redirectURL);
                     }
    -            } catch (ParameterException e) {
    +            }
    +            catch (ParameterException e)
    +            {
                     log.error(e.getMessage());
                 }
             }
     
             itemRequest.addPara(T_para1);
     
    -		String titleDC = item.getName();
    -		if (titleDC != null && titleDC.length() > 0)
    -			itemRequest.addPara(titleDC);
    +        String titleDC = item.getName();
    +        if (titleDC != null && titleDC.length() > 0)
    +        {
    +            itemRequest.addPara(titleDC);
    +        }
     
    -		List form = itemRequest.addList("form", List.TYPE_FORM);
    +        List form = itemRequest.addList("form", List.TYPE_FORM);
     
    -		Text requesterName = form.addItem().addText("requesterName");
    -		requesterName.setLabel(T_requesterName);
    -		requesterName.setValue(parameters.getParameter("requesterName", ""));
    +        Text requesterName = form.addItem().addText("requesterName");
    +        requesterName.setLabel(T_requesterName);
    +        requesterName.setValue(parameters.getParameter("requesterName", ""));
     
    -		Text requesterEmail = form.addItem().addText("requesterEmail");
    -		requesterEmail.setLabel(T_requesterEmail);
    -		requesterEmail.setHelp(T_requesterEmail_help);
    -		requesterEmail.setValue(parameters.getParameter("requesterEmail", ""));
    +        Text requesterEmail = form.addItem().addText("requesterEmail");
    +        requesterEmail.setLabel(T_requesterEmail);
    +        requesterEmail.setHelp(T_requesterEmail_help);
    +        requesterEmail.setValue(parameters.getParameter("requesterEmail", ""));
     
    -		Radio radio = form.addItem().addRadio("allFiles");
    -		String selected=!parameters.getParameter("allFiles","true").equalsIgnoreCase("false")?"true":"false";
    -		radio.setOptionSelected(selected);
    -		radio.setLabel(T_files);
    -		radio.addOption("true", T_allFiles);
    -		radio.addOption("false", T_notAllFiles);
    -		
    +        Radio radio = form.addItem().addRadio("allFiles");
    +        String selected=!parameters.getParameter("allFiles","true").equalsIgnoreCase("false")?"true":"false";
    +        radio.setOptionSelected(selected);
    +        radio.setLabel(T_files);
    +        radio.addOption("true", T_allFiles);
    +        radio.addOption("false", T_notAllFiles);
     
    -		TextArea message = form.addItem().addTextArea("message");
    -		message.setLabel(T_message);
    -		message.setValue(parameters.getParameter("message", ""));
    -		form.addItem().addHidden("bitstreamId").setValue(parameters.getParameter("bitstreamId", ""));
    -		form.addItem().addButton("submit").setValue(T_submit);
    -		
    -		// if button is pressed and form is re-loaded it means some parameter is missing
    -		if(request.getParameter("submit")!=null){
    -			if(StringUtils.isEmpty(parameters.getParameter("requesterName", ""))){
    -				requesterName.addError(T_requesterName_error);
    -			}
    -			if(StringUtils.isEmpty(parameters.getParameter("requesterEmail", ""))){
    -				requesterEmail.addError(T_requesterEmail_error);
    -			}
    -			if(StringUtils.isEmpty(parameters.getParameter("message", ""))){
    -				message.addError(T_message_error);
    -			}
    -		}
    -		itemRequest.addHidden("page").setValue(parameters.getParameter("page", "unknown"));
    -	}
    +
    +        TextArea message = form.addItem().addTextArea("message");
    +        message.setLabel(T_message);
    +        message.setValue(parameters.getParameter("message", ""));
    +        form.addItem().addHidden("bitstreamId").setValue(parameters.getParameter("bitstreamId", ""));
    +        form.addItem().addButton("submit").setValue(T_submit);
    +
    +        // if button is pressed and form is re-loaded it means some parameter is missing
    +        if (request.getParameter("submit") != null)
    +        {
    +            if (StringUtils.isEmpty(parameters.getParameter("requesterName", "")))
    +            {
    +                requesterName.addError(T_requesterName_error);
    +            }
    +            if (StringUtils.isEmpty(parameters.getParameter("requesterEmail", "")))
    +            {
    +                requesterEmail.addError(T_requesterEmail_error);
    +            }
    +            if (StringUtils.isEmpty(parameters.getParameter("message", "")))
    +            {
    +                message.addError(T_message_error);
    +            }
    +        }
    +        itemRequest.addHidden("page").setValue(parameters.getParameter("page", "unknown"));
    +    }
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseAction.java
    index c25753258b..6d0af45d97 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseAction.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseAction.java
    @@ -45,10 +45,10 @@ import java.util.Map;
     
     
     /**
    - * 
    + *
      * Original Concept, JSPUI version:    Universidade do Minho   at www.uminho.pt
      * Sponsorship of XMLUI version:    Instituto Oceanográfico de España at www.ieo.es
    - * 
    + *
      * @author Adán Román Ruiz at arvo.es (added request item support)
      */
     public class ItemRequestResponseAction extends AbstractAction
    @@ -58,14 +58,15 @@ public class ItemRequestResponseAction extends AbstractAction
         protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
         protected BitstreamStorageService bitstreamStorageService = StorageServiceFactory.getInstance().getBitstreamStorageService();
     
    -	/** log4j log */
    +    /** log4j log */
         private static Logger log = Logger.getLogger(ItemRequestResponseAction.class);
     
         public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
    -            String source, Parameters parameters) throws Exception
    +        String source, Parameters parameters)
    +        throws Exception
         {
             Request request = ObjectModelHelper.getRequest(objectModel);
    -       
    +
             String token = parameters.getParameter("token","");
             String decision = request.getParameter("decision");
             String isSent = request.getParameter("isSent");
    @@ -80,155 +81,200 @@ public class ItemRequestResponseAction extends AbstractAction
             Item item = requestItem.getItem();
             String titleDC = item.getName();
             if (titleDC != null && titleDC.length() > 0)
    -        	title=titleDC;
    +        {
    +            title = titleDC;
    +        }
             else
    -        	title="untitled";
    -        
    +        {
    +            title = "untitled";
    +        }
    +
             String button="";
             // Buttons on the page
    -        if(request.getParameter("send")!=null){
    -        	decision="true";
    -        	button="send";
    -        } else if(request.getParameter("dontSend")!=null){
    -        	decision="false";
    -        	button="dontSend";
    -        } else if(request.getParameter("contactRequester") !=null) {
    +        if (request.getParameter("send") != null)
    +        {
    +            decision = "true";
    +            button = "send";
    +        }
    +        else if (request.getParameter("dontSend") != null)
    +        {
    +            decision = "false";
    +            button = "dontSend";
    +        }
    +        else if (request.getParameter("contactRequester") != null)
    +        {
                 button = "contactRequester";
    -        } else if (request.getParameter("contactAuthor") != null) {
    +        }
    +        else if (request.getParameter("contactAuthor") != null)
    +        {
                 button = "contactAuthor";
             }
     
    -        if(request.getParameter("mail")!=null){
    -        	button="mail";
    -        }else if(request.getParameter("back")!=null){
    -        	button="back";
    +        if (request.getParameter("mail") != null)
    +        {
    +            button="mail";
             }
    -        if(request.getParameter("openAccess")!=null){
    -        	button="openAccess";
    +        else if (request.getParameter("back") != null)
    +        {
    +            button="back";
             }
    -         
    -        if(button.equals("mail")) {
    +        if (request.getParameter("openAccess") != null)
    +        {
    +            button="openAccess";
    +        }
    +
    +        if (button.equals("mail"))
    +        {
                 //Send mail
    -            if(StringUtils.isNotEmpty(decision) && decision.equals("true")){
    -        	    processSendDocuments(context,request,requestItem,item,title);
    -        	    isSent="true";
    -            } else if(StringUtils.isNotEmpty(decision) && decision.equals("false")) {
    +            if (StringUtils.isNotEmpty(decision) && decision.equals("true"))
    +            {
    +                processSendDocuments(context,request,requestItem,item,title);
    +                isSent="true";
    +            }
    +            else if (StringUtils.isNotEmpty(decision) && decision.equals("false"))
    +            {
                     processDeny(context, request, requestItem, item, title);
                     isSent = "true";
    -            } else if(StringUtils.isNotEmpty(contactPerson) && contactPerson.equals("requester")) {
    +            }
    +            else if (StringUtils.isNotEmpty(contactPerson) && contactPerson.equals("requester"))
    +            {
                     log.info("ContactRequester");
                     processContactRequester(request, requestItem);
                     decision = null;
                     isSent = "notify";
    -            } else if(StringUtils.isNotEmpty(contactPerson) && contactPerson.equals("author")) {
    +            }
    +            else if (StringUtils.isNotEmpty(contactPerson) && contactPerson.equals("author"))
    +            {
                     processContactAuthor(request);
                     decision = null;
                     isSent = "notify";
                 }
    -        } else if(button.equals("openAccess")){
    -        	if(processOpenAccessRequest(context,request,requestItem,item,title)){
    -            	// se acabo el flujo
    -            	return null;
    -        	}
    -        }else if(button.equals("back")){
    -        	decision=null;
    -            contactPerson=null;
    -        } else if(button.equals("contactRequester")) {
    -            decision=null;
    -            isSent=null;
    +        }
    +        else if (button.equals("openAccess"))
    +        {
    +            if (processOpenAccessRequest(context,request,requestItem,item,title))
    +            {
    +                // flow is finished
    +                return null;
    +            }
    +        }
    +        else if (button.equals("back"))
    +        {
    +            decision = null;
    +            contactPerson = null;
    +        }
    +        else if (button.equals("contactRequester"))
    +        {
    +            decision = null;
    +            isSent = null;
                 contactPerson = "requester";
    -        } else if(button.equals("contactAuthor")) {
    -            decision=null;
    -            isSent=null;
    +        }
    +        else if (button.equals("contactAuthor"))
    +        {
    +            decision = null;
    +            isSent = null;
                 contactPerson = "author";
             }
     
    -        
    -		Map map = new HashMap();
    -		map.put("decision", decision);
    -		map.put("token", token);
    -		map.put("isSent", isSent);
    +        Map map = new HashMap();
    +        map.put("decision", decision);
    +        map.put("token", token);
    +        map.put("isSent", isSent);
             map.put("contactPerson", contactPerson);
    -		map.put("title", title);
    -		map.put("name", request.getParameter("name"));
    -		map.put("email",request.getParameter("email"));
    -		return map;
    +        map.put("title", title);
    +        map.put("name", request.getParameter("name"));
    +        map.put("email", request.getParameter("email"));
    +        return map;
         }
     
     
     
    -    private boolean processOpenAccessRequest(Context context,Request request, RequestItem requestItem,Item item,String title) throws SQLException, IOException, MessagingException {
    -    	String name = request.getParameter("name");
    -    	String mail = request.getParameter("email");
    +    private boolean processOpenAccessRequest(Context context,Request request, RequestItem requestItem, Item item, String title)
    +        throws SQLException, IOException, MessagingException
    +    {
    +        String name = request.getParameter("name");
    +        String mail = request.getParameter("email");
     
    -    	if(StringUtils.isNotEmpty(name)&&StringUtils.isNotEmpty(mail)){
    -            RequestItemAuthor requestItemAuthor = DSpaceServicesFactory.getInstance().getServiceManager()
    -                    .getServiceByName(RequestItemAuthorExtractor.class.getName(),
    -                            RequestItemAuthorExtractor.class)
    -                    .getRequestItemAuthor(context, item);
    +        if (StringUtils.isNotEmpty(name)&&StringUtils.isNotEmpty(mail))
    +        {
    +            RequestItemAuthor requestItemAuthor = DSpaceServicesFactory
    +                .getInstance().getServiceManager().getServiceByName(
    +                    RequestItemAuthorExtractor.class.getName(),
    +                    RequestItemAuthorExtractor.class)
    +                        .getRequestItemAuthor(context, item);
     
    -	    	Email email = Email.getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "request_item.admin"));
    -	        email.addRecipient(requestItemAuthor.getEmail());
    -	        
    -	        email.addArgument(requestItem.getBitstream().getName());
    -	        email.addArgument(handleService.getCanonicalForm(item.getHandle()));
    -	        email.addArgument(requestItem.getToken());
    -	        email.addArgument(name);    
    -	        email.addArgument(mail);   
    -	        
    -	        email.send();
    -	        return true;
    -    	}
    -    	return false;
    -	}
    +            Email email = Email.getEmail(I18nUtil.getEmailFilename(
    +                context.getCurrentLocale(), "request_item.admin"));
    +            email.addRecipient(requestItemAuthor.getEmail());
     
    -	private void processSendDocuments(Context context,Request request, RequestItem requestItem,Item item,String title) throws SQLException, MessagingException, IOException {
    -    	String message = request.getParameter("message");
    -    	String subject = request.getParameter("subject");
    -    	
    -    	Email email = new Email();
    +            email.addArgument(requestItem.getBitstream().getName());
    +            email.addArgument(handleService.getCanonicalForm(item.getHandle()));
    +            email.addArgument(requestItem.getToken());
    +            email.addArgument(name);
    +            email.addArgument(mail);
    +
    +            email.send();
    +            return true;
    +        }
    +        return false;
    +    }
    +
    +    private void processSendDocuments(Context context,Request request, RequestItem requestItem,Item item,String title)
    +        throws SQLException, MessagingException, IOException
    +    {
    +        String message = request.getParameter("message");
    +        String subject = request.getParameter("subject");
    +
    +        Email email = new Email();
             email.setSubject(subject);
             email.setContent("{0}");
    -		email.addRecipient(requestItem.getReqEmail());
    +        email.addRecipient(requestItem.getReqEmail());
             email.addArgument(message);
    -       
    -        if (requestItem.isAllfiles()){
    +
    +        if (requestItem.isAllfiles())
    +        {
                 List bundles = itemService.getBundles(item, "ORIGINAL");
                 for (Bundle bundle : bundles) {
                     List bitstreams = bundle.getBitstreams();
    -                for (Bitstream bitstream : bitstreams) {
    -                    if (!bitstream.getFormat(context).isInternal() /*&& RequestItemManager.isRestricted(context, bitstreams[k])*/) {
    +                for (Bitstream bitstream : bitstreams)
    +                {
    +                    if (!bitstream.getFormat(context).isInternal() /*&& RequestItemManager.isRestricted(context, bitstreams[k])*/)
    +                    {
                             email.addAttachment(bitstreamStorageService.retrieve(context, bitstream), bitstream.getName(), bitstream.getFormat(context).getMIMEType());
                         }
                     }
                 }
    -        } else {
    +        }
    +        else
    +        {
                 Bitstream bit = requestItem.getBitstream();
                 email.addAttachment(bitstreamStorageService.retrieve(context, requestItem.getBitstream()), bit.getName(), bit.getFormat(context).getMIMEType());
    -        }     
    -        
    +        }
    +
             email.send();
     
             requestItem.setDecision_date(new Date());
             requestItem.setAccept_request(true);
             requestItemService.update(context, requestItem);
    -	}
    +    }
     
    -	private void processDeny(Context context,Request request, RequestItem requestItem,Item item,String title) throws SQLException, IOException, MessagingException {
    -		String message = request.getParameter("message");
    -    	String subject = request.getParameter("subject");
    -    	        
    -    	Email email = new Email();
    +    private void processDeny(Context context,Request request, RequestItem requestItem,Item item,String title)
    +        throws SQLException, IOException, MessagingException
    +    {
    +        String message = request.getParameter("message");
    +        String subject = request.getParameter("subject");
    +
    +        Email email = new Email();
             email.setSubject(subject);
             email.setContent("{0}");
    -		email.addRecipient(requestItem.getReqEmail());
    +        email.addRecipient(requestItem.getReqEmail());
             email.addArgument(message);
             email.send();
    -        
    +
             requestItem.setDecision_date(new Date());
             requestItem.setAccept_request(false);
             requestItemService.update(context, requestItem);
    -	}
    +    }
     
         /**
          * Send an email back to the requester, letting them know request is being processed.
    @@ -238,7 +284,9 @@ public class ItemRequestResponseAction extends AbstractAction
          * @throws IOException
          * @throws MessagingException
          */
    -    private void processContactRequester(Request request, RequestItem requestItem) throws IOException, MessagingException {
    +    private void processContactRequester(Request request, RequestItem requestItem)
    +        throws IOException, MessagingException
    +    {
             String message = request.getParameter("message");
             String subject = request.getParameter("subject");
     
    @@ -258,7 +306,9 @@ public class ItemRequestResponseAction extends AbstractAction
          * @throws IOException
          * @throws MessagingException
          */
    -    private void processContactAuthor(Request request) throws IOException, MessagingException {
    +    private void processContactAuthor(Request request)
    +        throws IOException, MessagingException
    +    {
             String message = request.getParameter("message");
             String subject = request.getParameter("subject");
     
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseDecisionForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseDecisionForm.java
    index 3f6de6c92e..37549e5e08 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseDecisionForm.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseDecisionForm.java
    @@ -32,26 +32,26 @@ import org.xml.sax.SAXException;
     /**
      * Display to the user a simple decision form to select sending or not a file to
      * requester.
    - * 
    + *
      * Original Concept, JSPUI version:    Universidade do Minho   at www.uminho.pt
      * Sponsorship of XMLUI version:    Instituto Oceanográfico de España at www.ieo.es
    - * 
    + *
      * @author Adán Román Ruiz at arvo.es (added request item support)
      */
     public class ItemRequestResponseDecisionForm extends AbstractDSpaceTransformer
    -		implements CacheableProcessingComponent {
    -	/** Language Strings */
    -	private static final Message T_title = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.title");
    +        implements CacheableProcessingComponent {
    +    /** Language Strings */
    +    private static final Message T_title = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.title");
     
    -	private static final Message T_dspace_home = message("xmlui.general.dspace_home");
    +    private static final Message T_dspace_home = message("xmlui.general.dspace_home");
     
    -	private static final Message T_trail = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.trail");
    +    private static final Message T_trail = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.trail");
     
    -	private static final Message T_head = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.head");
    +    private static final Message T_head = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.head");
     
    -	private static final Message T_para1 = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.para1");
    +    private static final Message T_para1 = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.para1");
     
    -	private static final Message T_para2 = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.para2");
    +    private static final Message T_para2 = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.para2");
     
         private static final Message T_contactRequester = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.contactRequester");
     
    @@ -59,57 +59,62 @@ public class ItemRequestResponseDecisionForm extends AbstractDSpaceTransformer
     
         private static final Message T_send = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.send");
     
    -	private static final Message T_dontSend = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.dontSend");
    +    private static final Message T_dontSend = message("xmlui.ArtifactBrowser.ItemRequestResponseDecisionForm.dontSend");
     
    -	/**
    -	 * Generate the unique caching key. This key must be unique inside the space
    -	 * of this component.
    -	 */
    -	public Serializable getKey() {
    +    /**
    +     * Generate the unique caching key. This key must be unique inside the space
    +     * of this component.
    +     */
    +    public Serializable getKey() {
     
    -		String title = parameters.getParameter("title","");
    -		return HashUtil.hash(title);
    -	}
    +        String title = parameters.getParameter("title","");
    +        return HashUtil.hash(title);
    +    }
     
    -	/**
    -	 * Generate the cache validity object.
    -	 */
    -	public SourceValidity getValidity() {
    -		return NOPValidity.SHARED_INSTANCE;
    -	}
    +    /**
    +     * Generate the cache validity object.
    +     */
    +    public SourceValidity getValidity() {
    +        return NOPValidity.SHARED_INSTANCE;
    +    }
     
    -	public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -			WingException, UIException, SQLException, IOException,
    -			AuthorizeException {
    -		pageMeta.addMetadata("title").addContent(T_title);
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
    +    {
    +        pageMeta.addMetadata("title").addContent(T_title);
     
    -		pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
    -		pageMeta.addTrail().addContent(T_trail);
    -	}
    +        pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
    +        pageMeta.addTrail().addContent(T_trail);
    +    }
     
    -	public void addBody(Body body) throws SAXException, WingException,
    -			UIException, SQLException, IOException, AuthorizeException {
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
    +    {
     
    -		Request request = ObjectModelHelper.getRequest(objectModel);
    -		String title = parameters.getParameter("title","");
    -		// Build the item viewer division.
    -		Division itemRequest = body.addInteractiveDivision("itemRequest-form",
    -				request.getRequestURI(), Division.METHOD_POST, "primary");
    -		itemRequest.setHead(T_head);
    +        Request request = ObjectModelHelper.getRequest(objectModel);
    +        String title = parameters.getParameter("title","");
    +        // Build the item viewer division.
    +        Division itemRequest = body.addInteractiveDivision("itemRequest-form",
    +                request.getRequestURI(), Division.METHOD_POST, "primary");
    +        itemRequest.setHead(T_head);
     
    -		itemRequest.addPara(T_para1.parameterize(title));
    -		itemRequest.addPara(T_para2);
    +        itemRequest.addPara(T_para1.parameterize(title));
    +        itemRequest.addPara(T_para2);
     
    -		List form = itemRequest.addList("form", List.TYPE_FORM);
    +        List form = itemRequest.addList("form", List.TYPE_FORM);
     
    -        boolean helpdeskOverridesSubmitter = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("request.item.helpdesk.override", false);
    -        if(helpdeskOverridesSubmitter) {
    +        boolean helpdeskOverridesSubmitter = DSpaceServicesFactory.getInstance()
    +            .getConfigurationService().getBooleanProperty(
    +            "request.item.helpdesk.override", false);
    +        if (helpdeskOverridesSubmitter)
    +        {
                 form.addItem().addButton("contactRequester").setValue(T_contactRequester);
                 form.addItem().addButton("contactAuthor").setValue(T_contactAuthor);
             }
     
    -		form.addItem().addButton("send").setValue(T_send);
    -		form.addItem().addButton("dontSend").setValue(T_dontSend);
    -
    -	}
    +        form.addItem().addButton("send").setValue(T_send);
    +        form.addItem().addButton("dontSend").setValue(T_dontSend);
    +    }
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseFalseForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseFalseForm.java
    index 4dd7bb0a41..572730aaa8 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseFalseForm.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseFalseForm.java
    @@ -45,40 +45,40 @@ import org.xml.sax.SAXException;
     
     /**
      * Display to the user a simple form to send a message rejecting the file send.
    - * 
    + *
      * Original Concept, JSPUI version:    Universidade do Minho   at www.uminho.pt
      * Sponsorship of XMLUI version:    Instituto Oceanográfico de España at www.ieo.es
    - * 
    + *
      * @author Adán Román Ruiz at arvo.es (added request item support)
      */
     public class ItemRequestResponseFalseForm extends AbstractDSpaceTransformer implements CacheableProcessingComponent
     {
    -	 /** Language Strings */
    +     /** Language Strings */
         private static final Message T_title =
             message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.title");
    -    
    +
         private static final Message T_dspace_home =
             message("xmlui.general.dspace_home");
    -    
    +
         private static final Message T_trail =
             message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.trail");
    -    
    -    private static final Message T_head = 
    +
    +    private static final Message T_head =
             message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.head");
    -    
    +
         private static final Message T_para1 =
             message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.para1");
    -    
    +
         private static final Message T_mail =
             message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.mail");
     
         private static final Message T_back =
             message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.back");
    -    
    -    private static final Message T_message = 
    +
    +    private static final Message T_message =
             message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.message");
    -    
    -    private static final Message T_subject = 
    +
    +    private static final Message T_subject =
                 message("xmlui.ArtifactBrowser.ItemRequestResponseFalseForm.subject");
     
         protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
    @@ -91,71 +91,77 @@ public class ItemRequestResponseFalseForm extends AbstractDSpaceTransformer impl
          */
         public Serializable getKey() {
     
    -		String token = parameters.getParameter("token", "");
    -		String decision = parameters.getParameter("decision", "");
    +        String token = parameters.getParameter("token", "");
    +        String decision = parameters.getParameter("decision", "");
     
    -		return HashUtil.hash(token+"-"+decision);
    +        return HashUtil.hash(token+"-"+decision);
         }
     
         /**
          * Generate the cache validity object.
          */
    -    public SourceValidity getValidity() 
    +    public SourceValidity getValidity()
         {
             return NOPValidity.SHARED_INSTANCE;
         }
    -    
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    -    {       
    +
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
    +    {
             pageMeta.addMetadata("title").addContent(T_title);
    - 
    +
             pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
             pageMeta.addTrail().addContent(T_trail);
         }
     
    -    public void addBody(Body body) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
    -    	Request request = ObjectModelHelper.getRequest(objectModel);
    -    	Context context = ContextUtil.obtainContext(objectModel);
    +        Request request = ObjectModelHelper.getRequest(objectModel);
    +        Context context = ContextUtil.obtainContext(objectModel);
     
             String token = (String) request.getAttribute("token");
             RequestItem requestItem = requestItemService.findByToken(context, token);
     
    -		String title;
    -		Item item = requestItem.getItem();
    -		String titleDC = item.getName();
    -		if (StringUtils.isNotBlank(titleDC))
    -			title = titleDC;
    -		else
    -			title = "untitled";
    -		
    -		RequestItemAuthor author = DSpaceServicesFactory.getInstance().getServiceManager()
    -				.getServiceByName(RequestItemAuthorExtractor.class.getName(),
    -						RequestItemAuthorExtractor.class)
    -				.getRequestItemAuthor(context, item);
    +        String title;
    +        Item item = requestItem.getItem();
    +        String titleDC = item.getName();
    +        if (StringUtils.isNotBlank(titleDC))
    +        {
    +            title = titleDC;
    +        }
    +        else
    +        {
    +            title = "untitled";
    +        }
     
    -		Object[] args = new String[]{
    -					requestItem.getReqName(), // User
    -                    handleService.getCanonicalForm(item.getHandle()), // URL
    -					title, // request item title
    -					author.getFullName(),
    -					author.getEmail()
    -				};
    -		
    -		String subject = I18nUtil.getMessage("itemRequest.response.subject.reject", context);
    -		String messageTemplate = MessageFormat.format(I18nUtil.getMessage("itemRequest.response.body.reject", context), args);        
    +        RequestItemAuthor author = DSpaceServicesFactory.getInstance().getServiceManager()
    +            .getServiceByName(RequestItemAuthorExtractor.class.getName(),
    +                RequestItemAuthorExtractor.class)
    +            .getRequestItemAuthor(context, item);
    +
    +        Object[] args = new String[]{
    +            requestItem.getReqName(), // User
    +            handleService.getCanonicalForm(item.getHandle()), // URL
    +            title, // request item title
    +            author.getFullName(),
    +            author.getEmail()
    +        };
    +
    +        String subject = I18nUtil.getMessage("itemRequest.response.subject.reject", context);
    +        String messageTemplate = MessageFormat.format(I18nUtil.getMessage(
    +            "itemRequest.response.body.reject", context), args);
     
             Division itemRequest = body.addInteractiveDivision("itemRequest-form",
    -                request.getRequestURI(),Division.METHOD_POST,"primary");
    +            request.getRequestURI(),Division.METHOD_POST,"primary");
             itemRequest.setHead(T_head);
    -        
    +
             itemRequest.addPara(T_para1);
    -                
    +
             List form = itemRequest.addList("form",List.TYPE_FORM);
    -        
    +
             Text subj = form.addItem().addText("subject");
             subj.setLabel(T_subject);
             subj.setValue(subject);
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseTrueForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseTrueForm.java
    index 05b1999d57..1e215d6c66 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseTrueForm.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemRequestResponseTrueForm.java
    @@ -44,10 +44,10 @@ import org.xml.sax.SAXException;
     
     /**
      * Display to the user a simple form letting the user send a document with a message.
    - * 
    + *
      * Original Concept, JSPUI version:    Universidade do Minho   at www.uminho.pt
      * Sponsorship of XMLUI version:    Instituto Oceanográfico de España at www.ieo.es
    - * 
    + *
      * @author Adán Román Ruiz at arvo.es (added request item support)
      */
     public class ItemRequestResponseTrueForm extends AbstractDSpaceTransformer implements CacheableProcessingComponent
    @@ -55,29 +55,29 @@ public class ItemRequestResponseTrueForm extends AbstractDSpaceTransformer imple
         /** Language Strings */
         private static final Message T_title =
             message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.title");
    -    
    +
         private static final Message T_dspace_home =
             message("xmlui.general.dspace_home");
    -    
    +
         private static final Message T_trail =
             message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.trail");
    -    
    -    private static final Message T_head = 
    +
    +    private static final Message T_head =
             message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.head");
    -    
    +
         private static final Message T_para1 =
             message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.para1");
    -    
    +
         private static final Message T_mail =
             message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.mail");
     
         private static final Message T_back =
             message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.back");
    -    
    -    private static final Message T_message = 
    +
    +    private static final Message T_message =
             message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.message");
     
    -    private static final Message T_subject = 
    +    private static final Message T_subject =
                 message("xmlui.ArtifactBrowser.ItemRequestResponseTrueForm.subject");
     
         protected RequestItemService requestItemService = RequestItemServiceFactory.getInstance().getRequestItemService();
    @@ -87,69 +87,77 @@ public class ItemRequestResponseTrueForm extends AbstractDSpaceTransformer imple
          * Generate the unique caching key.
          * This key must be unique inside the space of this component.
          */
    -    public Serializable getKey() {      
    -		String token = parameters.getParameter("token", "");
    -		String decision = parameters.getParameter("decision", "");
    +    public Serializable getKey() {
    +        String token = parameters.getParameter("token", "");
    +        String decision = parameters.getParameter("decision", "");
     
    -		return HashUtil.hash(token+"-"+decision);
    +        return HashUtil.hash(token+"-"+decision);
         }
     
         /**
          * Generate the cache validity object.
          */
    -    public SourceValidity getValidity() 
    +    public SourceValidity getValidity()
         {
             return NOPValidity.SHARED_INSTANCE;
         }
    -    
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    +
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException,
                 WingException, UIException, SQLException, IOException,
                 AuthorizeException
    -    {       
    +    {
             pageMeta.addMetadata("title").addContent(T_title);
    - 
    +
             pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
             pageMeta.addTrail().addContent(T_trail);
         }
     
    -    public void addBody(Body body) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
    -    	Request request = ObjectModelHelper.getRequest(objectModel);
    -		Context context = ContextUtil.obtainContext(objectModel);
    +        Request request = ObjectModelHelper.getRequest(objectModel);
    +        Context context = ContextUtil.obtainContext(objectModel);
     
             String token = (String) request.getAttribute("token");
             RequestItem requestItem = requestItemService.findByToken(context, token);
     
    -		String title;
    -		Item item = requestItem.getItem();
    -		String titleDC = item.getName();
    -		if (titleDC != null && titleDC.length() > 0)
    -			title = titleDC;
    -		else
    -			title = "untitled";
    -		
    -		RequestItemAuthor author = DSpaceServicesFactory.getInstance().getServiceManager()
    -				.getServiceByName(RequestItemAuthorExtractor.class.getName(),
    -						RequestItemAuthorExtractor.class)
    -				.getRequestItemAuthor(context, item);
    +        String title;
    +        Item item = requestItem.getItem();
    +        String titleDC = item.getName();
    +        if (titleDC != null && titleDC.length() > 0)
    +        {
    +            title = titleDC;
    +        }
    +        else
    +        {
    +            title = "untitled";
    +        }
     
    -		Object[] args = new String[]{
    -					requestItem.getReqName(), // User
    -                    handleService.getCanonicalForm(item.getHandle()), // URL
    -					title, // request item title
    -					author.getFullName(),
    -					author.getEmail()
    -				};
    -		
    -		String subject = I18nUtil.getMessage("itemRequest.response.subject.approve", context);
    -		String messageTemplate = MessageFormat.format(I18nUtil.getMessage("itemRequest.response.body.approve", context), args);
    -		
    -        Division itemRequest = body.addInteractiveDivision("itemRequest-form", request.getRequestURI(),Division.METHOD_POST,"primary");
    +        RequestItemAuthor author = DSpaceServicesFactory.getInstance().getServiceManager()
    +            .getServiceByName(RequestItemAuthorExtractor.class.getName(),
    +                RequestItemAuthorExtractor.class)
    +            .getRequestItemAuthor(context, item);
    +
    +        Object[] args = new String[]{
    +            requestItem.getReqName(), // User
    +            handleService.getCanonicalForm(item.getHandle()), // URL
    +            title, // request item title
    +            author.getFullName(),
    +            author.getEmail()
    +        };
    +
    +        String subject = I18nUtil.getMessage("itemRequest.response.subject.approve", context);
    +        String messageTemplate = MessageFormat.format(I18nUtil.getMessage(
    +            "itemRequest.response.body.approve", context), args);
    +
    +        Division itemRequest = body.addInteractiveDivision("itemRequest-form",
    +            request.getRequestURI(), Division.METHOD_POST, "primary");
             itemRequest.setHead(T_head);
    -        
    +
             itemRequest.addPara(T_para1);
    -                
    +
             List form = itemRequest.addList("form",List.TYPE_FORM);
             Text subj = form.addItem().addText("subject");
             subj.setLabel(T_subject);
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemViewer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemViewer.java
    index 9736aa0710..d7f46dae1a 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemViewer.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/ItemViewer.java
    @@ -81,14 +81,15 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             message("xmlui.ArtifactBrowser.ItemViewer.head_parent_collections");
     
         private static final Message T_withdrawn = message("xmlui.ArtifactBrowser.ItemViewer.withdrawn");
    -    
    -	/** Cached validity object */
    -	private SourceValidity validity = null;
     
    -	/** XHTML crosswalk instance */
    -	private DisseminationCrosswalk xHTMLHeadCrosswalk = null;
    +    /** Cached validity object */
    +    private SourceValidity validity = null;
     
    -	private final String sfxFile = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir")
    +    /** XHTML crosswalk instance */
    +    private DisseminationCrosswalk xHTMLHeadCrosswalk = null;
    +
    +    private final String sfxFile = DSpaceServicesFactory.getInstance()
    +        .getConfigurationService().getProperty("dspace.dir")
                 + File.separator + "config" + File.separator + "sfx.xml";
     
         private static final Logger log = LoggerFactory.getLogger(ItemViewer.class);
    @@ -132,30 +133,29 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             DSpaceObject dso = null;
     
             if (this.validity == null)
    -    	{
    -	        try {
    -	            dso = HandleUtil.obtainHandle(objectModel);
    +        {
    +            try {
    +                dso = HandleUtil.obtainHandle(objectModel);
     
    -	            DSpaceValidity newValidity = new DSpaceValidity();
    -	            newValidity.add(context, dso);
    -	            this.validity =  newValidity.complete();
    -	        }
    -	        catch (Exception e)
    -	        {
    -	            // Ignore all errors and just invalidate the cache.
    -	        }
    -
    -    	}
    -    	return this.validity;
    +                DSpaceValidity newValidity = new DSpaceValidity();
    +                newValidity.add(context, dso);
    +                this.validity =  newValidity.complete();
    +            }
    +            catch (Exception e)
    +            {
    +                // Ignore all errors and just invalidate the cache.
    +            }
    +        }
    +        return this.validity;
         }
     
         /** Matches Handle System URIs. */
         private static final Pattern handlePattern = Pattern.compile(
    -            "hdl:|https?://hdl\\.handle\\.net/", Pattern.CASE_INSENSITIVE);
    +        "hdl:|https?://hdl\\.handle\\.net/", Pattern.CASE_INSENSITIVE);
     
         /** Matches DOI URIs. */
         private static final Pattern doiPattern = Pattern.compile(
    -            "doi:|https?://(dx\\.)?doi\\.org/", Pattern.CASE_INSENSITIVE);
    +        "doi:|https?://(dx\\.)?doi\\.org/", Pattern.CASE_INSENSITIVE);
     
         /**
          * Add the item's title and trail links to the page's metadata.
    @@ -191,8 +191,8 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
                 pageMeta.addMetadata("title").addContent(item.getHandle());
             }
     
    -        pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
    -        HandleUtil.buildHandleTrail(context, item,pageMeta,contextPath);
    +        pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
    +        HandleUtil.buildHandleTrail(context, item, pageMeta, contextPath);
             pageMeta.addTrail().addContent(T_trail);
     
             // Add SFX link
    @@ -212,7 +212,7 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
                 sfxserverUrl = sfxserverUrl.trim() +"&" + sfxQuery.trim();
                 pageMeta.addMetadata("sfx","server").addContent(sfxserverUrl);
             }
    -        
    +
             // Add persistent identifiers
             /* Temporarily switch to using metadata directly.
              * FIXME Proper fix is to have IdentifierService handle all durable
    @@ -223,15 +223,20 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             {
                 log.debug("Looking up Item {} by IdentifierProvider {}",
                         dso.getID(), idP.getClass().getName());
    -            try {
    +            try
    +            {
                     String id = idP.lookup(context, dso);
                     log.debug("Found identifier {}", id);
                     String idType;
                     String providerName = idP.getClass().getSimpleName().toLowerCase();
                     if (providerName.contains("handle"))
    +                {
                         idType = "handle";
    +                }
                     else if (providerName.contains("doi"))
    +                {
                         idType = "doi";
    +                }
                     else
                     {
                         log.info("Unhandled provider {}", idP.getClass().getName());
    @@ -240,7 +245,9 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
                     log.debug("Adding identifier of type {}", idType);
                     Metadata md = pageMeta.addMetadata("identifier", idType);
                     md.addContent(id);
    -            } catch (IdentifierNotFoundException | IdentifierNotResolvableException ex) {
    +            }
    +            catch (IdentifierNotFoundException | IdentifierNotResolvableException ex)
    +            {
                     continue;
                 }
             }
    @@ -275,7 +282,7 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             String sfxserverImg = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("sfx.server.image_url");
             if (sfxserverImg != null && sfxserverImg.length() > 0)
             {
    -            pageMeta.addMetadata("sfx","image_url").addContent(sfxserverImg);
    +            pageMeta.addMetadata("sfx", "image_url").addContent(sfxserverImg);
             }
     
             boolean googleEnabled = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty(
    @@ -295,8 +302,9 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             // Metadata for  element
             if (xHTMLHeadCrosswalk == null)
             {
    -            xHTMLHeadCrosswalk = (DisseminationCrosswalk) CoreServiceFactory.getInstance().getPluginService().getNamedPlugin(
    -              DisseminationCrosswalk.class, "XHTML_HEAD_ITEM");
    +            xHTMLHeadCrosswalk = (DisseminationCrosswalk) CoreServiceFactory
    +                .getInstance().getPluginService().getNamedPlugin(
    +                    DisseminationCrosswalk.class, "XHTML_HEAD_ITEM");
             }
     
             // Produce  elements for header from crosswalk
    @@ -361,13 +369,14 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             }
     
             // Add Withdrawn Message if it is
    -        if(item.isWithdrawn()){
    +        if (item.isWithdrawn())
    +        {
                 Division div = division.addDivision("notice", "notice");
                 Para p = div.addPara();
                 p.addContent(T_withdrawn);
                 //Set proper response. Return "404 Not Found"
                 HttpServletResponse response = (HttpServletResponse)objectModel
    -                    .get(HttpEnvironment.HTTP_RESPONSE_OBJECT);   
    +                    .get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                 return;
             }
    @@ -399,7 +408,8 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             }
     
             // Reference the actual Item
    -        ReferenceSet appearsInclude = referenceSet.addReference(item).addReferenceSet(ReferenceSet.TYPE_DETAIL_LIST,null,"hierarchy");
    +        ReferenceSet appearsInclude = referenceSet.addReference(item)
    +            .addReferenceSet(ReferenceSet.TYPE_DETAIL_LIST, null, "hierarchy");
             appearsInclude.setHead(T_head_parent_collections);
     
             // Reference all collections the item appears in.
    @@ -408,7 +418,7 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
                 appearsInclude.addReference(collection);
             }
     
    -        showfullPara = division.addPara(null,"item-view-toggle item-view-toggle-bottom");
    +        showfullPara = division.addPara(null, "item-view-toggle item-view-toggle-bottom");
     
             if (showFullItem(objectModel))
             {
    @@ -418,7 +428,7 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
             else
             {
                 String link = contextPath + "/handle/" + item.getHandle()
    -                    + "?show=full";
    +                + "?show=full";
                 showfullPara.addXref(link).addContent(T_show_full);
             }
         }
    @@ -438,7 +448,7 @@ public class ItemViewer extends AbstractDSpaceTransformer implements CacheablePr
     
         @Override
         public void recycle() {
    -    	this.validity = null;
    -    	super.recycle();
    +        this.validity = null;
    +        super.recycle();
         }
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/AbstractRecentSubmissionTransformer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/AbstractRecentSubmissionTransformer.java
    index eb1200d010..94bd001c10 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/AbstractRecentSubmissionTransformer.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/AbstractRecentSubmissionTransformer.java
    @@ -84,34 +84,36 @@ public abstract class AbstractRecentSubmissionTransformer extends AbstractDSpace
          */
         public SourceValidity getValidity()
         {
    -    	if (this.validity == null)
    -    	{
    -	        try
    -	        {
    -	            DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    +        if (this.validity == null)
    +        {
    +            try
    +            {
    +                DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
     
    -	            DSpaceValidity validity = new DSpaceValidity();
    +                DSpaceValidity validity = new DSpaceValidity();
     
    -	            // Add the actual collection;
    -	            validity.add(context, dso);
    +                // Add the actual collection;
    +                validity.add(context, dso);
     
                     getRecentlySubmittedItems(dso);
    -                if(queryResults != null){
    +                if (queryResults != null)
    +                {
                         List resultingObjects = queryResults.getDspaceObjects();
    -                    for(DSpaceObject resultObject : resultingObjects){
    +                    for (DSpaceObject resultObject : resultingObjects)
    +                    {
                             validity.add(context, resultObject);
                         }
                         validity.add("numFound:" + resultingObjects.size());
                     }
     
    -	            this.validity = validity.complete();
    -	        }
    -	        catch (Exception e)
    -	        {
    -	            // Just ignore all errors and return an invalid cache.
    -	        }
    -    	}
    -    	return this.validity;
    +                this.validity = validity.complete();
    +            }
    +            catch (Exception e)
    +            {
    +                // Just ignore all errors and return an invalid cache.
    +            }
    +        }
    +        return this.validity;
         }
     
         /**
    @@ -121,12 +123,13 @@ public abstract class AbstractRecentSubmissionTransformer extends AbstractDSpace
          */
         protected void getRecentlySubmittedItems(DSpaceObject dso) {
     
    -        if(queryResults != null)
    +        if (queryResults != null)
             {
                 return; // queryResults;
             }
     
    -        try {
    +        try
    +        {
                 DiscoverQuery queryArgs = new DiscoverQuery();
     
                 //Add the default filter queries
    @@ -135,12 +138,17 @@ public abstract class AbstractRecentSubmissionTransformer extends AbstractDSpace
                 queryArgs.addFilterQueries(defaultFilterQueries.toArray(new String[defaultFilterQueries.size()]));
                 queryArgs.setDSpaceObjectFilter(Constants.ITEM);
     
    -            DiscoveryRecentSubmissionsConfiguration recentSubmissionConfiguration = discoveryConfiguration.getRecentSubmissionConfiguration();
    -            if(recentSubmissionConfiguration != null){
    +            DiscoveryRecentSubmissionsConfiguration recentSubmissionConfiguration =
    +                discoveryConfiguration.getRecentSubmissionConfiguration();
    +            if (recentSubmissionConfiguration != null)
    +            {
                     maxRecentSubmissions = recentSubmissionConfiguration.getMax();
                     queryArgs.setMaxResults(maxRecentSubmissions);
    -                String sortField = SearchUtils.getSearchService().toSortFieldIndex(recentSubmissionConfiguration.getMetadataSortField(), recentSubmissionConfiguration.getType());
    -                if(sortField != null){
    +                String sortField = SearchUtils.getSearchService().toSortFieldIndex(
    +                    recentSubmissionConfiguration.getMetadataSortField(),
    +                    recentSubmissionConfiguration.getType());
    +                if (sortField != null)
    +                {
                         queryArgs.setSortField(
                                 sortField,
                                 DiscoverQuery.SORT_ORDER.desc
    @@ -148,12 +156,18 @@ public abstract class AbstractRecentSubmissionTransformer extends AbstractDSpace
                     }
                     SearchService service = SearchUtils.getSearchService();
                     queryResults = service.search(context, dso, queryArgs);
    -            }else{
    +            }
    +            else
    +            {
                     //No configuration, no results
                     queryResults = null;
                 }
    -        }catch (SearchServiceException se){
    -            log.error("Caught SearchServiceException while retrieving recent submission for: " + (dso == null ? "home page" : dso.getHandle()), se);
    +        }
    +        catch (SearchServiceException se)
    +        {
    +            log.error(
    +            "Caught SearchServiceException while retrieving recent submission for: "
    +            + (dso == null ? "home page" : dso.getHandle()), se);
             }
         }
     
    @@ -163,9 +177,11 @@ public abstract class AbstractRecentSubmissionTransformer extends AbstractDSpace
          * @param dso the site/community/collection on who's home page we are
          * @throws WingException ...
          */
    -    protected void addViewMoreLink(Division recentSubmissionDiv, DSpaceObject dso) throws WingException {
    +    protected void addViewMoreLink(Division recentSubmissionDiv, DSpaceObject dso)
    +        throws WingException
    +    {
             String url = contextPath;
    -        if(dso != null)
    +        if (dso != null)
             {
                 url += "/handle/" + dso.getHandle();
             }
    @@ -180,5 +196,4 @@ public abstract class AbstractRecentSubmissionTransformer extends AbstractDSpace
             maxRecentSubmissions = 0;
             super.recycle();
         }
    -
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CSVExportDiscoveryNavigation.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CSVExportDiscoveryNavigation.java
    index a2746226ef..2b7d5ad48f 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CSVExportDiscoveryNavigation.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CSVExportDiscoveryNavigation.java
    @@ -38,22 +38,23 @@ import org.apache.log4j.Logger;
     
     public class CSVExportDiscoveryNavigation  extends AbstractDSpaceTransformer implements CacheableProcessingComponent
     {
    -	private static final Logger log = Logger.getLogger(CSVExportDiscoveryNavigation.class);
    -	
    -	private static final Message T_context_head = message("xmlui.administrative.Navigation.context_head");
    -	private static final Message T_export_metadata = message("xmlui.administrative.Navigation.context_search_export_metadata");
    -	
    -	private AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
    -	
    +    private static final Logger log = Logger.getLogger(CSVExportDiscoveryNavigation.class);
    +
    +    private static final Message T_context_head = message("xmlui.administrative.Navigation.context_head");
    +    private static final Message T_export_metadata = message("xmlui.administrative.Navigation.context_search_export_metadata");
    +
    +    private AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
    +
         /**
          * Generate the unique caching key.
          * This key must be unique inside the space of this component.
          */
    -    public Serializable getKey() {
    -	 try {
    +    public Serializable getKey()
    +    {
    +        try {
                 Request request = ObjectModelHelper.getRequest(objectModel);
                 String key = request.getScheme() + request.getServerName() + request.getServerPort() + request.getSitemapURI() + request.getQueryString();
    -            
    +
                 DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
                 if (dso != null)
                 {
    @@ -61,7 +62,7 @@ public class CSVExportDiscoveryNavigation  extends AbstractDSpaceTransformer imp
                 }
     
                 return HashUtil.hash(key);
    -        } 
    +        }
             catch (SQLException sqle)
             {
                 // Ignore all errors and just return that the component is not cachable.
    @@ -71,123 +72,139 @@ public class CSVExportDiscoveryNavigation  extends AbstractDSpaceTransformer imp
     
         /**
          * Generate the cache validity object.
    -     * 
    +     *
          * The cache is always valid.
          */
         public SourceValidity getValidity() {
             return NOPValidity.SHARED_INSTANCE;
         }
    -    
    +
         /**
          * Add the basic navigational options:
    -     * 
    +     *
          * Search - advanced search
    -     * 
    +     *
          * browse - browse by Titles - browse by Authors - browse by Dates
    -     * 
    +     *
          * language FIXME: add languages
    -     * 
    +     *
          * context - export metadata if in discover
    -     * 
    +     *
          * action no action options are added.
          */
    -    public void addOptions(Options options) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addOptions(Options options)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
    -    	Context context = ContextUtil.obtainContext(objectModel);
    -    	Request request = ObjectModelHelper.getRequest(objectModel);
    -    	
    +        Context context = ContextUtil.obtainContext(objectModel);
    +        Request request = ObjectModelHelper.getRequest(objectModel);
    +
             /* regulate the ordering */
             options.addList("discovery");
             options.addList("browse");
             options.addList("account");
             options.addList("administrative");
    -                
    +
             // get uri to see if using discovery and if under a specific handle
             String uri = request.getSitemapURI();
    -        
    +
             // check value in dspace.cfg
             String search_export_config = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.search.metadata_export");
    -        
    +
             // get query
             String query = decodeFromURL(request.getParameter("query"));
    -                
    +
             // get scope, if not under handle returns null
             String scope= request.getParameter("scope");
    -        
    +
             // used to serialize all query filters together
    -    	String filters = "";
    -    	
    -    	// get all query filters
    -    	String[] fqs = DiscoveryUIUtils.getFilterQueries(ObjectModelHelper.getRequest(objectModel), context);
    -        
    -    	if (fqs != null)
    +        String filters = "";
    +
    +        // get all query filters
    +        String[] fqs = DiscoveryUIUtils.getFilterQueries(ObjectModelHelper.getRequest(objectModel), context);
    +
    +        if (fqs != null)
             {
    -        	for(int i = 0; i < fqs.length; i++) {
    -            	if(i < fqs.length - 1)
    -            		filters += fqs[i] + ",";
    -            	else
    -            		filters += fqs[i];
    +            for (int i = 0; i < fqs.length; i++)
    +            {
    +                if (i < fqs.length - 1)
    +                {
    +                    filters += fqs[i] + ",";
    +                }
    +                else
    +                {
    +                    filters += fqs[i];
    +                }
                 }
             }
    -    	
    -    	// check scope
    -    	if(isEmpty(scope)) scope = "/";
    -    	
    -    	// check query
    -    	if(isEmpty(query)) query = "*";
    -    	
    -    	// check if under a handle, already in discovery        	
    -    	if(uri.contains("handle")) {
    -    		scope = uri.replace("handle/", "").replace("/discover", "");
    +
    +        // check scope
    +        if (isEmpty(scope)) scope = "/";
    +
    +        // check query
    +        if (isEmpty(query)) query = "*";
    +
    +        // check if under a handle, already in discovery
    +        if (uri.contains("handle"))
    +        {
    +            scope = uri.replace("handle/", "").replace("/discover", "");
             }
    -    	
    -    	// replace forward slash to make query parameter safe
    -    	try {
    -        	scope = scope.replace("/", "~");
    +
    +        // replace forward slash to make query parameter safe
    +        try {
    +            scope = scope.replace("/", "~");
    +        }
    +        catch (NullPointerException e)
    +        {
    +        }
    +
    +        if (search_export_config != null)
    +        {
    +            // some logging
    +            log.info("uri: " + uri);
    +            log.info("query: " + query);
    +            log.info("scope: " + scope);
    +            log.info("filters: " + filters);
    +
    +            boolean show = false;
    +
    +            if (search_export_config.equals("admin"))
    +            {
    +                if (authorizeService.isAdmin(context))
    +                {
    +                    show = true;
    +                }
    +            }
    +            else if (search_export_config.equals("user") ||
    +                search_export_config.equals("anonymous"))
    +            {
    +                show = true;
    +            }
    +
    +            if (show)
    +            {
    +                List results = options.addList("context");
    +                results.setHead(T_context_head);
    +                String link = contextPath + "/discover/search/csv?query=" + query + "&scope=" + scope;
    +                if (!isEmpty(filters))
    +                {
    +                    link += "&filters=" + filters;
    +                }
    +                results.addItem().addXref(link, T_export_metadata);
    +            }
             }
    -        catch(NullPointerException e) { }
    -    	
    -    	if(search_export_config != null) {
    -    		// some logging    		
    -			log.info("uri: " + uri);
    -			log.info("query: " + query);
    -			log.info("scope: " + scope);
    -			log.info("filters: " + filters);
    -			
    -			boolean show = false;
    -    		        		
    -    		if(search_export_config.equals("admin")) {
    -    			if(authorizeService.isAdmin(context)) {
    -    				show = true;
    -    			}
    -    		}
    -    		else if(search_export_config.equals("user") || search_export_config.equals("anonymous")){
    -    			show = true;
    -    		}
    -    		
    -    		if(show) {
    -    			List results = options.addList("context");    		
    -            	results.setHead(T_context_head);
    -            	String link = contextPath + "/discover/search/csv?query=" + query + "&scope=" + scope;
    -            	if(!isEmpty(filters)) {
    -            		link += "&filters=" + filters;
    -            	}
    -            	results.addItem().addXref(link, T_export_metadata);
    -    		}
    -    	}
         }
    -    
    +
         private boolean isEmpty(String str) {
    -    	return str == null || str.length() == 0;
    +        return str == null || str.length() == 0;
         }
     
         /**
          * Ensure that the context path is added to the page meta.
          */
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
             // Add metadata for quick searches:
             pageMeta.addMetadata("search", "simpleURL").addContent("/discover");
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CollectionSearch.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CollectionSearch.java
    index 2c956a608e..0256d372a0 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CollectionSearch.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CollectionSearch.java
    @@ -47,7 +47,7 @@ public class CollectionSearch extends AbstractDSpaceTransformer implements Cache
             message("xmlui.general.go");
     
         public static final Message T_untitled =
    -    	message("xmlui.general.untitled");
    +        message("xmlui.general.untitled");
     
         /**
          Might implement browse links to activate views into search instead...
    @@ -64,7 +64,7 @@ public class CollectionSearch extends AbstractDSpaceTransformer implements Cache
             message("xmlui.ArtifactBrowser.CollectionViewer.browse_dates");
     
         private static final Message T_advanced_search_link=
    -    	message("xmlui.ArtifactBrowser.CollectionViewer.advanced_search_link");
    +        message("xmlui.ArtifactBrowser.CollectionViewer.advanced_search_link");
         */
     
         /** Cached validity object */
    @@ -104,48 +104,47 @@ public class CollectionSearch extends AbstractDSpaceTransformer implements Cache
          */
         public SourceValidity getValidity()
         {
    -    	if (this.validity == null)
    -    	{
    +        if (this.validity == null)
    +        {
                 Collection collection = null;
    -	        try
    -	        {
    -	            DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    +            try
    +            {
    +                DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
     
    -	            if (dso == null)
    +                if (dso == null)
                     {
                         return null;
                     }
     
    -	            if (!(dso instanceof Collection))
    +                if (!(dso instanceof Collection))
                     {
                         return null;
                     }
     
    -	            collection = (Collection) dso;
    +                collection = (Collection) dso;
     
    -	            DSpaceValidity validity = new DSpaceValidity();
    +                DSpaceValidity validity = new DSpaceValidity();
     
    -	            // Add the actual collection;
    -	            validity.add(context, collection);
    +                // Add the actual collection;
    +                validity.add(context, collection);
     
    -	            this.validity = validity.complete();
    -	        }
    -	        catch (Exception e)
    -	        {
    -	            // Just ignore all errors and return an invalid cache.
    -	        }
    -            
    -    	}
    -    	return this.validity;
    +                this.validity = validity.complete();
    +            }
    +            catch (Exception e)
    +            {
    +                // Just ignore all errors and return an invalid cache.
    +            }
    +        }
    +        return this.validity;
         }
     
     
         /**
          * Add a page title and trail links.
          */
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
             DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
             if (!(dso instanceof Collection))
    @@ -171,30 +170,31 @@ public class CollectionSearch extends AbstractDSpaceTransformer implements Cache
     
             // Add RSS links if available
             String[] formats = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("webui.feed.formats");
    -		if ( formats != null )
    -		{
    -			for (String format : formats)
    -			{
    -				// Remove the protocol number, i.e. just list 'rss' or' atom'
    -				String[] parts = format.split("_");
    -				if (parts.length < 1)
    +        if ( formats != null )
    +        {
    +            for (String format : formats)
    +            {
    +                // Remove the protocol number, i.e. just list 'rss' or' atom'
    +                String[] parts = format.split("_");
    +                if (parts.length < 1)
                     {
                         continue;
                     }
     
    -				String feedFormat = parts[0].trim()+"+xml";
    +                String feedFormat = parts[0].trim()+"+xml";
     
    -				String feedURL = contextPath+"/feed/"+format.trim()+"/"+collection.getHandle();
    -				pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    -			}
    -		}
    +                String feedURL = contextPath+"/feed/"+format.trim()+"/"+collection.getHandle();
    +                pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    +            }
    +        }
         }
     
         /**
          * Display a single collection
          */
    -    public void addBody(Body body) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
             DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
             if (!(dso instanceof Collection))
    @@ -258,4 +258,4 @@ public class CollectionSearch extends AbstractDSpaceTransformer implements Cache
             this.validity = null;
             super.recycle();
         }
    -}
    \ No newline at end of file
    +}
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CommunitySearch.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CommunitySearch.java
    index d7953a93a5..decbb234ac 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CommunitySearch.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/CommunitySearch.java
    @@ -52,7 +52,7 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
             message("xmlui.general.go");
     
         public static final Message T_untitled =
    -    	message("xmlui.general.untitled");
    +        message("xmlui.general.untitled");
     
         private static final Message T_head_sub_collections =
             message("xmlui.ArtifactBrowser.CommunityViewer.head_sub_collections");
    @@ -65,7 +65,8 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
          * This key must be unique inside the space of this component.
          */
         public Serializable getKey() {
    -        try {
    +        try
    +        {
                 DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
     
                 if (dso == null)
    @@ -93,48 +94,50 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
         public SourceValidity getValidity()
         {
             if (this.validity == null)
    -    	{
    +        {
                 Community community = null;
    -	        try {
    -	            DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    +            try
    +            {
    +                DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
     
    -	            if (dso == null)
    +                if (dso == null)
                     {
                         return null;
                     }
     
    -	            if (!(dso instanceof Community))
    +                if (!(dso instanceof Community))
                     {
                         return null;
                     }
     
    -	            community = (Community) dso;
    +                community = (Community) dso;
     
    -	            DSpaceValidity validity = new DSpaceValidity();
    -	            validity.add(context, community);
    +                DSpaceValidity validity = new DSpaceValidity();
    +                validity.add(context, community);
     
    -	            List subCommunities = community.getSubcommunities();
    -	            List collections = community.getCollections();
    -	            // Sub communities
    -	            for (Community subCommunity : subCommunities)
    -	            {
    -	                validity.add(context, subCommunity);
    -	            }
    -	            // Sub collections
    -	            for (Collection collection : collections)
    -	            {
    -	                validity.add(context, collection);
    -	            }
    +                List subCommunities = community.getSubcommunities();
    +                List collections = community.getCollections();
    +                // Sub communities
    +                for (Community subCommunity : subCommunities)
    +                {
    +                    validity.add(context, subCommunity);
    +                }
    +                // Sub collections
    +                for (Collection collection : collections)
    +                {
    +                    validity.add(context, collection);
    +                }
     
    -	            this.validity = validity.complete();
    -	        }
    -	        catch (Exception e)
    -	        {
    -	            // Ignore all errors and invalidate the cache.
    -	        }
    +                this.validity = validity.complete();
    +            }
    +            catch (Exception e)
    +            {
    +                // Ignore all errors and invalidate the cache.
    +            }
     
    -            log.info(LogManager.getHeader(context, "view_community", "community_id=" + (community == null ? "" : community.getID())));
    -    	}
    +            log.info(LogManager.getHeader(context, "view_community",
    +                "community_id=" + (community == null ? "" : community.getID())));
    +        }
             return this.validity;
         }
     
    @@ -142,9 +145,9 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
         /**
          * Add the community's title and trail links to the page's metadata
          */
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
     
         }
    @@ -153,8 +156,9 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
          * Display a single community (and reference any subcommunites or
          * collections)
          */
    -    public void addBody(Body body) throws SAXException, WingException,
    -            UIException, SQLException, IOException, AuthorizeException
    +    public void addBody(Body body)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
     
             DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    @@ -183,12 +187,12 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
     
             {
                 Division search = home.addDivision("community-search-browse",
    -                    "secondary search-browse");
    +                "secondary search-browse");
     
                 // Search query
                 Division query = search.addInteractiveDivision("community-search",
    -                    contextPath + "/handle/" + community.getHandle() + "/discover",
    -                    Division.METHOD_POST, "secondary search");
    +                contextPath + "/handle/" + community.getHandle() + "/discover",
    +                Division.METHOD_POST, "secondary search");
     
                 Para para = query.addPara("search-query", null);
                 para.addContent(T_full_text_search);
    @@ -196,19 +200,18 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
                 para.addText("query");
                 para.addContent(" ");
                 para.addButton("submit").setValue(T_go);
    -           //query.addPara().addXref(contextPath + "/handle/" + community.getHandle() + "/advanced-search", T_advanced_search_link);
    +//            query.addPara().addXref(contextPath + "/handle/" + community.getHandle() + "/advanced-search", T_advanced_search_link);
     
    -            // Browse by list
    -       //     Division browseDiv = search.addDivision("community-browse","secondary browse");
    -         //   List browse = browseDiv.addList("community-browse", List.TYPE_SIMPLE,
    -        //            "community-browse");
    -      //      browse.setHead(T_head_browse);
    -    //        String url = contextPath + "/handle/" + community.getHandle();
    -  //          browse.addItemXref(url + "/browse?type=title",T_browse_titles);
    -  //          browse.addItemXref(url + "/browse?type=author",T_browse_authors);
    +//            Browse by list
    +//            Division browseDiv = search.addDivision("community-browse","secondary browse");
    +//            List browse = browseDiv.addList("community-browse", List.TYPE_SIMPLE,
    +//                "community-browse");
    +//            browse.setHead(T_head_browse);
    +//            String url = contextPath + "/handle/" + community.getHandle();
    +//            browse.addItemXref(url + "/browse?type=title",T_browse_titles);
    +//            browse.addItemXref(url + "/browse?type=author",T_browse_authors);
     //            browse.addItemXref(url + "/browse?type=dateissued",T_browse_dates);
             }
    -
         }
     
         /**
    @@ -220,7 +223,4 @@ public class CommunitySearch extends AbstractDSpaceTransformer implements Cachea
             this.validity = null;
             super.recycle();
         }
    -
    -
    -
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SiteViewer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SiteViewer.java
    index 93f49f40ee..5feb5bada3 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SiteViewer.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/discovery/SiteViewer.java
    @@ -57,31 +57,31 @@ public class SiteViewer extends AbstractDSpaceTransformer implements CacheablePr
         /**
          * Add a page title and trail links.
          */
    -    public void addPageMeta(PageMeta pageMeta) throws SAXException,
    -            WingException, UIException, SQLException, IOException,
    -            AuthorizeException
    +    public void addPageMeta(PageMeta pageMeta)
    +        throws SAXException, WingException, UIException, SQLException,
    +        IOException, AuthorizeException
         {
    -    	pageMeta.addMetadata("title").addContent(T_dspace_home);
    -    	pageMeta.addTrailLink(contextPath, T_dspace_home);
    +        pageMeta.addMetadata("title").addContent(T_dspace_home);
    +        pageMeta.addTrailLink(contextPath, T_dspace_home);
     
             // Add RSS links if available
             String[] formats = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("webui.feed.formats");
    -		if ( formats != null )
    -		{
    -			for (String format : formats)
    -			{
    -				// Remove the protocol number, i.e. just list 'rss' or' atom'
    -				String[] parts = format.split("_");
    -				if (parts.length < 1)
    +        if ( formats != null )
    +        {
    +            for (String format : formats)
    +            {
    +                // Remove the protocol number, i.e. just list 'rss' or' atom'
    +                String[] parts = format.split("_");
    +                if (parts.length < 1)
                     {
                         continue;
                     }
     
    -				String feedFormat = parts[0].trim()+"+xml";
    +                String feedFormat = parts[0].trim() + "+xml";
     
    -				String feedURL = contextPath+"/feed/"+format.trim()+"/site";
    -				pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    -			}
    -		}
    +                String feedURL = contextPath + "/feed/" + format.trim() + "/site";
    +                pageMeta.addMetadata("feed", feedFormat).addContent(feedURL);
    +            }
    +        }
         }
    -}
    \ No newline at end of file
    +}
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticateAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticateAction.java
    index 2f307f9299..498059a290 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticateAction.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticateAction.java
    @@ -27,13 +27,13 @@ import org.dspace.core.Context;
     import org.dspace.eperson.EPerson;
     
     /**
    - * Attempt to authenticate the user based upon their presented credentials. 
    + * Attempt to authenticate the user based upon their presented credentials.
      * This action uses the HTTP parameters of login_email, login_password, and
      * login_realm as credentials.
    - * 
    + *
      * 

    If the authentication attempt is successful then an HTTP redirect will be - * sent to the browser redirecting them to their original location in the - * system before authenticated or if none is supplied back to the DSpace + * sent to the browser redirecting them to their original location in the + * system before authenticated or if none is supplied back to the DSpace * home page. The action will also return true, thus contents of the action will * be executed. * @@ -55,7 +55,7 @@ import org.dspace.eperson.EPerson; public class AuthenticateAction extends AbstractAction { /** - * Attempt to authenticate the user. + * Attempt to authenticate the user. * @param redirector redirector. * @param resolver source resolver. * @param objectModel object model. @@ -66,7 +66,8 @@ public class AuthenticateAction extends AbstractAction */ @Override public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, - String source, Parameters parameters) throws Exception + String source, Parameters parameters) + throws Exception { // First check if we are performing a new login Request request = ObjectModelHelper.getRequest(objectModel); @@ -78,10 +79,10 @@ public class AuthenticateAction extends AbstractAction // Protect against NPE errors inside the authentication // class. if ((email == null) || (password == null)) - { - return null; - } - + { + return null; + } + try { Context context = AuthenticationUtil.authenticate(objectModel, email,password, realm); @@ -90,43 +91,42 @@ public class AuthenticateAction extends AbstractAction if (eperson != null) { - // The user has successfully logged in - String redirectURL = request.getContextPath(); - - if (AuthenticationUtil.isInterupptedRequest(objectModel)) - { - // Resume the request and set the redirect target URL to - // that of the originally interrupted request. - redirectURL += AuthenticationUtil.resumeInterruptedRequest(objectModel); - } - else - { - // Otherwise direct the user to the specified 'loginredirect' page (or homepage by default) - String loginRedirect = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.user.loginredirect"); - redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "/"; - } - + // The user has successfully logged in + String redirectURL = request.getContextPath(); + + if (AuthenticationUtil.isInterupptedRequest(objectModel)) + { + // Resume the request and set the redirect target URL to + // that of the originally interrupted request. + redirectURL += AuthenticationUtil.resumeInterruptedRequest(objectModel); + } + else + { + // Otherwise direct the user to the specified 'loginredirect' page (or homepage by default) + String loginRedirect = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.user.loginredirect"); + redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "/"; + } + // Authentication successful send a redirect. - final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - + final HttpServletResponse httpResponse =(HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + httpResponse.sendRedirect(redirectURL); - + // log the user out for the rest of this current request, however they will be reauthenticated // fully when they come back from the redirect. This prevents caching problems where part of the // request is performed before the user was authenticated and the other half after it succeeded. This // way the user is fully authenticated from the start of the request. context.setCurrentUser(null); - + return new HashMap(); } } catch (SQLException sqle) { throw new PatternException("Unable to perform authentication", - sqle); + sqle); } - + return null; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticationCountSelector.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticationCountSelector.java index ffa3602b24..8b9c650bc6 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticationCountSelector.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/AuthenticationCountSelector.java @@ -24,35 +24,37 @@ import org.dspace.authenticate.factory.AuthenticateServiceFactory; import org.dspace.authenticate.service.AuthenticationService; /** - * Selector will count the number of interactive AuthenticationMethods defined in the + * Selector will count the number of interactive AuthenticationMethods defined in the * dspace configuration file. * @author Jay Paz * @author Scott Phillips * */ -public class AuthenticationCountSelector implements Selector{ +public class AuthenticationCountSelector implements Selector { protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); /** * Returns true if the expression (in this case a number) is equal to the number * of AuthenticationMethods defined in the dspace.cfg file. */ - public boolean select(String expression, Map objectModel, Parameters parameters) { - // get an iterator of all the AuthenticationMethods defined - final Iterator authMethods = authenticationService - .authenticationMethodIterator(); - - final HttpServletResponse httpResponse = (HttpServletResponse) objectModel - .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - final HttpServletRequest httpRequest = (HttpServletRequest) objectModel - .get(HttpEnvironment.HTTP_REQUEST_OBJECT); - - int authMethodCount = 0; - - // iterate to count the methods - while(authMethods.hasNext()){ - AuthenticationMethod auth = authMethods.next(); - try + public boolean select(String expression, Map objectModel, Parameters parameters) + { + // get an iterator of all the AuthenticationMethods defined + final Iterator authMethods = + authenticationService.authenticationMethodIterator(); + + final HttpServletResponse httpResponse = (HttpServletResponse) objectModel + .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + final HttpServletRequest httpRequest = (HttpServletRequest) objectModel + .get(HttpEnvironment.HTTP_REQUEST_OBJECT); + + int authMethodCount = 0; + + // iterate to count the methods + while (authMethods.hasNext()) + { + AuthenticationMethod auth = authMethods.next(); + try { if (auth.loginPageURL( ContextUtil.obtainContext(objectModel), httpRequest, @@ -65,13 +67,10 @@ public class AuthenticationCountSelector implements Selector{ // mmm... we should not never go here, anyway we convert it in an unchecked exception throw new IllegalStateException(e); } - } - - final Integer exp = Integer.valueOf(expression); - - return (authMethodCount == exp); - } - - - + } + + final Integer exp = Integer.valueOf(expression); + + return (authMethodCount == exp); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/EditProfile.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/EditProfile.java index d81da241c2..b09825a952 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/EditProfile.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/EditProfile.java @@ -236,239 +236,239 @@ public class EditProfile extends AbstractDSpaceTransformer } - public void addBody(Body body) throws WingException, SQLException - { - // Log that we are viewing a profile - log.info(LogManager.getHeader(context, "view_profile", "")); - - Request request = ObjectModelHelper.getRequest(objectModel); - - String defaultFirstName="",defaultLastName="",defaultPhone=""; - String defaultLanguage=null; - if (request.getParameter("submit") != null) - { - defaultFirstName = request.getParameter("first_name"); - defaultLastName = request.getParameter("last_name"); - defaultPhone = request.getParameter("phone"); - defaultLanguage = request.getParameter("language"); - } - else if (eperson != null) - { - defaultFirstName = eperson.getFirstName(); - defaultLastName = eperson.getLastName(); - defaultPhone = ePersonService.getMetadata(eperson, "phone"); - defaultLanguage = eperson.getLanguage(); - } - - String action = contextPath; - if (registering) - { - action += "/register"; - } - else - { - action += "/profile"; - } - - - - - Division profile = body.addInteractiveDivision("information", - action,Division.METHOD_POST,"primary"); - - if (registering) - { - profile.setHead(T_head_create); - } - else - { - profile.setHead(T_head_update); - } - - // Add the progress list if we are registering a new user - if (registering) - { - EPersonUtils.registrationProgressList(profile, 2); - } - - - - - - List form = profile.addList("form",List.TYPE_FORM); - - List identity = form.addList("identity",List.TYPE_FORM); - identity.setHead(T_head_identify); - - // Email - identity.addLabel(T_email_address); - identity.addItem(email); - - // First name - Text firstName = identity.addItem().addText("first_name"); - firstName.setAutofocus("autofocus"); - firstName.setRequired(); - firstName.setLabel(T_first_name); - firstName.setValue(defaultFirstName); - if (errors.contains("first_name")) - { - firstName.addError(T_error_required); - } - if (!registering && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) - { - firstName.setDisabled(); - } - - // Last name - Text lastName = identity.addItem().addText("last_name"); - lastName.setRequired(); - lastName.setLabel(T_last_name); - lastName.setValue(defaultLastName); - if (errors.contains("last_name")) - { - lastName.addError(T_error_required); - } - if (!registering &&!DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) - { - lastName.setDisabled(); - } - - // Phone - Text phone = identity.addItem().addText("phone"); - phone.setLabel(T_telephone); - phone.setValue(defaultPhone); - if (errors.contains("phone")) - { - phone.addError(T_error_required); - } - if (!registering && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) - { - phone.setDisabled(); - } + public void addBody(Body body) throws WingException, SQLException + { + // Log that we are viewing a profile + log.info(LogManager.getHeader(context, "view_profile", "")); + + Request request = ObjectModelHelper.getRequest(objectModel); - // Language - Select lang = identity.addItem().addSelect("language"); - lang.setLabel(T_language); - if (supportedLocales.length > 0) - { - for (Locale lc : supportedLocales) - { - lang.addOption(lc.toString(), lc.getDisplayName()); - } - } - else - { - lang.addOption(I18nUtil.DEFAULTLOCALE.toString(), I18nUtil.DEFAULTLOCALE.getDisplayName()); - } - lang.setOptionSelected((defaultLanguage == null || defaultLanguage.equals("")) ? - I18nUtil.DEFAULTLOCALE.toString() : defaultLanguage); - if (!registering && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) - { - lang.setDisabled(); - } - - // Subscriptions - if (!registering) - { - List subscribe = form.addList("subscriptions",List.TYPE_FORM); - subscribe.setHead(T_subscriptions); - - subscribe.addItem(T_subscriptions_help); - - java.util.List currentList = subscribeService.getSubscriptions(context, context.getCurrentUser()); - java.util.List possibleList = collectionService.findAll(context); - - Select subscriptions = subscribe.addItem().addSelect("subscriptions"); - subscriptions.setLabel(T_email_subscriptions); - subscriptions.setHelp(""); - subscriptions.enableAddOperation(); - subscriptions.enableDeleteOperation(); - - subscriptions.addOption(-1,T_select_collection); - CollectionDropDown.CollectionPathEntry[] possibleEntries = CollectionDropDown.annotateWithPaths(context, possibleList); - for (CollectionDropDown.CollectionPathEntry possible : possibleEntries) - { - subscriptions.addOption(possible.collection.getID().toString(), possible.path); - } - - for (Subscription subscription : currentList) { - subscriptions.addInstance().setOptionSelected(subscription.getCollection().getID().toString()); - } - } - - - if (allowSetPassword) - { - List security = form.addList("security",List.TYPE_FORM); - security.setHead(T_head_security); - - if (registering) - { - security.addItem().addContent(T_create_password_instructions); - } - else - { - security.addItem().addContent(T_update_password_instructions); - } - - - Field password = security.addItem().addPassword("password"); - password.setLabel(T_password); - if (registering) - { - password.setRequired(); - } - if (errors.contains("password")) - { - password.addError(T_error_invalid_password); - } - - Field passwordConfirm = security.addItem().addPassword("password_confirm"); - passwordConfirm.setLabel(T_confirm_password); - if (registering) - { - passwordConfirm.setRequired(); - } - if (errors.contains("password_confirm")) - { - passwordConfirm.addError(T_error_unconfirmed_password); - } - } - - Button submit = form.addItem().addButton("submit"); - if (registering) - { - submit.setValue(T_submit_update); - } - else - { - submit.setValue(T_submit_create); - } - - profile.addHidden("eperson-continue").setValue(knot.getId()); - - - - if (!registering) - { - // Add a list of groups that this user is apart of. - java.util.List memberships = groupService.allMemberGroups(context, context.getCurrentUser()); - - - // Not a member of any groups then don't do anything. - if (!(memberships.size() > 0)) - { - return; - } - - List list = profile.addList("memberships"); - list.setHead(T_head_auth); - for (Group group: memberships) - { - list.addItem(group.getName()); - } - } - } + String defaultFirstName="",defaultLastName="",defaultPhone=""; + String defaultLanguage=null; + if (request.getParameter("submit") != null) + { + defaultFirstName = request.getParameter("first_name"); + defaultLastName = request.getParameter("last_name"); + defaultPhone = request.getParameter("phone"); + defaultLanguage = request.getParameter("language"); + } + else if (eperson != null) + { + defaultFirstName = eperson.getFirstName(); + defaultLastName = eperson.getLastName(); + defaultPhone = ePersonService.getMetadata(eperson, "phone"); + defaultLanguage = eperson.getLanguage(); + } + + String action = contextPath; + if (registering) + { + action += "/register"; + } + else + { + action += "/profile"; + } + + + + + Division profile = body.addInteractiveDivision("information", + action,Division.METHOD_POST,"primary"); + + if (registering) + { + profile.setHead(T_head_create); + } + else + { + profile.setHead(T_head_update); + } + + // Add the progress list if we are registering a new user + if (registering) + { + EPersonUtils.registrationProgressList(profile, 2); + } + + + + + + List form = profile.addList("form",List.TYPE_FORM); + + List identity = form.addList("identity",List.TYPE_FORM); + identity.setHead(T_head_identify); + + // Email + identity.addLabel(T_email_address); + identity.addItem(email); + + // First name + Text firstName = identity.addItem().addText("first_name"); + firstName.setAutofocus("autofocus"); + firstName.setRequired(); + firstName.setLabel(T_first_name); + firstName.setValue(defaultFirstName); + if (errors.contains("first_name")) + { + firstName.addError(T_error_required); + } + if (!registering && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) + { + firstName.setDisabled(); + } + + // Last name + Text lastName = identity.addItem().addText("last_name"); + lastName.setRequired(); + lastName.setLabel(T_last_name); + lastName.setValue(defaultLastName); + if (errors.contains("last_name")) + { + lastName.addError(T_error_required); + } + if (!registering &&!DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) + { + lastName.setDisabled(); + } + + // Phone + Text phone = identity.addItem().addText("phone"); + phone.setLabel(T_telephone); + phone.setValue(defaultPhone); + if (errors.contains("phone")) + { + phone.addError(T_error_required); + } + if (!registering && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) + { + phone.setDisabled(); + } + + // Language + Select lang = identity.addItem().addSelect("language"); + lang.setLabel(T_language); + if (supportedLocales.length > 0) + { + for (Locale lc : supportedLocales) + { + lang.addOption(lc.toString(), lc.getDisplayName()); + } + } + else + { + lang.addOption(I18nUtil.DEFAULTLOCALE.toString(), I18nUtil.DEFAULTLOCALE.getDisplayName()); + } + lang.setOptionSelected((defaultLanguage == null || defaultLanguage.equals("")) ? + I18nUtil.DEFAULTLOCALE.toString() : defaultLanguage); + if (!registering && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.editmetadata", true)) + { + lang.setDisabled(); + } + + // Subscriptions + if (!registering) + { + List subscribe = form.addList("subscriptions",List.TYPE_FORM); + subscribe.setHead(T_subscriptions); + + subscribe.addItem(T_subscriptions_help); + + java.util.List currentList = subscribeService.getSubscriptions(context, context.getCurrentUser()); + java.util.List possibleList = collectionService.findAll(context); + + Select subscriptions = subscribe.addItem().addSelect("subscriptions"); + subscriptions.setLabel(T_email_subscriptions); + subscriptions.setHelp(""); + subscriptions.enableAddOperation(); + subscriptions.enableDeleteOperation(); + + subscriptions.addOption(-1,T_select_collection); + CollectionDropDown.CollectionPathEntry[] possibleEntries = CollectionDropDown.annotateWithPaths(context, possibleList); + for (CollectionDropDown.CollectionPathEntry possible : possibleEntries) + { + subscriptions.addOption(possible.collection.getID().toString(), possible.path); + } + + for (Subscription subscription : currentList) { + subscriptions.addInstance().setOptionSelected(subscription.getCollection().getID().toString()); + } + } + + + if (allowSetPassword) + { + List security = form.addList("security",List.TYPE_FORM); + security.setHead(T_head_security); + + if (registering) + { + security.addItem().addContent(T_create_password_instructions); + } + else + { + security.addItem().addContent(T_update_password_instructions); + } + + + Field password = security.addItem().addPassword("password"); + password.setLabel(T_password); + if (registering) + { + password.setRequired(); + } + if (errors.contains("password")) + { + password.addError(T_error_invalid_password); + } + + Field passwordConfirm = security.addItem().addPassword("password_confirm"); + passwordConfirm.setLabel(T_confirm_password); + if (registering) + { + passwordConfirm.setRequired(); + } + if (errors.contains("password_confirm")) + { + passwordConfirm.addError(T_error_unconfirmed_password); + } + } + + Button submit = form.addItem().addButton("submit"); + if (registering) + { + submit.setValue(T_submit_update); + } + else + { + submit.setValue(T_submit_create); + } + + profile.addHidden("eperson-continue").setValue(knot.getId()); + + + + if (!registering) + { + // Add a list of groups that this user is apart of. + java.util.List memberships = groupService.allMemberGroups(context, context.getCurrentUser()); + + + // Not a member of any groups then don't do anything. + if (!(memberships.size() > 0)) + { + return; + } + + List list = profile.addList("memberships"); + list.setHead(T_head_auth); + for (Group group: memberships) + { + list.addItem(group.getName()); + } + } + } /** * Recycle @@ -490,7 +490,7 @@ public class EditProfile extends AbstractDSpaceTransformer private static Locale[] getSupportedLocales() { String[] ll = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("webui.supported.locales"); - if(ll != null && ll.length>0) + if (ll != null && ll.length>0) { return I18nUtil.parseLocales(ll); } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/FailedAuthentication.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/FailedAuthentication.java index 55ae661b50..be27b0f13c 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/FailedAuthentication.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/FailedAuthentication.java @@ -26,46 +26,54 @@ import org.dspace.authorize.AuthorizeException; import org.xml.sax.SAXException; public class FailedAuthentication extends AbstractDSpaceTransformer { - private static final String SESSION_ATTRIBUTE_NAME = "xmlui.Eperson.FailedAuthentication.message"; - - public static final Message BAD_CREDENTIALS = message("xmlui.EPerson.FailedAuthentication.BadCreds"); - public static final Message BAD_ARGUMENTS = message("xmlui.EPerson.FailedAuthentication.BadArgs"); - public static final Message NO_SUCH_USER = message("xmlui.EPerson.FailedAuthentication.NoSuchUser"); - - - /**language strings */ + private static final String SESSION_ATTRIBUTE_NAME = "xmlui.Eperson.FailedAuthentication.message"; + + public static final Message BAD_CREDENTIALS = message("xmlui.EPerson.FailedAuthentication.BadCreds"); + public static final Message BAD_ARGUMENTS = message("xmlui.EPerson.FailedAuthentication.BadArgs"); + public static final Message NO_SUCH_USER = message("xmlui.EPerson.FailedAuthentication.NoSuchUser"); + + + /**language strings */ public static final Message T_title = message("xmlui.EPerson.FailedAuthentication.title"); public static final Message T_dspace_home = message("xmlui.general.dspace_home"); public static final Message T_trail = message("xmlui.EPerson.FailedAuthentication.trail"); - + public static final Message T_h1 = message("xmlui.EPerson.FailedAuthentication.h1"); - - - public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { - Request request = ObjectModelHelper.getRequest(objectModel); - - Division div = body.addDivision("failed_auth"); - div.setHead(T_h1); - div.addPara((Message)request.getSession().getAttribute(SESSION_ATTRIBUTE_NAME)); - deRegisterErrorCode(request); - } - public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { - pageMeta.addMetadata("title").addContent(T_title); + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + Request request = ObjectModelHelper.getRequest(objectModel); + + Division div = body.addDivision("failed_auth"); + div.setHead(T_h1); + div.addPara((Message)request.getSession().getAttribute(SESSION_ATTRIBUTE_NAME)); + deRegisterErrorCode(request); + } + + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/",T_dspace_home); pageMeta.addTrail().addContent(T_trail); - } - - public static void registerErrorCode(Message message, HttpServletRequest request){ - request.getSession().setAttribute(SESSION_ATTRIBUTE_NAME, message); - } - - private static void deRegisterErrorCode(Request request){ - request.getSession().removeAttribute(SESSION_ATTRIBUTE_NAME); - } + } + + public static void registerErrorCode(Message message, HttpServletRequest request) + { + request.getSession().setAttribute(SESSION_ATTRIBUTE_NAME, message); + } + + private static void deRegisterErrorCode(Request request) + { + request.getSession().removeAttribute(SESSION_ATTRIBUTE_NAME); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPAuthenticateAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPAuthenticateAction.java index 58572c2b3d..758282fc78 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPAuthenticateAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPAuthenticateAction.java @@ -30,14 +30,14 @@ import org.dspace.eperson.EPerson; * Attempt to authenticate the user based upon their presented credentials. This * action uses the HTTP parameters of username, ldap_password, and login_realm * as credentials. - * + * *

    If the authentication attempt is successful then an HTTP redirect will be * sent to the browser redirecting them to their original location in the system * before authenticated or if none is supplied back to the DSpace home page. The * action will also return true, thus contents of the action will be executed. - * + * *

    If the authentication attempt fails, the action returns false. - * + * *

    Example use: * *

    @@ -46,14 +46,14 @@ import org.dspace.eperson.EPerson;
      * 
      * }
      * 
    - * + * * @author Jay Paz */ public class LDAPAuthenticateAction extends AbstractAction { - /** - * Attempt to authenticate the user. + /** + * Attempt to authenticate the user. * @param redirector redirector. * @param resolver source resolver. * @param objectModel object model. @@ -62,69 +62,72 @@ public class LDAPAuthenticateAction extends AbstractAction { * @return results of the action. * @throws org.apache.cocoon.sitemap.PatternException if unable to authenticate. * @throws java.lang.Exception passed through. - */ + */ @Override - public Map act(Redirector redirector, SourceResolver resolver, - Map objectModel, String source, Parameters parameters) - throws PatternException, Exception { - // First check if we are performing a new login - Request request = ObjectModelHelper.getRequest(objectModel); + public Map act(Redirector redirector, SourceResolver resolver, + Map objectModel, String source, Parameters parameters) + throws PatternException, Exception + { + // First check if we are performing a new login + Request request = ObjectModelHelper.getRequest(objectModel); - String username = request.getParameter("username"); - String password = request.getParameter("ldap_password"); - String realm = request.getParameter("login_realm"); + String username = request.getParameter("username"); + String password = request.getParameter("ldap_password"); + String realm = request.getParameter("login_realm"); - // Skip out of no name or password given. - if (username == null || password == null) + // Skip out of no name or password given. + if (username == null || password == null) { return null; } - - try { - Context context = AuthenticationUtil.authenticate(objectModel,username, password, realm); - EPerson eperson = context.getCurrentUser(); + try + { + Context context = AuthenticationUtil.authenticate(objectModel,username, password, realm); - if (eperson != null) { - // The user has successfully logged in - String redirectURL = request.getContextPath(); + EPerson eperson = context.getCurrentUser(); - if (AuthenticationUtil.isInterupptedRequest(objectModel)) { - // Resume the request and set the redirect target URL to - // that of the originally interrupted request. - redirectURL += AuthenticationUtil - .resumeInterruptedRequest(objectModel); - } + if (eperson != null) { + // The user has successfully logged in + String redirectURL = request.getContextPath(); + + if (AuthenticationUtil.isInterupptedRequest(objectModel)) { + // Resume the request and set the redirect target URL to + // that of the originally interrupted request. + redirectURL += AuthenticationUtil + .resumeInterruptedRequest(objectModel); + } else { // Otherwise direct the user to the specified 'loginredirect' page (or homepage by default) String loginRedirect = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.user.loginredirect"); - redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "/"; + redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "/"; } - // Authentication successful send a redirect. - final HttpServletResponse httpResponse = (HttpServletResponse) objectModel - .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + // Authentication successful send a redirect. + final HttpServletResponse httpResponse = (HttpServletResponse) objectModel + .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - httpResponse.sendRedirect(redirectURL); + httpResponse.sendRedirect(redirectURL); - // log the user out for the rest of this current request, - // however they will be reauthenticated - // fully when they come back from the redirect. This prevents - // caching problems where part of the - // request is performed fore the user was authenticated and the - // other half after it succeeded. This - // way the user is fully authenticated from the start of the - // request. - context.setCurrentUser(null); + // log the user out for the rest of this current request, + // however they will be reauthenticated + // fully when they come back from the redirect. This prevents + // caching problems where part of the + // request is performed fore the user was authenticated and the + // other half after it succeeded. This + // way the user is fully authenticated from the start of the + // request. + context.setCurrentUser(null); - return new HashMap(); - } - } catch (SQLException sqle) { - throw new PatternException("Unable to perform authentication", sqle); - } - - return null; - } + return new HashMap(); + } + } + catch (SQLException sqle) + { + throw new PatternException("Unable to perform authentication", sqle); + } + return null; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPLogin.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPLogin.java index d43f505e8a..8c440e2bf3 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPLogin.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LDAPLogin.java @@ -32,169 +32,174 @@ import org.xml.sax.SAXException; /** * Query the user for their authentication credentials. - * + * * The parameter "return-url" may be passed to give a location where to redirect * the user to after successfully authenticating. - * + * * @author Jay Paz */ public class LDAPLogin extends AbstractDSpaceTransformer implements - CacheableProcessingComponent { - /** language strings */ - public static final Message T_title = message("xmlui.EPerson.LDAPLogin.title"); + CacheableProcessingComponent { - public static final Message T_dspace_home = message("xmlui.general.dspace_home"); + /** language strings */ + public static final Message T_title = message("xmlui.EPerson.LDAPLogin.title"); - public static final Message T_trail = message("xmlui.EPerson.LDAPLogin.trail"); + public static final Message T_dspace_home = message("xmlui.general.dspace_home"); - public static final Message T_head1 = message("xmlui.EPerson.LDAPLogin.head1"); + public static final Message T_trail = message("xmlui.EPerson.LDAPLogin.trail"); - public static final Message T_userName = message("xmlui.EPerson.LDAPLogin.username"); + public static final Message T_head1 = message("xmlui.EPerson.LDAPLogin.head1"); - public static final Message T_error_bad_login = message("xmlui.EPerson.LDAPLogin.error_bad_login"); + public static final Message T_userName = message("xmlui.EPerson.LDAPLogin.username"); - public static final Message T_password = message("xmlui.EPerson.LDAPLogin.password"); + public static final Message T_error_bad_login = message("xmlui.EPerson.LDAPLogin.error_bad_login"); - public static final Message T_submit = message("xmlui.EPerson.LDAPLogin.submit"); + public static final Message T_password = message("xmlui.EPerson.LDAPLogin.password"); - /** - * Generate the unique caching key. This key must be unique inside the space - * of this component. - */ - public Serializable getKey() { - Request request = ObjectModelHelper.getRequest(objectModel); - String previous_username = request.getParameter("username"); + public static final Message T_submit = message("xmlui.EPerson.LDAPLogin.submit"); - // Get any message parameters - HttpSession session = request.getSession(); - String header = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); - String message = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); - String characters = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); + /** + * Generate the unique caching key. This key must be unique inside the space + * of this component. + */ + public Serializable getKey() { + Request request = ObjectModelHelper.getRequest(objectModel); + String previous_username = request.getParameter("username"); - // If there is a message or previous email attempt then the page is not - // cachable - if (header == null && message == null && characters == null - && previous_username == null) + // Get any message parameters + HttpSession session = request.getSession(); + String header = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); + String message = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); + String characters = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); + + // If there is a message or previous email attempt then the page is not + // cachable + if (header == null && message == null && characters == null && + previous_username == null) { // cacheable return "1"; } - else + else { // Uncachable return "0"; } - } + } - /** - * Generate the cache validity object. - */ - public SourceValidity getValidity() { - Request request = ObjectModelHelper.getRequest(objectModel); - String previous_username = request.getParameter("username"); + /** + * Generate the cache validity object. + */ + public SourceValidity getValidity() { + Request request = ObjectModelHelper.getRequest(objectModel); + String previous_username = request.getParameter("username"); - // Get any message parameters - HttpSession session = request.getSession(); - String header = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); - String message = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); - String characters = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); + // Get any message parameters + HttpSession session = request.getSession(); + String header = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); + String message = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); + String characters = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); - // If there is a message or previous email attempt then the page is not - // cachable - if (header == null && message == null && characters == null - && previous_username == null) + // If there is a message or previous email attempt then the page is not + // cachable + if (header == null && message == null && characters == null && + previous_username == null) { // Always valid return NOPValidity.SHARED_INSTANCE; } - else + else { // invalid return null; } - } + } - /** - * Set the page title and trail. - */ - public void addPageMeta(PageMeta pageMeta) throws WingException { - pageMeta.addMetadata("title").addContent(T_title); + /** + * Set the page title and trail. + */ + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_trail); - } + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_trail); + } - /** - * Display the login form. - */ - public void addBody(Body body) throws SQLException, SAXException, - WingException { - // Check if the user has previously attempted to login. - Request request = ObjectModelHelper.getRequest(objectModel); - HttpSession session = request.getSession(); - String previousUserName = request.getParameter("username"); + /** + * Display the login form. + */ + public void addBody(Body body) + throws SQLException, SAXException, WingException + { + // Check if the user has previously attempted to login. + Request request = ObjectModelHelper.getRequest(objectModel); + HttpSession session = request.getSession(); + String previousUserName = request.getParameter("username"); - // Get any message parameters - String header = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); - String message = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); - String characters = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); + // Get any message parameters + String header = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); + String message = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); + String characters = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); - if (header != null || message != null || characters != null) { - Division reason = body.addDivision("login-reason"); + if (header != null || message != null || characters != null) + { + Division reason = body.addDivision("login-reason"); - if (header != null) + if (header != null) { reason.setHead(message(header)); } - else + else { // Always have a head. reason.setHead("Authentication Required"); } - if (message != null) + if (message != null) { reason.addPara(message(message)); } - if (characters != null) + if (characters != null) { reason.addPara(characters); } - } + } - Division login = body.addInteractiveDivision("login", contextPath - + "/ldap-login", Division.METHOD_POST, "primary"); - login.setHead(T_head1); + Division login = body.addInteractiveDivision("login", contextPath + + "/ldap-login", Division.METHOD_POST, "primary"); + login.setHead(T_head1); - List list = login.addList("ldap-login", List.TYPE_FORM); + List list = login.addList("ldap-login", List.TYPE_FORM); - Text email = list.addItem().addText("username"); - email.setRequired(); + Text email = list.addItem().addText("username"); + email.setRequired(); email.setAutofocus("autofocus"); - email.setLabel(T_userName); - if (previousUserName != null) { - email.setValue(previousUserName); - email.addError(T_error_bad_login); - } + email.setLabel(T_userName); + if (previousUserName != null) + { + email.setValue(previousUserName); + email.addError(T_error_bad_login); + } - Item item = list.addItem(); - Password password = item.addPassword("ldap_password"); - password.setRequired(); - password.setLabel(T_password); + Item item = list.addItem(); + Password password = item.addPassword("ldap_password"); + password.setRequired(); + password.setLabel(T_password); - list.addLabel(); - Item submit = list.addItem("login-in", null); - submit.addButton("submit").setValue(T_submit); - - } + list.addLabel(); + Item submit = list.addItem("login-in", null); + submit.addButton("submit").setValue(T_submit); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginChooser.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginChooser.java index 807b21cff3..8796e14cfe 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginChooser.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginChooser.java @@ -39,157 +39,162 @@ import org.xml.sax.SAXException; /** * Displays a list of authentication methods. This page is displayed if more * than one AuthenticationMethod is defined in the dpace config file. - * + * * @author Jay Paz - * + * */ public class LoginChooser extends AbstractDSpaceTransformer implements - CacheableProcessingComponent { + CacheableProcessingComponent { - public static final Message T_dspace_home = message("xmlui.general.dspace_home"); + public static final Message T_dspace_home = message("xmlui.general.dspace_home"); - public static final Message T_title = message("xmlui.EPerson.LoginChooser.title"); + public static final Message T_title = message("xmlui.EPerson.LoginChooser.title"); - public static final Message T_trail = message("xmlui.EPerson.LoginChooser.trail"); + public static final Message T_trail = message("xmlui.EPerson.LoginChooser.trail"); - public static final Message T_head1 = message("xmlui.EPerson.LoginChooser.head1"); + public static final Message T_head1 = message("xmlui.EPerson.LoginChooser.head1"); - public static final Message T_para1 = message("xmlui.EPerson.LoginChooser.para1"); + public static final Message T_para1 = message("xmlui.EPerson.LoginChooser.para1"); - protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); - /** - * Generate the unique caching key. This key must be unique inside the space - * of this component. - */ - public Serializable getKey() { - Request request = ObjectModelHelper.getRequest(objectModel); - String previous_email = request.getParameter("login_email"); + protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); + /** + * Generate the unique caching key. This key must be unique inside the space + * of this component. + */ + public Serializable getKey() { + Request request = ObjectModelHelper.getRequest(objectModel); + String previous_email = request.getParameter("login_email"); - // Get any message parameters - HttpSession session = request.getSession(); - String header = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); - String message = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); - String characters = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); + // Get any message parameters + HttpSession session = request.getSession(); + String header = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); + String message = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); + String characters = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); - // If there is a message or previous email attempt then the page is not - // cachable - if (header == null && message == null && characters == null - && previous_email == null) + // If there is a message or previous email attempt then the page is not + // cachable + if (header == null && message == null && characters == null + && previous_email == null) { // cacheable return "1"; } - else + else { // Uncachable return "0"; } - } + } - /** - * Generate the cache validity object. - */ - public SourceValidity getValidity() { - Request request = ObjectModelHelper.getRequest(objectModel); - String previous_email = request.getParameter("login_email"); + /** + * Generate the cache validity object. + */ + public SourceValidity getValidity() { + Request request = ObjectModelHelper.getRequest(objectModel); + String previous_email = request.getParameter("login_email"); - // Get any message parameters - HttpSession session = request.getSession(); - String header = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); - String message = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); - String characters = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); + // Get any message parameters + HttpSession session = request.getSession(); + String header = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); + String message = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); + String characters = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); - // If there is a message or previous email attempt then the page is not - // cachable - if (header == null && message == null && characters == null - && previous_email == null) + // If there is a message or previous email attempt then the page is not + // cachable + if (header == null && message == null && characters == null + && previous_email == null) { // Always valid return NOPValidity.SHARED_INSTANCE; } - else + else { // invalid return null; } - } + } - /** - * Set the page title and trail. - */ - public void addPageMeta(PageMeta pageMeta) throws WingException { - pageMeta.addMetadata("title").addContent(T_title); + /** + * Set the page title and trail. + */ + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_trail); - } + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_trail); + } - /** - * Display the login choices. - */ - public void addBody(Body body) throws SQLException, SAXException, - WingException { - Iterator authMethods = authenticationService - .authenticationMethodIterator(); - Request request = ObjectModelHelper.getRequest(objectModel); - HttpSession session = request.getSession(); + /** + * Display the login choices. + */ + public void addBody(Body body) + throws SQLException, SAXException, WingException + { + Iterator authMethods = authenticationService + .authenticationMethodIterator(); + Request request = ObjectModelHelper.getRequest(objectModel); + HttpSession session = request.getSession(); - // Get any message parameters - String header = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); - String message = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); - String characters = (String) session - .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); + // Get any message parameters + String header = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER); + String message = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE); + String characters = (String) session + .getAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS); - if ( (header != null && header.trim().length() > 0) || - (message != null && message.trim().length() > 0) || - (characters != null && characters.trim().length() > 0)) { - Division reason = body.addDivision("login-reason"); + if ( (header != null && header.trim().length() > 0) || + (message != null && message.trim().length() > 0) || + (characters != null && characters.trim().length() > 0)) + { + Division reason = body.addDivision("login-reason"); - if (header != null) - { - reason.setHead(message(header)); - } - else - { - // Always have a head. - reason.setHead("Authentication Required"); - } - - if (message != null) - { - reason.addPara(message(message)); - } - - if (characters != null) - { - reason.addPara(characters); - } - } + if (header != null) + { + reason.setHead(message(header)); + } + else + { + // Always have a head. + reason.setHead("Authentication Required"); + } - Division loginChooser = body.addDivision("login-chooser"); - loginChooser.setHead(T_head1); - loginChooser.addPara().addContent(T_para1); + if (message != null) + { + reason.addPara(message(message)); + } - List list = loginChooser.addList("login-options", List.TYPE_SIMPLE); + if (characters != null) + { + reason.addPara(characters); + } + } - while (authMethods.hasNext()) { - final AuthenticationMethod authMethod = (AuthenticationMethod) authMethods - .next(); + Division loginChooser = body.addDivision("login-chooser"); + loginChooser.setHead(T_head1); + loginChooser.addPara().addContent(T_para1); + + List list = loginChooser.addList("login-options", List.TYPE_SIMPLE); + + while (authMethods.hasNext()) + { + final AuthenticationMethod authMethod = + (AuthenticationMethod) authMethods.next(); HttpServletRequest hreq = (HttpServletRequest) this.objectModel - .get(HttpEnvironment.HTTP_REQUEST_OBJECT); + .get(HttpEnvironment.HTTP_REQUEST_OBJECT); HttpServletResponse hresp = (HttpServletResponse) this.objectModel - .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - + .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + String loginURL = authMethod.loginPageURL(context, hreq, hresp); String authTitle = authMethod.loginPageTitle(context); @@ -197,25 +202,23 @@ public class LoginChooser extends AbstractDSpaceTransformer implements if (loginURL != null && authTitle != null) { - if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.force.ssl") - && !request.isSecure()) + if (DSpaceServicesFactory.getInstance().getConfigurationService() + .getBooleanProperty("xmlui.force.ssl") && !request.isSecure()) { StringBuffer location = new StringBuffer("https://"); location - .append( - DSpaceServicesFactory.getInstance().getConfigurationService() - .getProperty("dspace.hostname")) - .append(loginURL).append( - request.getQueryString() == null ? "" - : ("?" + request.getQueryString())); + .append( + DSpaceServicesFactory.getInstance().getConfigurationService() + .getProperty("dspace.hostname")) + .append(loginURL).append( + request.getQueryString() == null ? "" + : ("?" + request.getQueryString())); loginURL = location.toString(); } final Item item = list.addItem(); item.addXref(loginURL, message(authTitle)); } - - } - } - + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java index b3d472e5a9..8188a681f7 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/LoginRedirect.java @@ -28,71 +28,78 @@ import org.dspace.services.factory.DSpaceServicesFactory; /** * When only one login method is defined in the dspace.cfg file this class will * redirect to the URL provided by that AuthenticationMethod class - * + * * @author Jay Paz * @author Scott Phillips - * + * */ public class LoginRedirect extends AbstractAction { - protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); + protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService(); - public Map act(Redirector redirector, SourceResolver resolver, - Map objectModel, String source, Parameters parameters) - throws Exception { + public Map act(Redirector redirector, SourceResolver resolver, + Map objectModel, String source, Parameters parameters) + throws Exception + { - final HttpServletResponse httpResponse = (HttpServletResponse) objectModel - .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - final HttpServletRequest httpRequest = (HttpServletRequest) objectModel - .get(HttpEnvironment.HTTP_REQUEST_OBJECT); - final Iterator authMethods = authenticationService - .authenticationMethodIterator(); + final HttpServletResponse httpResponse = (HttpServletResponse) objectModel + .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + final HttpServletRequest httpRequest = (HttpServletRequest) objectModel + .get(HttpEnvironment.HTTP_REQUEST_OBJECT); + final Iterator authMethods = authenticationService + .authenticationMethodIterator(); if (authMethods == null) { throw new IllegalStateException( - "No explicit authentication methods found when exactly one was expected."); + "No explicit authentication methods found when exactly one was expected."); } - AuthenticationMethod authMethod = null; + AuthenticationMethod authMethod = null; while (authMethods.hasNext()) { AuthenticationMethod currAuthMethod = authMethods.next(); if (currAuthMethod.loginPageURL(ContextUtil - .obtainContext(objectModel), httpRequest, httpResponse) != null) + .obtainContext(objectModel), httpRequest, httpResponse) != null) { if (authMethod != null) { throw new IllegalStateException( - "Multiple explicit authentication methods found when only one was expected."); + "Multiple explicit authentication methods found when only one was expected."); } authMethod = currAuthMethod; } } final String url = ((AuthenticationMethod) authMethod).loginPageURL( - ContextUtil.obtainContext(objectModel), httpRequest, - httpResponse); + ContextUtil.obtainContext(objectModel), httpRequest, httpResponse); - - // now we want to check for the force ssl property - if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.force.ssl")) { - if (!httpRequest.isSecure()) { - StringBuffer location = new StringBuffer("https://"); - location.append(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.hostname")).append(url).append( - httpRequest.getQueryString() == null ? "" - : ("?" + httpRequest.getQueryString())); - httpResponse.sendRedirect(location.toString()); - } else { - httpResponse.sendRedirect(url); - } - } else { - httpResponse.sendRedirect(url); - } + // now we want to check for the force ssl property + if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.force.ssl")) + { - return new HashMap(); - } + if (!httpRequest.isSecure()) + { + StringBuffer location = new StringBuffer("https://"); + location.append(DSpaceServicesFactory.getInstance() + .getConfigurationService().getProperty("dspace.hostname")).append(url).append( + httpRequest.getQueryString() == null + ? "" + : ("?" + httpRequest.getQueryString())); + httpResponse.sendRedirect(location.toString()); + } + else + { + httpResponse.sendRedirect(url); + } + } + else + { + httpResponse.sendRedirect(url); + } + return new HashMap(); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/Navigation.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/Navigation.java index 49fabc813d..5eb46b695b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/Navigation.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/Navigation.java @@ -37,17 +37,17 @@ import org.xml.sax.SAXException; /** * Add the eperson navigation items to the document. This includes: - * + * * 1) Login and Logout links - * - * 2) Navigational links to register or edit their profile based + * + * 2) Navigational links to register or edit their profile based * upon whether the user is authenticatied or not. - * - * 3) User metadata - * - * 4) The user's language preferences (whether someone is logged + * + * 3) User metadata + * + * 4) The user's language preferences (whether someone is logged * in or not) - * + * * @author Scott Phillips */ @@ -56,21 +56,21 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr /** Language Strings */ private static final Message T_my_account = message("xmlui.EPerson.Navigation.my_account"); - + private static final Message T_profile = message("xmlui.EPerson.Navigation.profile"); - + private static final Message T_logout = message("xmlui.EPerson.Navigation.logout"); - + private static final Message T_login = message("xmlui.EPerson.Navigation.login"); - + private static final Message T_register = message("xmlui.EPerson.Navigation.register"); - /** Cached validity object */ - private SourceValidity validity; + /** Cached validity object */ + private SourceValidity validity; protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); @@ -80,14 +80,14 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr * * @return The generated key hashes the src */ - public Serializable getKey() + public Serializable getKey() { Request request = ObjectModelHelper.getRequest(objectModel); - - // Special case, don't cache anything if the user is logging + + // Special case, don't cache anything if the user is logging // in. The problem occures because of timming, this cache key - // is generated before we know whether the operation has - // succeeded or failed. So we don't know whether to cache this + // is generated before we know whether the operation has + // succeeded or failed. So we don't know whether to cache this // under the user's specific cache or under the anonymous user. if (request.getParameter("login_email") != null || request.getParameter("login_password") != null || @@ -95,7 +95,7 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr { return null; } - + // FIXME: // Do not cache the home page. There is a bug that is causing the // homepage to be cached with user's data after a logout. This @@ -103,10 +103,10 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr // cache this page. if (request.getSitemapURI().length() == 0) { - return null; + return null; } - - StringBuilder key; + + StringBuilder key; if (context.getCurrentUser() != null) { key = new StringBuilder(context.getCurrentUser().getEmail()); @@ -115,7 +115,7 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr { key = new StringBuilder("anonymous"); } - + // Add the user's language Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) @@ -123,7 +123,7 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr Locale locale = (Locale) locales.nextElement(); key.append("-").append(locale.toString()); } - + return HashUtil.hash(key.toString()); } @@ -133,65 +133,68 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr * @return The generated validity object or null if the * component is currently not cacheable. */ - public SourceValidity getValidity() + public SourceValidity getValidity() { - if (this.validity == null) - { - // Only use the DSpaceValidity object is someone is logged in. - if (context.getCurrentUser() != null) - { - try { - DSpaceValidity validity = new DSpaceValidity(); - - validity.add(context, eperson); - - java.util.List groups = groupService.allMemberGroups(context, eperson); - for (Group group : groups) - { - validity.add(context, group); - } - - this.validity = validity.complete(); - } - catch (SQLException sqle) - { - // Just ignore it and return invalid. - } - } - else - { - this.validity = NOPValidity.SHARED_INSTANCE; - } - } - return this.validity; + if (this.validity == null) + { + // Only use the DSpaceValidity object is someone is logged in. + if (context.getCurrentUser() != null) + { + try + { + DSpaceValidity validity = new DSpaceValidity(); + + validity.add(context, eperson); + + java.util.List groups = groupService.allMemberGroups(context, eperson); + for (Group group : groups) + { + validity.add(context, group); + } + + this.validity = validity.complete(); + } + catch (SQLException sqle) + { + // Just ignore it and return invalid. + } + } + else + { + this.validity = NOPValidity.SHARED_INSTANCE; + } + } + return this.validity; } - + /** * Add the eperson aspect navigational options. */ - public void addOptions(Options options) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addOptions(Options options) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - /* Create skeleton menu structure to ensure consistent order between aspects, - * even if they are never used - */ + /* Create skeleton menu structure to ensure consistent order between aspects, + * even if they are never used + */ options.addList("browse"); List account = options.addList("account"); options.addList("context"); options.addList("administrative"); - + account.setHead(T_my_account); EPerson eperson = this.context.getCurrentUser(); if (eperson != null) { String fullName = eperson.getFullName(); - account.addItemXref(contextPath+"/logout",T_logout); - account.addItemXref(contextPath+"/profile",T_profile.parameterize(fullName)); - } - else + account.addItemXref(contextPath+"/logout", T_logout); + account.addItemXref(contextPath+"/profile", T_profile.parameterize(fullName)); + } + else { - account.addItemXref(contextPath+"/login",T_login); - if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.user.registration", true)) + account.addItemXref(contextPath+"/login", T_login); + if (DSpaceServicesFactory.getInstance().getConfigurationService() + .getBooleanProperty("xmlui.user.registration", true)) { account.addItemXref(contextPath + "/register", T_register); } @@ -201,9 +204,9 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr /** * Add the user metadata */ - public void addUserMeta(UserMeta userMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public void addUserMeta(UserMeta userMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { EPerson eperson = context.getCurrentUser(); if (eperson != null) @@ -223,17 +226,17 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr // Always have a login URL. userMeta.addMetadata("identifier","loginURL").addContent(contextPath+"/login"); - + // Always add language information Request request = ObjectModelHelper.getRequest(objectModel); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); - userMeta.addMetadata("language","RFC3066").addContent(locale.toString()); + userMeta.addMetadata("language","RFC3066").addContent(locale.toString()); } } - + /** * recycle */ @@ -242,5 +245,4 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr this.validity = null; super.recycle(); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/ShibbolethAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/ShibbolethAction.java index 81fbec4a8e..78bd85415e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/ShibbolethAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/ShibbolethAction.java @@ -27,18 +27,18 @@ import org.dspace.core.Context; import org.dspace.eperson.EPerson; /** - * Attempt to authenticate the user based upon their presented shibboleth credentials. + * Attempt to authenticate the user based upon their presented shibboleth credentials. * This action uses the HTTP parameters as supplied by Shibboleth SP. * Read dspace.cfg for configuration detail. * *

    If the authentication attempt is successful then an HTTP redirect will be - * sent to the browser redirecting them to their original location in the - * system before authenticated or if none is supplied back to the DSpace + * sent to the browser redirecting them to their original location in the + * system before authenticated or if none is supplied back to the DSpace * home page. The action will also return true, thus contents of the action will * be executed. * *

    If the authentication attempt fails, the action returns false. - * + * *

    Example use: * *

    @@ -70,8 +70,8 @@ public class ShibbolethAction extends AbstractAction
          */
         @Override
         public Map act(Redirector redirector, SourceResolver resolver, Map objectModel,
    -            String source, Parameters parameters)
    -            throws PatternException, Exception
    +        String source, Parameters parameters)
    +        throws PatternException, Exception
         {
             try
             {
    @@ -79,7 +79,7 @@ public class ShibbolethAction extends AbstractAction
                 Context context = AuthenticationUtil.authenticate(objectModel, null, null, null);
     
                 EPerson eperson = null;
    -            if(context != null)
    +            if (context != null)
                 {
                     eperson = context.getCurrentUser();
                 }
    @@ -87,27 +87,28 @@ public class ShibbolethAction extends AbstractAction
                 if (eperson != null)
                 {
                     Request request = ObjectModelHelper.getRequest(objectModel);
    -            	// The user has successfully logged in
    -            	String redirectURL = request.getContextPath();
    -            	
    -            	if (AuthenticationUtil.isInterupptedRequest(objectModel))
    -            	{
    -            		// Resume the request and set the redirect target URL to
    -            		// that of the originally interrupted request.
    -            		redirectURL += AuthenticationUtil.resumeInterruptedRequest(objectModel);
    -            	}
    -            	else
    -            	{
    -            		// Otherwise direct the user to the specified 'loginredirect' page (or homepage by default)
    -            		String loginRedirect = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.user.loginredirect");
    -            		redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "/";	
    -            	}
    -            	
    +                // The user has successfully logged in
    +                String redirectURL = request.getContextPath();
    +
    +                if (AuthenticationUtil.isInterupptedRequest(objectModel))
    +                {
    +                    // Resume the request and set the redirect target URL to
    +                    // that of the originally interrupted request.
    +                    redirectURL += AuthenticationUtil.resumeInterruptedRequest(objectModel);
    +                }
    +                else
    +                {
    +                    // Otherwise direct the user to the specified 'loginredirect' page (or homepage by default)
    +                    String loginRedirect = DSpaceServicesFactory.getInstance()
    +                        .getConfigurationService().getProperty("xmlui.user.loginredirect");
    +                    redirectURL += (loginRedirect != null) ? loginRedirect.trim() : "/";
    +                }
    +
                     // Authentication successful - send a redirect.
                     final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
    -                
    +
                     httpResponse.sendRedirect(redirectURL);
    -                
    +
                     // log the user out for the rest of this current request, however they will be reauthenticated
                     // fully when they come back from the redirect. This prevents caching problems where part of the
                     // request is performed for the user was authenticated and the other half after it succeeded. This
    @@ -115,17 +116,16 @@ public class ShibbolethAction extends AbstractAction
                     //
                     // TODO: have no idea what this is, but leave it as it is, could be broken
                     context.setCurrentUser(null);
    -                
    +
                     return new HashMap();
                 }
             }
             catch (SQLException sqle)
             {
    -            throw new PatternException("Unable to perform Shibboleth authentication",
    -                    sqle);
    +            throw new PatternException(
    +                "Unable to perform Shibboleth authentication", sqle);
             }
    -        
    +
             return null;
         }
    -
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartForgotPassword.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartForgotPassword.java
    index a555c71083..fd5e92be0c 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartForgotPassword.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartForgotPassword.java
    @@ -105,49 +105,48 @@ public class StartForgotPassword extends AbstractDSpaceTransformer
             pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
             pageMeta.addTrail().addContent(T_trail_forgot_password);
         }
    -    
    -    
    -   public void addBody(Body body) throws WingException {
    +
    +    public void addBody(Body body) throws WingException {
    +         
    +        Division forgot = body.addInteractiveDivision("start-forgot-password",
    +                contextPath+"/forgot",Division.METHOD_POST,"primary");
             
    -       Division forgot = body.addInteractiveDivision("start-forgot-password",
    -               contextPath+"/forgot",Division.METHOD_POST,"primary");
    -       
    -       forgot.setHead(T_head);
    -       
    -       EPersonUtils.forgottProgressList(forgot,1);
    -       
    -       forgot.addPara(T_para1);
    -       
    -       List form = forgot.addList("form",List.TYPE_FORM);
    -       
    -       Text email = form.addItem().addText("email");
    -       email.setRequired();
    -       email.setAutofocus("autofocus");
    -       email.setLabel(T_email_address);
    -       email.setHelp(T_email_address_help);
    -       
    -       // Prefill with invalid email if this is a retry attempt.
    -       if (email != null)
    -       {
    -           email.setValue(this.email);
    -       }
    -       if (errors.contains("email"))
    -       {
    -           email.addError(T_error_not_found);
    -       }
    -       
    -       Item submit = form.addItem();
    -       submit.addButton("submit").setValue(T_submit);
    -       
    -       forgot.addHidden("eperson-continue").setValue(knot.getId()); 
    -   }
    -   
    -   /**
    -    * Recycle
    -    */
    -   public void recycle() 
    -   {
    -       this.email = null;
    -       super.recycle();
    -   } 
    +        forgot.setHead(T_head);
    +        
    +        EPersonUtils.forgottProgressList(forgot,1);
    +        
    +        forgot.addPara(T_para1);
    +        
    +        List form = forgot.addList("form",List.TYPE_FORM);
    +        
    +        Text email = form.addItem().addText("email");
    +        email.setRequired();
    +        email.setAutofocus("autofocus");
    +        email.setLabel(T_email_address);
    +        email.setHelp(T_email_address_help);
    +        
    +        // Prefill with invalid email if this is a retry attempt.
    +        if (email != null)
    +        {
    +            email.setValue(this.email);
    +        }
    +        if (errors.contains("email"))
    +        {
    +            email.addError(T_error_not_found);
    +        }
    +        
    +        Item submit = form.addItem();
    +        submit.addButton("submit").setValue(T_submit);
    +        
    +        forgot.addHidden("eperson-continue").setValue(knot.getId()); 
    +    }
    +    
    +    /**
    +     * Recycle
    +     */
    +    public void recycle() 
    +    {
    +        this.email = null;
    +        super.recycle();
    +    } 
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartRegistration.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartRegistration.java
    index 5499243045..298d33077d 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartRegistration.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/StartRegistration.java
    @@ -168,64 +168,66 @@ public class StartRegistration extends AbstractDSpaceTransformer implements Cach
             pageMeta.addTrail().addContent(T_trail_new_registration);
         }
         
    -   public void addBody(Body body) throws WingException {
    +    public void addBody(Body body) throws WingException {
    +         
    +        if (accountExists) {
    +            Division exists = body.addInteractiveDivision(
    +                "register-account-exists", contextPath + "/register",
    +                Division.METHOD_POST, "primary");
    + 
    +            exists.setHead(T_head1);
    +            
    +            exists.addPara(T_para1);
    + 
    +            List form = exists.addList("form");
    +            
    +            form.addLabel(T_reset_password_for);
    +            form.addItem(this.email);
    +            
    +            form.addLabel();
    +            Item submit = form.addItem();
    +            submit.addButton("submit_forgot").setValue(T_submit_reset);
    +            
    +            exists.addHidden("email").setValue(this.email);
    +            exists.addHidden("eperson-continue").setValue(knot.getId()); 
    +        }
             
    -       if (accountExists) {
    -           Division exists = body.addInteractiveDivision("register-account-exists",contextPath+"/register",Division.METHOD_POST,"primary");
    -
    -           exists.setHead(T_head1);
    -           
    -           exists.addPara(T_para1);
    -
    -           List form = exists.addList("form");
    -           
    -           form.addLabel(T_reset_password_for);
    -           form.addItem(this.email);
    -           
    -           form.addLabel();
    -           Item submit = form.addItem();
    -           submit.addButton("submit_forgot").setValue(T_submit_reset);
    -           
    -           exists.addHidden("email").setValue(this.email);
    -           exists.addHidden("eperson-continue").setValue(knot.getId()); 
    -       }
    -       
    -       
    -       Division register = body.addInteractiveDivision("register",
    -               contextPath+"/register",Division.METHOD_POST,"primary");
    -       
    -       register.setHead(T_head2);
    -       
    -       EPersonUtils.registrationProgressList(register,1);
    -       
    -       register.addPara(T_para2);
    -       
    -       List form = register.addList("form",List.TYPE_FORM);
    -       
    -       Text email = form.addItem().addText("email");
    -       email.setRequired();
    -       email.setAutofocus("autofocus");
    -       email.setLabel(T_email_address);
    -       email.setHelp(T_email_address_help);
    -       email.setValue(this.email);
    -       if (errors.contains("email"))
    -       {
    -           email.addError(T_error_bad_email);
    -       }
    -       
    -       Item submit = form.addItem();
    -       submit.addButton("submit").setValue(T_submit_register);
    -       
    -       register.addHidden("eperson-continue").setValue(knot.getId()); 
    -   }
    -   
    -   /**
    -    * Recycle
    -    */
    -   public void recycle() 
    -   {
    -       this.email = null;
    -       this.errors = null;
    -       super.recycle();
    -   }
    +        
    +        Division register = body.addInteractiveDivision("register",
    +                contextPath+"/register",Division.METHOD_POST,"primary");
    +        
    +        register.setHead(T_head2);
    +        
    +        EPersonUtils.registrationProgressList(register,1);
    +        
    +        register.addPara(T_para2);
    +        
    +        List form = register.addList("form",List.TYPE_FORM);
    +        
    +        Text email = form.addItem().addText("email");
    +        email.setRequired();
    +        email.setAutofocus("autofocus");
    +        email.setLabel(T_email_address);
    +        email.setHelp(T_email_address_help);
    +        email.setValue(this.email);
    +        if (errors.contains("email"))
    +        {
    +            email.addError(T_error_bad_email);
    +        }
    +        
    +        Item submit = form.addItem();
    +        submit.addButton("submit").setValue(T_submit_register);
    +        
    +        register.addHidden("eperson-continue").setValue(knot.getId()); 
    +    }
    +    
    +    /**
    +     * Recycle
    +     */
    +    public void recycle() 
    +    {
    +        this.email = null;
    +        this.errors = null;
    +        super.recycle();
    +    }
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/UnAuthenticateAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/UnAuthenticateAction.java
    index 25896e85b3..92e68f6922 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/UnAuthenticateAction.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/eperson/UnAuthenticateAction.java
    @@ -25,9 +25,9 @@ import org.dspace.core.Context;
     import org.dspace.eperson.EPerson;
     
     /**
    - * Unauthenticate the current user. There is no way this action will fail, 
    + * Unauthenticate the current user. There is no way this action will fail,
      * so any components inside the action will be executed.
    - * 
    + *
      * 

    This action will always send an HTTP redirect to the DSpace home page. * *

    Example: @@ -35,13 +35,13 @@ import org.dspace.eperson.EPerson; *

      * {@code
      * 
    - * 
    + *
      * 
      *   
      * 
      * }
      * 
    - * + * * @author Scott Phillips */ @@ -50,7 +50,7 @@ public class UnAuthenticateAction extends AbstractAction /** * Logout the current user. - * + * * @param redirector redirector. * @param resolver source resolver. * @param objectModel @@ -62,36 +62,39 @@ public class UnAuthenticateAction extends AbstractAction */ @Override public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, - String source, Parameters parameters) throws Exception + String source, Parameters parameters) + throws Exception { - + Context context = ContextUtil.obtainContext(objectModel); - final HttpServletRequest httpRequest = + final HttpServletRequest httpRequest = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); - final HttpServletResponse httpResponse = + final HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); EPerson eperson = context.getCurrentUser(); - + // Actually log the user out. AuthenticationUtil.logOut(context,httpRequest); - + // Set the user as logged in for the rest of this request so that the cache does not get spoiled. context.setCurrentUser(eperson); - + // Forward the user to the home page. - if((DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.public.logout")) && (httpRequest.isSecure())) { - StringBuffer location = new StringBuffer("http://"); - location.append(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.hostname")).append( - httpRequest.getContextPath()); - httpResponse.sendRedirect(location.toString()); - - } - else{ - httpResponse.sendRedirect(httpRequest.getContextPath()); + if ((DSpaceServicesFactory.getInstance().getConfigurationService() + .getBooleanProperty("xmlui.public.logout")) && (httpRequest.isSecure())) + { + StringBuffer location = new StringBuffer("http://"); + location.append(DSpaceServicesFactory.getInstance() + .getConfigurationService().getProperty("dspace.hostname")) + .append(httpRequest.getContextPath()); + httpResponse.sendRedirect(location.toString()); } - + else + { + httpResponse.sendRedirect(httpRequest.getContextPath()); + } + return new HashMap(); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ConfigurationMatcher.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ConfigurationMatcher.java index 4e91e07299..3c47bccffc 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ConfigurationMatcher.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ConfigurationMatcher.java @@ -19,10 +19,10 @@ import org.dspace.services.factory.DSpaceServicesFactory; /** * Use the configuration in Dspace.cfg to select paths in sitemap.xmap - * + * * Original Concept, JSPUI version: Universidade do Minho at www.uminho.pt * Sponsorship of XMLUI version: Instituto Oceanográfico de España at www.ieo.es - * + * * @author Adán Román Ruiz at arvo.es */ @@ -30,8 +30,8 @@ public class ConfigurationMatcher extends AbstractLogEnabled implements Matcher { /** * Format "keyInDspace.cfg,value,value" - * "Only property" check if it is defined(not empty), - * "property,value" check if property has this value, + * "Only property" check if it is defined(not empty), + * "property,value" check if property has this value, * "property, value,value..." check that property has one of the following values. * operator ! is alowed: "!property, value, value2" property has not value 1 nor value 2 * @param pattern @@ -40,40 +40,57 @@ public class ConfigurationMatcher extends AbstractLogEnabled implements Matcher * environment passed through via cocoon * @return null or map containing value of sitemap parameter 'pattern' */ - public Map match(String pattern, Map objectModel, Parameters parameters) throws PatternException + public Map match(String pattern, Map objectModel, Parameters parameters) + throws PatternException { - boolean not = false; - boolean itMatch = false; - if (pattern.startsWith("!")) { - not = true; - pattern = pattern.substring(1); - } - String[] expressions = pattern.split(","); - String propertyValue = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(expressions[0]); - if (expressions.length == 1) { - if (StringUtils.isNotEmpty(propertyValue)) { - itMatch = true; - } else { - itMatch = false; - } - } else { - for (int i = 1; i < expressions.length; i++) { - if (StringUtils.equalsIgnoreCase(expressions[i], propertyValue)) { - itMatch = true; - break; - } - } - itMatch = false; - } - if (itMatch && !not) { - return new HashMap(); - } else if (itMatch && not) { - return null; - } else if (!itMatch && !not) { - return null; - } else if (!itMatch && not) { - return new HashMap(); - } - return null; - } + boolean not = false; + boolean itMatch = false; + if (pattern.startsWith("!")) + { + not = true; + pattern = pattern.substring(1); + } + String[] expressions = pattern.split(","); + String propertyValue = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(expressions[0]); + if (expressions.length == 1) + { + if (StringUtils.isNotEmpty(propertyValue)) + { + itMatch = true; + } + else + { + itMatch = false; + } + } + else + { + for (int i = 1; i < expressions.length; i++) + { + if (StringUtils.equalsIgnoreCase(expressions[i], propertyValue)) + { + itMatch = true; + break; + } + } + itMatch = false; + } + if (itMatch && !not) + { + return new HashMap(); + } + else if (itMatch && not) + { + return null; + } + else if (!itMatch && !not) + { + return null; + } + else if (!itMatch && not) + { + return new HashMap(); + } + return null; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/HandleAuthorizedMatcher.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/HandleAuthorizedMatcher.java index a57559daa1..e2842a67e8 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/HandleAuthorizedMatcher.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/HandleAuthorizedMatcher.java @@ -28,7 +28,7 @@ import org.dspace.core.Context; * Test the current URL to see if the user has access to the described * resources. The privelege tested against uses the pattern attribute, the * possible values are listed in the DSpace Constant class. - * + * * @author Scott Phillips * @author Tim Van den Langenbergh */ @@ -42,7 +42,7 @@ public class HandleAuthorizedMatcher extends AbstractLogEnabled implements Match * Match method to see if the sitemap parameter exists. If it does have a * value the parameter added to the array list for later sitemap * substitution. - * + * * @param pattern * name of sitemap parameter to find * @param objectModel @@ -50,55 +50,54 @@ public class HandleAuthorizedMatcher extends AbstractLogEnabled implements Match * @return null or map containing value of sitemap parameter 'pattern' */ public Map match(String pattern, Map objectModel, Parameters parameters) - throws PatternException + throws PatternException { - // Are we checking for *NOT* the action or the action. - boolean not = false; - int action = -1; // the action to check - - if (pattern.startsWith("!")) - { - not = true; - pattern = pattern.substring(1); - } - - for (int i=0; i< Constants.actionText.length; i++) - { - if (Constants.actionText[i].equals(pattern)) - { - action = i; - } - } - - // Is it a valid action? - if (action < 0 || action >= Constants.actionText.length) - { - getLogger().warn("Invalid action: '"+pattern+"'"); - return null; - } - + // Are we checking for *NOT* the action or the action. + boolean not = false; + int action = -1; // the action to check + + if (pattern.startsWith("!")) + { + not = true; + pattern = pattern.substring(1); + } + + for (int i=0; i< Constants.actionText.length; i++) + { + if (Constants.actionText[i].equals(pattern)) + { + action = i; + } + } + + // Is it a valid action? + if (action < 0 || action >= Constants.actionText.length) + { + getLogger().warn("Invalid action: '"+pattern+"'"); + return null; + } + try { - Context context = ContextUtil.obtainContext(objectModel); + Context context = ContextUtil.obtainContext(objectModel); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - + if (dso == null) { return null; } - + boolean authorized = authorizeService.authorizeActionBoolean(context, dso, action); // XOR if (not ^ authorized) { - return new HashMap(); + return new HashMap(); } else { return null; } - } catch (SQLException sqle) { diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/NoticeTransformer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/NoticeTransformer.java index 6c2c024cc4..b31071cf2f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/NoticeTransformer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/NoticeTransformer.java @@ -17,26 +17,26 @@ import org.dspace.app.xmlui.wing.element.Division; import org.dspace.authorize.AuthorizeException; /** - * This class will add a simple notification div the DRI document. Typically + * This class will add a simple notification div the DRI document. Typically * this transformer is used after an action has been performed to let the * user know if an operation succeeded or failed. - * + * *

    The possible parameters are: * *

    outcome: The outcome determines whether the notice is positive or negative. - * Possible values are: "success", "failure", or "neutral". If no values are + * Possible values are: "success", "failure", or "neutral". If no values are * supplied then neutral is assumed. * *

    header: An i18n dictionary key referencing the text that should be used * as a header for this notice. - * + * *

    message: An i18n dictionary key referencing the text that should be used as - * the content for this notice. - * + * the content for this notice. + * *

    characters: Plain text string that should be used as the content for this * notice. Normally, all messages should be i18n dictionary keys, however this * parameter is useful for error messages that are not necessarily translated. - * + * *

    All parameters are optional but you must supply at least the message or the * characters. * @@ -49,69 +49,70 @@ import org.dspace.authorize.AuthorizeException; * * } *

    - * + * * @author Scott Phillips * @author Alexey Maslov */ -public class NoticeTransformer extends AbstractDSpaceTransformer +public class NoticeTransformer extends AbstractDSpaceTransformer { - - /** Language Strings */ - private static final Message T_head = - message("xmlui.general.notice.default_head"); - - /** - * Add the notice div to the body. + + /** Language Strings */ + private static final Message T_head = + message("xmlui.general.notice.default_head"); + + /** + * Add the notice div to the body. * @throws org.dspace.app.xmlui.wing.WingException passed through. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ + */ @Override - public void addBody(Body body) throws WingException, SQLException, AuthorizeException - { - String outcome = parameters.getParameter("outcome",null); - String header = parameters.getParameter("header",null); - String message = parameters.getParameter("message",null); - String characters = parameters.getParameter("characters",null); - - if ((message == null || message.length() <= 0) && - (characters == null || characters.length() <= 0)) + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { + String outcome = parameters.getParameter("outcome",null); + String header = parameters.getParameter("header",null); + String message = parameters.getParameter("message",null); + String characters = parameters.getParameter("characters",null); + + if ((message == null || message.length() <= 0) && + (characters == null || characters.length() <= 0)) { throw new WingException("No message found."); } - - String rend = "notice"; - if ("neutral".equals(outcome)) + + String rend = "notice"; + if ("neutral".equals(outcome)) { rend += " neutral"; } - else if ("success".equals(outcome)) + else if ("success".equals(outcome)) { rend += " success"; } - else if ("failure".equals(outcome)) + else if ("failure".equals(outcome)) { rend += " failure"; } - - Division div = body.addDivision("general-message",rend); - if ((header != null) && (!"".equals(header))) + + Division div = body.addDivision("general-message", rend); + if ((header != null) && (!"".equals(header))) { div.setHead(message(header)); } - else + else { div.setHead(T_head); } - if (message != null && message.length() > 0) + if (message != null && message.length() > 0) { div.addPara(message(message)); } - - if (characters != null && characters.length() > 0) + + if (characters != null && characters.length() > 0) { div.addPara(characters); } - } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/statistics/StatisticsTransformer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/statistics/StatisticsTransformer.java index 9d7b015bdf..5b6ac66088 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/statistics/StatisticsTransformer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/statistics/StatisticsTransformer.java @@ -33,7 +33,7 @@ import java.util.Date; public class StatisticsTransformer extends AbstractDSpaceTransformer { - private static Logger log = Logger.getLogger(StatisticsTransformer.class); + private static Logger log = Logger.getLogger(StatisticsTransformer.class); private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_head_title = message("xmlui.statistics.title"); @@ -50,29 +50,31 @@ public class StatisticsTransformer extends AbstractDSpaceTransformer { private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); public StatisticsTransformer(Date dateStart, Date dateEnd) { this.dateStart = dateStart; this.dateEnd = dateEnd; - this.context = new Context(); - } + this.context = new Context(); + } public StatisticsTransformer() { - this.context = new Context(); - } + this.context = new Context(); + } /** * Add a page title and trail links */ - public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException + { //Try to find our dspace object DSpaceObject dso = HandleUtil.obtainHandle(objectModel); pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - if(dso != null) + if (dso != null) { HandleUtil.buildHandleTrail(context, dso, pageMeta, contextPath, true); } @@ -83,65 +85,73 @@ public class StatisticsTransformer extends AbstractDSpaceTransformer { } /** - * What to add at the end of the body - */ - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException { + * What to add at the end of the body + */ + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException + { //Try to find our dspace object DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - try - { - if(dso != null) - { - renderViewer(body, dso); - } - else - { - renderHome(body); - } - - } catch (RuntimeException e) { + try + { + if (dso != null) + { + renderViewer(body, dso); + } + else + { + renderHome(body); + } + } + catch (RuntimeException e) + { throw e; - } catch (Exception e) { - log.error(e.getMessage(), e); - } + } + catch (Exception e) + { + log.error(e.getMessage(), e); + } + } - } + public void renderHome(Body body) + throws WingException + { - public void renderHome(Body body) throws WingException { - - Division home = body.addDivision("home", "primary repository"); - Division division = home.addDivision("stats", "secondary stats"); - division.setHead(T_head_title); + Division home = body.addDivision("home", "primary repository"); + Division division = home.addDivision("stats", "secondary stats"); + division.setHead(T_head_title); /* - try { + try + { + StatisticsTable statisticsTable = new StatisticsTable( + new StatisticsDataVisits()); - StatisticsTable statisticsTable = new StatisticsTable( - new StatisticsDataVisits()); + statisticsTable.setTitle(T_head_visits_month); + statisticsTable.setId("tab1"); - statisticsTable.setTitle(T_head_visits_month); - statisticsTable.setId("tab1"); + DatasetTimeGenerator timeAxis = new DatasetTimeGenerator(); + timeAxis.setDateInterval("month", "-6", "+1"); + statisticsTable.addDatasetGenerator(timeAxis); - DatasetTimeGenerator timeAxis = new DatasetTimeGenerator(); - timeAxis.setDateInterval("month", "-6", "+1"); - statisticsTable.addDatasetGenerator(timeAxis); + addDisplayTable(division, statisticsTable); - addDisplayTable(division, statisticsTable); - - } catch (Exception e) { - log.error("Error occurred while creating statistics for home page", - e); - } - */ - try { + } + catch (Exception e) + { + log.error("Error occurred while creating statistics for home page", + e); + } + */ + try + { /** List of the top 10 items for the entire repository **/ - StatisticsListing statListing = new StatisticsListing( - new StatisticsDataVisits()); + StatisticsListing statListing = new StatisticsListing( + new StatisticsDataVisits()); - statListing.setTitle(T_head_visits_total); - statListing.setId("list1"); + statListing.setTitle(T_head_visits_total); + statListing.setId("list1"); //Adding a new generator for our top 10 items without a name length delimiter DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); @@ -149,76 +159,81 @@ public class StatisticsTransformer extends AbstractDSpaceTransformer { statListing.addDatasetGenerator(dsoAxis); //Render the list as a table - addDisplayListing(division, statListing); + addDisplayListing(division, statListing); - } catch (Exception e) { - log.error("Error occurred while creating statistics for home page", e); - } + } + catch (Exception e) + { + log.error("Error occurred while creating statistics for home page", e); + } + } - } + public void renderViewer(Body body, DSpaceObject dso) + throws WingException + { - public void renderViewer(Body body, DSpaceObject dso) throws WingException { + Division home = body.addDivision( + Constants.typeText[dso.getType()].toLowerCase() + "-home", + "primary repository " + Constants.typeText[dso.getType()].toLowerCase()); - Division home = body.addDivision( - Constants.typeText[dso.getType()].toLowerCase() + "-home", - "primary repository " + Constants.typeText[dso.getType()].toLowerCase()); - - // Build the collection viewer division. - Division division = home.addDivision("stats", "secondary stats"); - division.setHead(T_head_title); + // Build the collection viewer division. + Division division = home.addDivision("stats", "secondary stats"); + division.setHead(T_head_title); - - try { - StatisticsListing statListing = new StatisticsListing( - new StatisticsDataVisits(dso)); - statListing.setTitle(T_head_visits_total); - statListing.setId("list1"); + try + { + StatisticsListing statListing = new StatisticsListing( + new StatisticsDataVisits(dso)); - DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); - dsoAxis.addDsoChild(dso.getType(), 10, false, -1); - statListing.addDatasetGenerator(dsoAxis); + statListing.setTitle(T_head_visits_total); + statListing.setId("list1"); - addDisplayListing(division, statListing); + DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); + dsoAxis.addDsoChild(dso.getType(), 10, false, -1); + statListing.addDatasetGenerator(dsoAxis); - } catch (Exception e) { - log.error( - "Error occurred while creating statistics for dso with ID: " - + dso.getID() + " and type " + dso.getType() - + " and handle: " + dso.getHandle(), e); - } - - - - try { + addDisplayListing(division, statListing); + } + catch (Exception e) + { + log.error( + "Error occurred while creating statistics for dso with ID: " + + dso.getID() + " and type " + dso.getType() + + " and handle: " + dso.getHandle(), e); + } - StatisticsTable statisticsTable = new StatisticsTable(new StatisticsDataVisits(dso)); + try + { + StatisticsTable statisticsTable = new StatisticsTable(new StatisticsDataVisits(dso)); - statisticsTable.setTitle(T_head_visits_month); - statisticsTable.setId("tab1"); + statisticsTable.setTitle(T_head_visits_month); + statisticsTable.setId("tab1"); - DatasetTimeGenerator timeAxis = new DatasetTimeGenerator(); - timeAxis.setDateInterval("month", "-6", "+1"); - statisticsTable.addDatasetGenerator(timeAxis); + DatasetTimeGenerator timeAxis = new DatasetTimeGenerator(); + timeAxis.setDateInterval("month", "-6", "+1"); + statisticsTable.addDatasetGenerator(timeAxis); - DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); - dsoAxis.addDsoChild(dso.getType(), 10, false, -1); - statisticsTable.addDatasetGenerator(dsoAxis); + DatasetDSpaceObjectGenerator dsoAxis = new DatasetDSpaceObjectGenerator(); + dsoAxis.addDsoChild(dso.getType(), 10, false, -1); + statisticsTable.addDatasetGenerator(dsoAxis); - addDisplayTable(division, statisticsTable); + addDisplayTable(division, statisticsTable); + } + catch (Exception e) + { + log.error( + "Error occurred while creating statistics for dso with ID: " + + dso.getID() + " and type " + dso.getType() + + " and handle: " + dso.getHandle(), e); + } - } catch (Exception e) { - log.error( - "Error occurred while creating statistics for dso with ID: " - + dso.getID() + " and type " + dso.getType() - + " and handle: " + dso.getHandle(), e); - } - - if(dso instanceof org.dspace.content.Item){ - //Make sure our item has at least one bitstream - org.dspace.content.Item item = (org.dspace.content.Item) dso; + if (dso instanceof org.dspace.content.Item) + { + //Make sure our item has at least one bitstream + org.dspace.content.Item item = (org.dspace.content.Item) dso; try { - if(itemService.hasUploadedFiles(item)){ + if (itemService.hasUploadedFiles(item)){ StatisticsListing statsList = new StatisticsListing(new StatisticsDataVisits(dso)); statsList.setTitle(T_head_visits_bitstream); @@ -230,17 +245,20 @@ public class StatisticsTransformer extends AbstractDSpaceTransformer { addDisplayListing(division, statsList); } - } catch (Exception e) { + } + catch (Exception e) + { log.error( - "Error occurred while creating statistics for dso with ID: " - + dso.getID() + " and type " + dso.getType() - + " and handle: " + dso.getHandle(), e); + "Error occurred while creating statistics for dso with ID: " + + dso.getID() + " and type " + dso.getType() + + " and handle: " + dso.getHandle(), e); } } - try { + try + { StatisticsListing statListing = new StatisticsListing( - new StatisticsDataVisits(dso)); + new StatisticsDataVisits(dso)); statListing.setTitle(T_head_visits_countries); statListing.setId("list2"); @@ -254,16 +272,19 @@ public class StatisticsTransformer extends AbstractDSpaceTransformer { statListing.addDatasetGenerator(typeAxis); addDisplayListing(division, statListing); - } catch (Exception e) { + } + catch (Exception e) + { log.error( - "Error occurred while creating statistics for dso with ID: " - + dso.getID() + " and type " + dso.getType() - + " and handle: " + dso.getHandle(), e); + "Error occurred while creating statistics for dso with ID: " + + dso.getID() + " and type " + dso.getType() + + " and handle: " + dso.getHandle(), e); } - try { + try + { StatisticsListing statListing = new StatisticsListing( - new StatisticsDataVisits(dso)); + new StatisticsDataVisits(dso)); statListing.setTitle(T_head_visits_cities); statListing.setId("list3"); @@ -277,138 +298,143 @@ public class StatisticsTransformer extends AbstractDSpaceTransformer { statListing.addDatasetGenerator(typeAxis); addDisplayListing(division, statListing); - } catch (Exception e) { + } + catch (Exception e) + { log.error( - "Error occurred while creating statistics for dso with ID: " - + dso.getID() + " and type " + dso.getType() - + " and handle: " + dso.getHandle(), e); + "Error occurred while creating statistics for dso with ID: " + + dso.getID() + " and type " + dso.getType() + + " and handle: " + dso.getHandle(), e); + } + } + + + /** + * Adds a table layout to the page + * + * @param mainDiv + * the div to add the table to + * @param display + * @throws SAXException + * @throws WingException + * @throws ParseException + * @throws IOException + * @throws SolrServerException + * @throws SQLException + * An exception that provides information on a database access error or other errors. + */ + private void addDisplayTable(Division mainDiv, StatisticsTable display) + throws SAXException, WingException, SQLException, SolrServerException, + IOException, ParseException + { + + String title = display.getTitle(); + + Dataset dataset = display.getDataset(); + + if (dataset == null) { + /** activate dataset query */ + dataset = display.getDataset(context); } - } + if (dataset != null) + { + String[][] matrix = dataset.getMatrix(); - - /** - * Adds a table layout to the page - * - * @param mainDiv - * the div to add the table to - * @param display - * @throws SAXException - * @throws WingException - * @throws ParseException - * @throws IOException - * @throws SolrServerException - * @throws SQLException - */ - private void addDisplayTable(Division mainDiv, StatisticsTable display) - throws SAXException, WingException, SQLException, - SolrServerException, IOException, ParseException { - - String title = display.getTitle(); - - Dataset dataset = display.getDataset(); - - if (dataset == null) { - /** activate dataset query */ - dataset = display.getDataset(context); - } - - if (dataset != null) { - - String[][] matrix = dataset.getMatrix(); - - /** Generate Table */ - Division wrapper = mainDiv.addDivision("tablewrapper"); - Table table = wrapper.addTable("list-table", 1, 1, - title == null ? "detailtable" : "tableWithTitle detailtable"); - if (title != null) + /** Generate Table */ + Division wrapper = mainDiv.addDivision("tablewrapper"); + Table table = wrapper.addTable("list-table", 1, 1, + title == null ? "detailtable" : "tableWithTitle detailtable"); + if (title != null) { table.setHead(message(title)); } - /** Generate Header Row */ - Row headerRow = table.addRow(); - headerRow.addCell("spacer", Cell.ROLE_HEADER, "labelcell"); + /** Generate Header Row */ + Row headerRow = table.addRow(); + headerRow.addCell("spacer", Cell.ROLE_HEADER, "labelcell"); - String[] cLabels = dataset.getColLabels().toArray(new String[0]); - for (int row = 0; row < cLabels.length; row++) { - Cell cell = headerRow.addCell(0 + "-" + row + "-h", + String[] cLabels = dataset.getColLabels().toArray(new String[0]); + for (int row = 0; row < cLabels.length; row++) + { + Cell cell = headerRow.addCell(0 + "-" + row + "-h", Cell.ROLE_HEADER, "labelcell"); - cell.addContent(cLabels[row]); - } + cell.addContent(cLabels[row]); + } - /** Generate Table Body */ - for (int row = 0; row < matrix.length; row++) { - Row valListRow = table.addRow(); + /** Generate Table Body */ + for (int row = 0; row < matrix.length; row++) + { + Row valListRow = table.addRow(); - /** Add Row Title */ - valListRow.addCell("" + row, Cell.ROLE_DATA, "labelcell") - .addContent(dataset.getRowLabels().get(row)); + /** Add Row Title */ + valListRow.addCell("" + row, Cell.ROLE_DATA, "labelcell") + .addContent(dataset.getRowLabels().get(row)); - /** Add Rest of Row */ - for (int col = 0; col < matrix[row].length; col++) { - Cell cell = valListRow.addCell(row + "-" + col, - Cell.ROLE_DATA, "datacell"); - cell.addContent(matrix[row][col]); - } - } - } + /** Add Rest of Row */ + for (int col = 0; col < matrix[row].length; col++) + { + Cell cell = valListRow.addCell(row + "-" + col, + Cell.ROLE_DATA, "datacell"); + cell.addContent(matrix[row][col]); + } + } + } + } - } + private void addDisplayListing(Division mainDiv, StatisticsListing display) + throws SAXException, WingException, SQLException, SolrServerException, + IOException, ParseException + { + String title = display.getTitle(); - private void addDisplayListing(Division mainDiv, StatisticsListing display) - throws SAXException, WingException, SQLException, - SolrServerException, IOException, ParseException { + Dataset dataset = display.getDataset(); - String title = display.getTitle(); + if (dataset == null) + { + /** activate dataset query */ + dataset = display.getDataset(context); + } - Dataset dataset = display.getDataset(); + if (dataset != null) + { - if (dataset == null) { - /** activate dataset query */ - dataset = display.getDataset(context); - } + String[][] matrix = dataset.getMatrix(); - if (dataset != null) { + // String[] rLabels = dataset.getRowLabels().toArray(new String[0]); - String[][] matrix = dataset.getMatrix(); - - // String[] rLabels = dataset.getRowLabels().toArray(new String[0]); - - Table table = mainDiv.addTable("list-table", matrix.length, 2, - title == null ? "detailtable" : "tableWithTitle detailtable"); - if (title != null) + Table table = mainDiv.addTable("list-table", matrix.length, 2, + title == null ? "detailtable" : "tableWithTitle detailtable"); + if (title != null) { table.setHead(message(title)); } - Row headerRow = table.addRow(); + Row headerRow = table.addRow(); - headerRow.addCell("", Cell.ROLE_HEADER, "labelcell"); - - headerRow.addCell("", Cell.ROLE_HEADER, "labelcell").addContent(message(T_head_visits_views)); + headerRow.addCell("", Cell.ROLE_HEADER, "labelcell"); - /** Generate Table Body */ - for (int col = 0; col < matrix[0].length; col++) { - Row valListRow = table.addRow(); + headerRow.addCell("", Cell.ROLE_HEADER, "labelcell").addContent(message(T_head_visits_views)); - Cell catCell = valListRow.addCell(col + "1", Cell.ROLE_DATA, - "labelcell"); - catCell.addContent(dataset.getColLabels().get(col)); + /** Generate Table Body */ + for (int col = 0; col < matrix[0].length; col++) + { + Row valListRow = table.addRow(); - Cell valCell = valListRow.addCell(col + "2", Cell.ROLE_DATA, - "datacell"); - valCell.addContent(matrix[0][col]); + Cell catCell = valListRow.addCell(col + "1", Cell.ROLE_DATA, + "labelcell"); + catCell.addContent(dataset.getColLabels().get(col)); - } - - if (!"".equals(display.getCss())) { - List attrlist = mainDiv.addList("divattrs"); - attrlist.addItem("style", display.getCss()); - } - - } - - } + Cell valCell = valListRow.addCell(col + "2", Cell.ROLE_DATA, + "datacell"); + valCell.addContent(matrix[0][col]); + } + if (!"".equals(display.getCss())) + { + List attrlist = mainDiv.addList("divattrs"); + attrlist.addItem("style", display.getCss()); + } + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/AbstractStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/AbstractStep.java index e5b9fd95e8..79e0603a7e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/AbstractStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/AbstractStep.java @@ -38,123 +38,123 @@ import org.dspace.workflowbasic.BasicWorkflowItem; import org.xml.sax.SAXException; /** - * This abstract class represents an abstract page in the - * submission or workflow processes. This class provides a place - * for common resources to be shared such as i18n tags, progress bars, + * This abstract class represents an abstract page in the + * submission or workflow processes. This class provides a place + * for common resources to be shared such as i18n tags, progress bars, * and a common setup. - * - * + * + * * @author Scott Phillips * @author Tim Donohue (updated for Configurable Submission) */ -public abstract class AbstractStep extends AbstractDSpaceTransformer +public abstract class AbstractStep extends AbstractDSpaceTransformer { - private static final Logger log = Logger.getLogger(AbstractStep.class); + private static final Logger log = Logger.getLogger(AbstractStep.class); /** General Language Strings */ - protected static final Message T_submission_title = + protected static final Message T_submission_title = message("xmlui.Submission.general.submission.title"); - protected static final Message T_submission_trail = + protected static final Message T_submission_trail = message("xmlui.Submission.general.submission.trail"); - protected static final Message T_submission_head = + protected static final Message T_submission_head = message("xmlui.Submission.general.submission.head"); - protected static final Message T_previous = + protected static final Message T_previous = message("xmlui.Submission.general.submission.previous"); - protected static final Message T_save = + protected static final Message T_save = message("xmlui.Submission.general.submission.save"); - protected static final Message T_next = + protected static final Message T_next = message("xmlui.Submission.general.submission.next"); - protected static final Message T_complete = + protected static final Message T_complete = message("xmlui.Submission.general.submission.complete"); - protected static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - protected static final Message T_workflow_title = + protected static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + protected static final Message T_workflow_title = message("xmlui.Submission.general.workflow.title"); - protected static final Message T_workflow_trail = + protected static final Message T_workflow_trail = message("xmlui.Submission.general.workflow.trail"); - protected static final Message T_workflow_head = + protected static final Message T_workflow_head = message("xmlui.Submission.general.workflow.head"); - protected static final Message T_showfull = + protected static final Message T_showfull = message("xmlui.Submission.general.showfull"); - protected static final Message T_showsimple = + protected static final Message T_showsimple = message("xmlui.Submission.general.showsimple"); - - protected static final Message T_default_title = + + protected static final Message T_default_title = message("xmlui.Submission.general.default.title"); - protected static final Message T_default_trail = + protected static final Message T_default_trail = message("xmlui.Submission.general.default.trail"); - - + + /** Progress Bar Language Strings */ - protected static final Message T_initial_questions = + protected static final Message T_initial_questions = message("xmlui.Submission.general.progress.initial_questions"); - protected static final Message T_describe = + protected static final Message T_describe = message("xmlui.Submission.general.progress.describe"); - protected static final Message T_upload = + protected static final Message T_upload = message("xmlui.Submission.general.progress.upload"); - protected static final Message T_review = + protected static final Message T_review = message("xmlui.Submission.general.progress.review"); - protected static final Message T_creative_commons = + protected static final Message T_creative_commons = message("xmlui.Submission.general.progress.creative_commons"); - protected static final Message T_license = + protected static final Message T_license = message("xmlui.Submission.general.progress.license"); - - - /** - * The id of the currently active workspace or workflow, this contains - * the incomplete DSpace item + + + /** + * The id of the currently active workspace or workflow, this contains + * the incomplete DSpace item */ - protected String id; - + protected String id; + /** * The current DSpace SubmissionInfo */ protected SubmissionInfo submissionInfo; - - /** - * The in progress submission, if one is available, this may be either - * a workflowItem or a workspaceItem. - */ - protected InProgressSubmission submission; - - /** - * The current step and page's numeric values that it is at currently. This - * number is dynamic between submissions. - */ - protected StepAndPage stepAndPage; - - /** - * The handle being processed by the current step. - */ - protected String handle; - - /** - * The error flag which was returned by the processing of this step - */ - protected int errorFlag; - - /** - * A list of fields that may be in error, not all stages support - * errored fields but if they do then this is where a list of all - * fields in error may be found. - */ - protected java.util.List errorFields; + + /** + * The in progress submission, if one is available, this may be either + * a workflowItem or a workspaceItem. + */ + protected InProgressSubmission submission; + + /** + * The current step and page's numeric values that it is at currently. This + * number is dynamic between submissions. + */ + protected StepAndPage stepAndPage; + + /** + * The handle being processed by the current step. + */ + protected String handle; + + /** + * The error flag which was returned by the processing of this step + */ + protected int errorFlag; + + /** + * A list of fields that may be in error, not all stages support + * errored fields but if they do then this is where a list of all + * fields in error may be found. + */ + protected java.util.List errorFields; - /** The parameters that are required by this submissions / workflow step */ - protected boolean requireSubmission = false; - protected boolean requireWorkflow = false; - protected boolean requireWorkspace = false; - protected boolean requireStep = false; - protected boolean requireHandle = false; - + /** The parameters that are required by this submissions / workflow step */ + protected boolean requireSubmission = false; + protected boolean requireWorkflow = false; + protected boolean requireWorkspace = false; + protected boolean requireStep = false; + protected boolean requireHandle = false; - /** - * Grab all the page's parameters from the sitemap. This includes - * workspaceID, step, and a list of errored fields. - * - * If the implementer set any required parameters then ensure that - * they are all present. + + /** + * Grab all the page's parameters from the sitemap. This includes + * workspaceID, step, and a list of errored fields. + * + * If the implementer set any required parameters then ensure that + * they are all present. * * @param resolver source resolver. * @param objectModel TBD @@ -163,23 +163,23 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer * @throws org.apache.cocoon.ProcessingException passed through. * @throws org.xml.sax.SAXException passed through. * @throws java.io.IOException passed through. - */ + */ @Override - public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) - throws ProcessingException, SAXException, IOException - { - super.setup(resolver,objectModel,src,parameters); + public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver,objectModel,src,parameters); - try { - this.id = parameters.getParameter("id",null); - this.stepAndPage = new StepAndPage(parameters.getParameter("step","-1.-1")); - log.debug("AbstractStep.setup: step is " + parameters.getParameter("step","]defaulted[")); // FIXME mhw - this.handle = parameters.getParameter("handle",null); - this.errorFlag = Integer.valueOf(parameters.getParameter("error", String.valueOf(AbstractProcessingStep.STATUS_COMPLETE))); - this.errorFields = getErrorFields(parameters); - - // load in-progress submission - if (this.id != null) + try { + this.id = parameters.getParameter("id",null); + this.stepAndPage = new StepAndPage(parameters.getParameter("step","-1.-1")); + log.debug("AbstractStep.setup: step is " + parameters.getParameter("step","]defaulted[")); // FIXME mhw + this.handle = parameters.getParameter("handle",null); + this.errorFlag = Integer.valueOf(parameters.getParameter("error", String.valueOf(AbstractProcessingStep.STATUS_COMPLETE))); + this.errorFields = getErrorFields(parameters); + + // load in-progress submission + if (this.id != null) { try { this.submissionInfo = FlowUtils.obtainSubmissionInfo(objectModel, this.id); @@ -189,119 +189,119 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer } this.submission = submissionInfo.getSubmissionItem(); } - - // Check required error conditions - if (this.requireSubmission && this.submission == null) + + // Check required error conditions + if (this.requireSubmission && this.submission == null) { throw new ProcessingException("Unable to find submission for id: " + this.id); } - - if (this.requireWorkflow && !(submission instanceof BasicWorkflowItem)) + + if (this.requireWorkflow && !(submission instanceof BasicWorkflowItem)) { throw new ProcessingException("The submission is not a workflow, " + this.id); } - - if (this.requireWorkspace && !(submission instanceof WorkspaceItem)) + + if (this.requireWorkspace && !(submission instanceof WorkspaceItem)) { throw new ProcessingException("The submission is not a workspace, " + this.id); } - - if (this.requireStep && stepAndPage.getStep() < 0) + + if (this.requireStep && stepAndPage.getStep() < 0) { throw new ProcessingException("Step is a required parameter."); } - - if (this.requireHandle && handle == null) + + if (this.requireHandle && handle == null) { throw new ProcessingException("Handle is a required parameter."); } - - } - catch (SQLException sqle) - { - throw new ProcessingException("Unable to find submission.",sqle); - } - } + + } + catch (SQLException sqle) + { + throw new ProcessingException("Unable to find submission.",sqle); + } + } - /** - * Base pageMeta that is added to ALL submission stages + /** + * Base pageMeta that is added to ALL submission stages * @throws org.xml.sax.SAXException passed through. * @throws org.dspace.app.xmlui.wing.WingException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws java.sql.SQLException passed through. * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. - */ + */ @Override - public void addPageMeta(PageMeta pageMeta) + public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException - { - if (submission instanceof WorkspaceItem) - { - pageMeta.addMetadata("title").addContent(T_submission_title); - - Collection collection = submission.getCollection(); - - pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - HandleUtil.buildHandleTrail(context, collection,pageMeta,contextPath, true); - pageMeta.addTrail().addContent(T_submission_trail); - } - else if (submissionInfo != null && submissionInfo.isInWorkflow()) - { - pageMeta.addMetadata("title").addContent(T_workflow_title); - - Collection collection = submission.getCollection(); - - pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - HandleUtil.buildHandleTrail(context, collection,pageMeta,contextPath, true); - pageMeta.addTrail().addContent(T_workflow_trail); - } - else - { - // defaults for pages that don't have a workspace item or workflow - // item such as the submission complete page where the object is in transition. - pageMeta.addMetadata("title").addContent(T_default_title); - - pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - pageMeta.addTrail().addContent(T_default_trail); - } - } + { + if (submission instanceof WorkspaceItem) + { + pageMeta.addMetadata("title").addContent(T_submission_title); + + Collection collection = submission.getCollection(); + + pageMeta.addTrailLink(contextPath + "/",T_dspace_home); + HandleUtil.buildHandleTrail(context, collection,pageMeta,contextPath, true); + pageMeta.addTrail().addContent(T_submission_trail); + } + else if (submissionInfo != null && submissionInfo.isInWorkflow()) + { + pageMeta.addMetadata("title").addContent(T_workflow_title); + + Collection collection = submission.getCollection(); + + pageMeta.addTrailLink(contextPath + "/",T_dspace_home); + HandleUtil.buildHandleTrail(context, collection,pageMeta,contextPath, true); + pageMeta.addTrail().addContent(T_workflow_trail); + } + else + { + // defaults for pages that don't have a workspace item or workflow + // item such as the submission complete page where the object is in transition. + pageMeta.addMetadata("title").addContent(T_default_title); + + pageMeta.addTrailLink(contextPath + "/",T_dspace_home); + pageMeta.addTrail().addContent(T_default_trail); + } + } - /** - * Add a submission progress list to the current div for this step. - * - * @param div The division to add the list to. + /** + * Add a submission progress list to the current div for this step. + * + * @param div The division to add the list to. * @throws org.dspace.app.xmlui.wing.WingException passed through. - */ - public void addSubmissionProgressList(Division div) throws WingException - { - // each entry in progress bar is placed under this "submit-progress" div - List progress = div.addList("submit-progress",List.TYPE_PROGRESS); - - // get Map of progress bar information - // key: entry # (i.e. step & page), - // value: entry name key (i.e. display name) - Map progBarInfo = this.submissionInfo.getProgressBarInfo(); + */ + public void addSubmissionProgressList(Division div) throws WingException + { + // each entry in progress bar is placed under this "submit-progress" div + List progress = div.addList("submit-progress",List.TYPE_PROGRESS); + + // get Map of progress bar information + // key: entry # (i.e. step & page), + // value: entry name key (i.e. display name) + Map progBarInfo = this.submissionInfo.getProgressBarInfo(); + + // add each entry to progress bar + for (Map.Entry progBarEntry : progBarInfo.entrySet()) + { + // Since we are using XML-UI, we need to prepend the heading key with "xmlui.Submission." + String entryNameKey = "xmlui.Submission." + progBarEntry.getValue(); + + // the value of entryNum is current step & page + // (e.g. 1.2 is page 2 of step 1) + StepAndPage currentStepAndPage = new StepAndPage(progBarEntry.getKey()); - // add each entry to progress bar - for (Map.Entry progBarEntry : progBarInfo.entrySet()) - { - // Since we are using XML-UI, we need to prepend the heading key with "xmlui.Submission." - String entryNameKey = "xmlui.Submission." + progBarEntry.getValue(); - - // the value of entryNum is current step & page - // (e.g. 1.2 is page 2 of step 1) - StepAndPage currentStepAndPage = new StepAndPage(progBarEntry.getKey()); - // add a button to progress bar for this step & page addJumpButton(progress, message(entryNameKey), currentStepAndPage); - } - - } - + } + + } + /** * Adds a single "jump-to" button, which when clicked will * jump the user directly to a particular step within the @@ -326,15 +326,15 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer throws WingException { // Only add the button if we have button text and a valid step & page! - if(buttonText!=null && stepAndPage.isSet()) - { + if (buttonText != null && stepAndPage.isSet()) + { // add a Jump To button for this section Button jumpButton = list.addItem("step_" + stepAndPage, renderJumpButton(stepAndPage)) .addButton(AbstractProcessingStep.PROGRESS_BAR_PREFIX + stepAndPage); jumpButton.setValue(buttonText); } } - + /** * Adds the "{@literal <-Previous}", "{@literal Save/Cancel}" and * "{@literal Next->}" buttons to a given form. This method ensures that @@ -352,18 +352,18 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer throws WingException { Item actions = controls.addItem(); - + // only have "<-Previous" button if not first step - if(!isFirstStep()) + if (!isFirstStep()) { actions.addButton(AbstractProcessingStep.PREVIOUS_BUTTON).setValue(T_previous); } - + // always show "Save/Cancel" actions.addButton(AbstractProcessingStep.CANCEL_BUTTON).setValue(T_save); - + // If last step, show "Complete Submission" - if(isLastStep()) + if (isLastStep()) { actions.addButton(AbstractProcessingStep.NEXT_BUTTON).setValue(T_complete); } @@ -372,29 +372,29 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer actions.addButton(AbstractProcessingStep.NEXT_BUTTON).setValue(T_next); } } - - - /** - * Get current step number - * - * @return step number - */ - public int getStep() - { - return this.stepAndPage.getStep(); - } - - - /** - * Get number of the current page within the current step - * - * @return page number (within current step) - */ - public int getPage() - { - return this.stepAndPage.getPage(); - } - + + + /** + * Get current step number + * + * @return step number + */ + public int getStep() + { + return this.stepAndPage.getStep(); + } + + + /** + * Get number of the current page within the current step + * + * @return page number (within current step) + */ + public int getPage() + { + return this.stepAndPage.getPage(); + } + /** * Return whether this is the first step in * the submission process (the first step is @@ -406,14 +406,15 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer public boolean isFirstStep() { Set submissionPagesSet = submissionInfo.getProgressBarInfo().keySet(); - String[] submissionPages = (String[]) submissionPagesSet.toArray(new String[submissionPagesSet.size()]); - + String[] submissionPages = (String[]) submissionPagesSet.toArray( + new String[submissionPagesSet.size()]); + StepAndPage firstStepAndPage = new StepAndPage(submissionPages[0]); return firstStepAndPage.equals(stepAndPage); } - - + + /** * Return whether this is the last step in * the submission process (the last step is @@ -425,20 +426,21 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer public boolean isLastStep() { boolean inWorkflow = this.submissionInfo.isInWorkflow(); - + Set submissionPagesSet = submissionInfo.getProgressBarInfo().keySet(); - String[] submissionPages = (String[]) submissionPagesSet.toArray(new String[submissionPagesSet.size()]); - + String[] submissionPages = (String[]) submissionPagesSet.toArray( + new String[submissionPagesSet.size()]); + StepAndPage lastStepAndPage; - - if(!inWorkflow) + + if (!inWorkflow) { // If not in Workflow, // Last step is considered the one *before* the Complete Step lastStepAndPage = new StepAndPage(submissionPages[submissionPages.length-2]); } else - { + { lastStepAndPage = new StepAndPage(submissionPages[submissionPages.length-1]); } @@ -446,24 +448,26 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer } /** - * Find the maximum step and page that the user has + * Find the maximum step and page that the user has * reached in the submission processes. * If this submission is a workflow then return max-int. * @return the maximum step and page reached. * @throws java.sql.SQLException passed through. */ - public StepAndPage getMaxStepAndPageReached() throws SQLException { + public StepAndPage getMaxStepAndPageReached() + throws SQLException + { if (this.submission instanceof WorkspaceItem) { WorkspaceItem workspaceItem = (WorkspaceItem) submission; int step = workspaceItem.getStageReached(); - if(step<0) + if (step<0) { step = 0; } - + int page = workspaceItem.getPageReached(); if (page < 0) { @@ -472,41 +476,41 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer return new StepAndPage(step, page); } - + // This is a workflow, return infinity. return new StepAndPage(Integer.MAX_VALUE, Integer.MAX_VALUE); } - - /** - * Retrieve error fields from the list of parameters - * and return a List of all fields which had errors - * + + /** + * Retrieve error fields from the list of parameters + * and return a List of all fields which had errors + * * @param parameters the list to search for error fields. - * @return {@link java.util.List} of field names with errors - */ - public java.util.List getErrorFields(Parameters parameters) - { - java.util.List fields = new ArrayList<>(); - - String errors = parameters.getParameter("error_fields",""); - - if (errors!=null && errors.length() > 0) - { - if(errors.indexOf(',') > 0) + * @return {@link java.util.List} of field names with errors + */ + public java.util.List getErrorFields(Parameters parameters) + { + java.util.List fields = new ArrayList<>(); + + String errors = parameters.getParameter("error_fields",""); + + if (errors!=null && errors.length() > 0) + { + if (errors.indexOf(',') > 0) { fields = Arrays.asList(errors.split(",")); } - else//only one error field + else //only one error field { fields.add(errors); } - } - - return fields; - } - - /** - * A simple method to determine how the Jump to button + } + + return fields; + } + + /** + * A simple method to determine how the Jump to button * for a given step and page should be rendered. *

    * If the given step and page corresponds to the current @@ -514,14 +518,14 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer *

    * If the given step and page is greater than the max, * render it with "disabled" style. - * - * @param givenStepAndPage - * This given step & page (e.g. (1,2)) + * + * @param givenStepAndPage + * This given step and page (e.g. (1,2)) * @return * render style for this button */ - private String renderJumpButton(StepAndPage givenStepAndPage) - { + private String renderJumpButton(StepAndPage givenStepAndPage) + { try { if (givenStepAndPage.equals(this.stepAndPage)) @@ -537,21 +541,21 @@ public abstract class AbstractStep extends AbstractDSpaceTransformer return null; } } - catch(Exception e) + catch (Exception e) { return null; - } - } - + } + } + @Override - public void recycle() - { - this.id = null; - this.submission = null; - this.stepAndPage = new StepAndPage(); - this.handle = null; - this.errorFlag = 0; - this.errorFields = null; - super.recycle(); - } + public void recycle() + { + this.id = null; + this.submission = null; + this.stepAndPage = new StepAndPage(); + this.handle = null; + this.errorFlag = 0; + this.errorFields = null; + super.recycle(); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/CollectionViewer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/CollectionViewer.java index d713b17656..210ef9bdf2 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/CollectionViewer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/CollectionViewer.java @@ -38,19 +38,19 @@ import org.xml.sax.SAXException; /** * Add a single link to the display item page that allows * the user to submit a new item to this collection. - * + * * @author Scott Phillips */ public class CollectionViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent { - - /** Language Strings */ - protected static final Message T_title = + + /** Language Strings */ + protected static final Message T_title = message("xmlui.Submission.SelectCollection.title"); - protected static final Message T_submit = - message("xmlui.Submission.CollectionViewer.link1"); - - + protected static final Message T_submit = + message("xmlui.Submission.CollectionViewer.link1"); + + /** Cached validity object */ private SourceValidity validity; @@ -71,7 +71,7 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache { return "0"; } - + return HashUtil.hash(dso.getHandle()); } catch (SQLException sqle) @@ -84,88 +84,88 @@ public class CollectionViewer extends AbstractDSpaceTransformer implements Cache /** * Generate the cache validity object. - * - * The validity object will include the collection being viewed and + * + * The validity object will include the collection being viewed and * all recently submitted items. This does not include the community / collection * hierarchy, when this changes they will not be reflected in the cache. */ public SourceValidity getValidity() { - if (this.validity == null) - { - try - { - DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - - if (dso == null) + if (this.validity == null) + { + try + { + DSpaceObject dso = HandleUtil.obtainHandle(objectModel); + + if (dso == null) { return null; } - - if (!(dso instanceof Collection)) + + if (!(dso instanceof Collection)) { return null; } - - Collection collection = (Collection) dso; - - DSpaceValidity validity = new DSpaceValidity(); - - // Add the actual collection; - validity.add(context, collection); - - // Add the eperson viewing the collection - validity.add(context, eperson); - - // Include any groups they are a member of - List groups = groupService.allMemberGroups(context, eperson); - for (Group group : groups) - { - validity.add(context, group); - } - - this.validity = validity.complete(); - } - catch (Exception e) - { - // Just ignore all errors and return an invalid cache. - } - } - return this.validity; + + Collection collection = (Collection) dso; + + DSpaceValidity validity = new DSpaceValidity(); + + // Add the actual collection; + validity.add(context, collection); + + // Add the eperson viewing the collection + validity.add(context, eperson); + + // Include any groups they are a member of + List groups = groupService.allMemberGroups(context, eperson); + for (Group group : groups) + { + validity.add(context, group); + } + + this.validity = validity.complete(); + } + catch (Exception e) + { + // Just ignore all errors and return an invalid cache. + } + } + return this.validity; } /** - * Add a single link to the view item page that allows the user + * Add a single link to the view item page that allows the user * to submit to the collection. */ - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { DSpaceObject dso = HandleUtil.obtainHandle(objectModel); if (!(dso instanceof Collection)) { return; } - + // Set up the major variables Collection collection = (Collection) dso; - + // Only add the submit link if the user has the ability to add items. if (authorizeService.authorizeActionBoolean(context, collection, Constants.ADD)) { - Division home = body.addDivision("collection-home","primary repository collection"); - Division viewer = home.addDivision("collection-view","secondary"); - String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit"; - viewer.addPara().addXref(submitURL,T_submit); + Division home = body.addDivision("collection-home", "primary repository collection"); + Division viewer = home.addDivision("collection-view", "secondary"); + String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit"; + viewer.addPara().addXref(submitURL, T_submit); } - } - + /** * Recycle */ - public void recycle() - { + public void recycle() + { this.validity = null; super.recycle(); } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/FlowUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/FlowUtils.java index 89561dcdce..d1501c060b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/FlowUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/FlowUtils.java @@ -33,13 +33,13 @@ import java.util.ArrayList; import java.util.Map; /** - * This is a utility class to aid in the submission flow scripts. - * Since data validation is cumbersome inside a flow script this - * is a collection of methods to perform processing at each step - * of the flow, the flow script will ties these operations - * together in a meaningful order but all actually processing + * This is a utility class to aid in the submission flow scripts. + * Since data validation is cumbersome inside a flow script this + * is a collection of methods to perform processing at each step + * of the flow, the flow script will ties these operations + * together in a meaningful order but all actually processing * is done through these various processes. - * + * * @author Scott Phillips * @author Tim Donohue (modified for Configurable Submission) */ @@ -47,64 +47,67 @@ import java.util.Map; public class FlowUtils { private static final Logger log = Logger.getLogger(FlowUtils.class); - + /** Where the submissionInfo is stored on an HTTP Request object */ private static final String DSPACE_SUBMISSION_INFO = "dspace.submission.info"; protected static final WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); protected static final WorkflowItemService workflowService = WorkflowServiceFactory.getInstance().getWorkflowItemService(); - /** - * Return the InProgressSubmission, either workspaceItem or workflowItem, - * depending on the id provided. If the id begins with an S then it is a - * considered a workspaceItem. If the id begins with a W then it is - * considered a workflowItem. - * - * @param context session context. - * @param inProgressSubmissionID the submission's ID. - * @return The InprogressSubmission or null if non found + /** + * Return the InProgressSubmission, either workspaceItem or workflowItem, + * depending on the id provided. If the id begins with an S then it is a + * considered a workspaceItem. If the id begins with a W then it is + * considered a workflowItem. + * + * @param context session context. + * @param inProgressSubmissionID the submission's ID. + * @return The InprogressSubmission or null if non found * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static InProgressSubmission findSubmission(Context context, String inProgressSubmissionID) - throws SQLException, AuthorizeException, IOException { - char type = inProgressSubmissionID.charAt(0); - int id = Integer.valueOf(inProgressSubmissionID.substring(1)); - - if (type == 'S') - { - return workspaceItemService.find(context, id); - } - else if (type == 'W' || type == 'X') { + */ + public static InProgressSubmission findSubmission(Context context, String inProgressSubmissionID) + throws SQLException, AuthorizeException, IOException + { + char type = inProgressSubmissionID.charAt(0); + int id = Integer.valueOf(inProgressSubmissionID.substring(1)); + + if (type == 'S') + { + return workspaceItemService.find(context, id); + } + else if (type == 'W' || type == 'X') + { return workflowService.find(context, id); } - return null; - } + return null; + } - /** - * Return the workspace identified by the given id, the id should be - * prepended with the character S to signify that it is a workspace - * instead of a workflow. - * - * @param context session context. - * @param inProgressSubmissionID identifier of the submission. - * @return The found workspace item, or null if none found. + /** + * Return the workspace identified by the given id, the id should be + * prepended with the character S to signify that it is a workspace + * instead of a workflow. + * + * @param context session context. + * @param inProgressSubmissionID identifier of the submission. + * @return The found workspace item, or null if none found. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static WorkspaceItem findWorkspace(Context context, String inProgressSubmissionID) - throws SQLException, AuthorizeException, IOException { - InProgressSubmission submission = findSubmission(context, inProgressSubmissionID); - if (submission instanceof WorkspaceItem) + */ + public static WorkspaceItem findWorkspace(Context context, String inProgressSubmissionID) + throws SQLException, AuthorizeException, IOException + { + InProgressSubmission submission = findSubmission(context, inProgressSubmissionID); + if (submission instanceof WorkspaceItem) { return (WorkspaceItem) submission; } - return null; - } + return null; + } - /** + /** * Obtains the submission info for the current submission process. * If a submissionInfo object has already been created * for this HTTP request, it is re-used, otherwise it is created. @@ -112,40 +115,41 @@ public class FlowUtils { * @param objectModel * the Cocoon object model * @param workspaceID - * the workspaceID of the submission info to obtain - * + * the workspaceID of the submission info to obtain + * * @return a SubmissionInfo object. * @throws java.sql.SQLException on error. * @throws java.io.IOException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. */ public static SubmissionInfo obtainSubmissionInfo(Map objectModel, String workspaceID) - throws SQLException, IOException, AuthorizeException { + throws SQLException, IOException, AuthorizeException + { Request request = ObjectModelHelper.getRequest(objectModel); Context context = ContextUtil.obtainContext(objectModel); - + //try loading subInfo from HTTP request SubmissionInfo subInfo = (SubmissionInfo) request.getAttribute(DSPACE_SUBMISSION_INFO); - + //get the submission represented by the WorkspaceID InProgressSubmission submission = findSubmission(context, workspaceID); //if no submission info, or wrong submission info, reload it! - if ((subInfo == null && submission!=null) || + if ((subInfo == null && submission!=null) || (subInfo!=null && submission!=null && subInfo.getSubmissionItem().getID()!=submission.getID())) { try { final HttpServletRequest httpRequest = (HttpServletRequest) objectModel .get(HttpEnvironment.HTTP_REQUEST_OBJECT); - + // load submission info subInfo = SubmissionInfo.load(httpRequest, submission); - + // Set the session ID context.setExtraLogInfo("session_id=" + request.getSession().getId()); - + // Store the submissionInfo in the request request.setAttribute(DSPACE_SUBMISSION_INFO, subInfo); } @@ -153,23 +157,23 @@ public class FlowUtils { { throw new SQLException("Error loading Submission Info: " + e.getMessage(), e); } - } - else if(subInfo==null && submission==null) + } + else if (subInfo==null && submission==null) { throw new SQLException("Unable to load Submission Information, since WorkspaceID (ID:" + workspaceID + ") is not a valid in-process submission."); } return subInfo; } - - /** - * Indicate the user has advanced to the given page within a given step. - * This will only actually do anything when it's a user initially entering + + /** + * Indicate the user has advanced to the given page within a given step. + * This will only actually do anything when it's a user initially entering * a submission. It will increase the "stage reached" and "page reached" * columns - it will not "set back" where a user has reached. - * + * * @param context The current DSpace content - * @param id The unique ID of the current workflow/workspace + * @param id The unique ID of the current workflow/workspace * @param step the step the user has just reached * @param page the page (within the step) the user has just reached * @throws java.sql.SQLException passed through. @@ -180,30 +184,30 @@ public class FlowUtils { throws SQLException, AuthorizeException, IOException { InProgressSubmission submission = findSubmission(context, id); - - if (submission instanceof WorkspaceItem) - { - WorkspaceItem workspaceItem = (WorkspaceItem) submission; - - if (step > workspaceItem.getStageReached()) - { - workspaceItem.setStageReached(step); - workspaceItem.setPageReached(1); //reset page to first page in new step - workspaceItemService.update(context, workspaceItem); - } - else if ((step == workspaceItem.getStageReached()) && - (page > workspaceItem.getPageReached())) - { - workspaceItem.setPageReached(page); + + if (submission instanceof WorkspaceItem) + { + WorkspaceItem workspaceItem = (WorkspaceItem) submission; + + if (step > workspaceItem.getStageReached()) + { + workspaceItem.setStageReached(step); + workspaceItem.setPageReached(1); //reset page to first page in new step workspaceItemService.update(context, workspaceItem); - } - } + } + else if ((step == workspaceItem.getStageReached()) && + (page > workspaceItem.getPageReached())) + { + workspaceItem.setPageReached(page); + workspaceItemService.update(context, workspaceItem); + } + } } - + /** - * Set a specific step and page as reached. + * Set a specific step and page as reached. * It will also "set back" where a user has reached. - * + * * @param context The current DSpace content * @param id The unique ID of the current workflow/workspace * @param step the step to set as reached, can be also a previous reached step @@ -226,148 +230,148 @@ public class FlowUtils { workspaceItemService.update(context, workspaceItem); } } - + /** - * Find the maximum step the user has reached in the submission processes. + * Find the maximum step the user has reached in the submission processes. * If this submission is a workflow then return max-int. - * + * * @param context The current DSpace context. - * @param id The unique ID of the current workflow/workspace. + * @param id The unique ID of the current workflow/workspace. * @return step that has been reached. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. */ - public static int getMaximumStepReached(Context context, String id) + public static int getMaximumStepReached(Context context, String id) throws SQLException, AuthorizeException, IOException { - - InProgressSubmission submission = findSubmission(context, id); - - if (submission instanceof WorkspaceItem) - { - WorkspaceItem workspaceItem = (WorkspaceItem) submission; - int stage = workspaceItem.getStageReached(); - if (stage < 0) + + InProgressSubmission submission = findSubmission(context, id); + + if (submission instanceof WorkspaceItem) + { + WorkspaceItem workspaceItem = (WorkspaceItem) submission; + int stage = workspaceItem.getStageReached(); + if (stage < 0) { stage = 0; } - return stage; - } - - // This is a workflow, return infinity. - return Integer.MAX_VALUE; - } - - /** - * Find the maximum page (within the maximum step) that the user has - * reached in the submission processes. + return stage; + } + + // This is a workflow, return infinity. + return Integer.MAX_VALUE; + } + + /** + * Find the maximum page (within the maximum step) that the user has + * reached in the submission processes. * If this submission is a workflow then return max-int. - * + * * @param context The current DSpace content - * @param id The unique ID of the current workflow/workspace + * @param id The unique ID of the current workflow/workspace * @return the furthest page reached. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. */ - public static int getMaximumPageReached(Context context, String id) + public static int getMaximumPageReached(Context context, String id) throws SQLException, AuthorizeException, IOException { - InProgressSubmission submission = findSubmission(context, id); - - if (submission instanceof WorkspaceItem) - { - WorkspaceItem workspaceItem = (WorkspaceItem) submission; - int page = workspaceItem.getPageReached(); - if (page < 0) + InProgressSubmission submission = findSubmission(context, id); + + if (submission instanceof WorkspaceItem) + { + WorkspaceItem workspaceItem = (WorkspaceItem) submission; + int page = workspaceItem.getPageReached(); + if (page < 0) { page = 0; } - return page; - } - - // This is a workflow, return infinity. - return Integer.MAX_VALUE; - } - - - /** - * Get current step number - * - * @param stepAndPage - * a double representing the current step and page - * (e.g. 1.2 is page 2 of step 1) - * @return step number - */ - public static int getStep(double stepAndPage) - { - //split step and page (e.g. 1.2 is page 2 of step 1) - String[] fields = Double.toString(stepAndPage).split("\\."); // split on period - - return Integer.parseInt(fields[0]); - } - - - /** - * Get number of the current page within the current step - * - *@param stepAndPage - * a double representing the current step and page - * (e.g. 1.2 is page 2 of step 1) - * @return page number (within current step) - */ - public static int getPage(double stepAndPage) - { - //split step and page (e.g. 1.2 is page 2 of step 1) - String[] fields = Double.toString(stepAndPage).split("\\."); // split on period - - return Integer.parseInt(fields[1]); - } - - /** - * Process the save or remove step. If the user has selected to - * remove their submission then remove it. - * - * @param context The current DSpace content - * @param id The unique ID of the current workspace/workflow - * @param request The cocoon request object. + return page; + } + + // This is a workflow, return infinity. + return Integer.MAX_VALUE; + } + + + /** + * Get current step number + * + * @param stepAndPage + * a double representing the current step and page + * (e.g. 1.2 is page 2 of step 1) + * @return step number + */ + public static int getStep(double stepAndPage) + { + //split step and page (e.g. 1.2 is page 2 of step 1) + String[] fields = Double.toString(stepAndPage).split("\\."); // split on period + + return Integer.parseInt(fields[0]); + } + + + /** + * Get number of the current page within the current step + * + * @param stepAndPage + * a double representing the current step and page + * (e.g. 1.2 is page 2 of step 1) + * @return page number (within current step) + */ + public static int getPage(double stepAndPage) + { + //split step and page (e.g. 1.2 is page 2 of step 1) + String[] fields = Double.toString(stepAndPage).split("\\."); // split on period + + return Integer.parseInt(fields[1]); + } + + /** + * Process the save or remove step. If the user has selected to + * remove their submission then remove it. + * + * @param context The current DSpace content + * @param id The unique ID of the current workspace/workflow + * @param request The cocoon request object. * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static void processSaveOrRemove(Context context, String id, Request request) + */ + public static void processSaveOrRemove(Context context, String id, Request request) throws SQLException, AuthorizeException, IOException - { - if (request.getParameter("submit_remove") != null) - { - // If they selected to remove the item then delete everything. - WorkspaceItem workspace = findWorkspace(context,id); - workspaceItemService.deleteAll(context, workspace); - } - } - - /** - * Return the HTML / DRI field name for the given input. - * - * @param input the given input. - * @return field name as a String (e.g. dc_contributor_editor) - */ - public static String getFieldName(DCInput input) - { - String dcSchema = input.getSchema(); - String dcElement = input.getElement(); - String dcQualifier = input.getQualifier(); - if (dcQualifier != null && ! dcQualifier.equals(Item.ANY)) - { - return dcSchema + "_" + dcElement + '_' + dcQualifier; - } - else - { - return dcSchema + "_" + dcElement; - } + { + if (request.getParameter("submit_remove") != null) + { + // If they selected to remove the item then delete everything. + WorkspaceItem workspace = findWorkspace(context,id); + workspaceItemService.deleteAll(context, workspace); + } + } + + /** + * Return the HTML / DRI field name for the given input. + * + * @param input the given input. + * @return field name as a String (e.g. dc_contributor_editor) + */ + public static String getFieldName(DCInput input) + { + String dcSchema = input.getSchema(); + String dcElement = input.getElement(); + String dcQualifier = input.getQualifier(); + if (dcQualifier != null && ! dcQualifier.equals(Item.ANY)) + { + return dcSchema + "_" + dcElement + '_' + dcQualifier; + } + else + { + return dcSchema + "_" + dcElement; + } + + } - } - /** * Retrieves a list of all steps and pages within the * current submission process. @@ -377,14 +381,14 @@ public class FlowUtils { * non-interactive steps which do not appear in the progress bar! *

    * This method is used by the Manakin submission flowscript - * (submission.js) to step forward/backward between steps. - * + * (submission.js) to step forward/backward between steps. + * * @param request * The HTTP Servlet Request object * @param subInfo * the current SubmissionInfo object * @return the list of steps and pages. - * + * */ public static StepAndPage[] getListOfAllSteps(HttpServletRequest request, SubmissionInfo subInfo) { @@ -397,14 +401,14 @@ public class FlowUtils { SubmissionStepConfig currentStep = subInfo.getSubmissionConfig() .getStep(i); int stepNumber = currentStep.getStepNumber(); - + //Skip over the "Select Collection" step, since // a user is never allowed to return to that step or jump from that step - if(currentStep.getId()!=null && currentStep.getId().equals(SubmissionStepConfig.SELECT_COLLECTION_STEP)) + if (currentStep.getId()!=null && currentStep.getId().equals(SubmissionStepConfig.SELECT_COLLECTION_STEP)) { continue; } - + // default to just one page in this step int numPages = 1; @@ -413,8 +417,8 @@ public class FlowUtils { // load the processing class for this step ClassLoader loader = subInfo.getClass().getClassLoader(); Class stepClass = loader.loadClass(currentStep.getProcessingClassName()); - - // call the "getNumberOfPages()" method of the class + + // call the "getNumberOfPages()" method of the class // to get it's number of pages AbstractProcessingStep step = (AbstractProcessingStep) stepClass .newInstance(); @@ -433,10 +437,10 @@ public class FlowUtils { for (int j = 1; j <= numPages; j++) { StepAndPage stepAndPageNum = new StepAndPage(stepNumber,j); - + listStepNumbers.add(stepAndPageNum); - }// end for each page - }// end for each step + } // end for each page + } // end for each step //convert into an array and return that return listStepNumbers.toArray(new StepAndPage[listStepNumbers.size()]); diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Navigation.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Navigation.java index b436a84e80..8424b74e1e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Navigation.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Navigation.java @@ -24,58 +24,59 @@ import org.dspace.authorize.AuthorizeException; import org.xml.sax.SAXException; /** - * Simple navigation class to add the top level link to + * Simple navigation class to add the top level link to * the main submissions page. - * + * * @author Scott Phillips */ public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent { - - - /** Language Strings **/ - protected static final Message T_submissions = + + + /** Language Strings **/ + protected static final Message T_submissions = message("xmlui.Submission.Navigation.submissions"); - - /** + + /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { - + return 1; } /** * Generate the cache validity object. */ - public SourceValidity getValidity() + public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } - - - public void addOptions(Options options) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + + + public void addOptions(Options options) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - // Basic navigation skeleton + // Basic navigation skeleton options.addList("browse"); List account = options.addList("account"); options.addList("context"); options.addList("administrative"); - -// This doesn't flow very well, lets remove it and see if anyone misses it. -// DSpaceObject dso = HandleUtil.obtainHandle(objectModel); -// if (dso != null && dso instanceof Collection) -// { -// Collection collection = (Collection) dso; -// if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD)) -// { -// String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit"; -// account.addItemXref(submitURL,"Submit to this collection"); -// } -// } - - account.addItemXref(contextPath+"/submissions",T_submissions); + +// This doesn't flow very well, lets remove it and see if anyone misses it. +// DSpaceObject dso = HandleUtil.obtainHandle(objectModel); +// if (dso != null && dso instanceof Collection) +// { +// Collection collection = (Collection) dso; +// if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD)) +// { +// String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit"; +// account.addItemXref(submitURL,"Submit to this collection"); +// } +// } + + account.addItemXref(contextPath+"/submissions",T_submissions); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/StepTransformer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/StepTransformer.java index 01c41467c3..400db77261 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/StepTransformer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/StepTransformer.java @@ -9,7 +9,7 @@ package org.dspace.app.xmlui.aspect.submission; import java.io.IOException; import java.sql.SQLException; -import java.util.Map; +import java.util.Map; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; @@ -34,158 +34,162 @@ import org.xml.sax.SAXException; *

    * This transformer just initializes the current step class * and calls the appropriate method(s) for the step. - * + * * @author Tim Donohue * @see AbstractStep */ public class StepTransformer extends AbstractDSpaceTransformer { - /** - * The id of the currently active workspace or workflow, this contains - * the incomplete DSpace item + /** + * The id of the currently active workspace or workflow, this contains + * the incomplete DSpace item */ - protected String id; - - /** - * The current step and page's numeric value that it is at currently. This - * number is dynamic between submissions and is a double where the integer - * value is the step #, and the decimal value is the page # - * (e.g. 1.2 is page 2 of step 1) - */ - private double stepAndPage; - - /** - * Full name of the step's transformer class (which must extend - * org.dspace.app.xmlui.submission.AbstractStep). - */ - private String transformerClassName; - - /** + protected String id; + + /** + * The current step and page's numeric value that it is at currently. This + * number is dynamic between submissions and is a double where the integer + * value is the step #, and the decimal value is the page # + * (e.g. 1.2 is page 2 of step 1) + */ + private double stepAndPage; + + /** + * Full name of the step's transformer class (which must extend + * org.dspace.app.xmlui.submission.AbstractStep). + */ + private String transformerClassName; + + /** * The handle of the collection into which this DSpace * item is being submitted */ - protected String collectionHandle; - - /** - * An instance of the current step's transformer class (which must extend - * org.dspace.app.xmlui.submission.AbstractStep). This class is - * used to generate the actual DRI for this step. - */ - private AbstractSubmissionStep step; - - - /** - * Grab all the step's parameters from the sitemap. This includes - * workspaceID, step, and a list of errored fields. - * - * If the implementer set any required parameters then ensure that - * they are all present. - */ - public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) - throws ProcessingException, SAXException, IOException - { - super.setup(resolver,objectModel,src,parameters); + protected String collectionHandle; - // retrieve id and transformer information - // (This ID should always exist by this point, since the - // selection of the collection should have already happened!) - this.id = parameters.getParameter("id",null); - this.transformerClassName = parameters.getParameter("transformer",null); - - // even though its not used in this class, this "step" parameter - // is heavily used by the Transformers which extend the - // org.dspace.app.xmlui.submission.AbstractStep - this.stepAndPage = Double.valueOf(parameters.getParameter("step","-1")); - - // retrieve collection handle if it's there - this.collectionHandle = parameters.getParameter("handle",null); - - try - { - // retrieve an instance of the transformer class - ClassLoader loader = this.getClass().getClassLoader(); - Class stepClass = loader - .loadClass(this.transformerClassName); - - // this XML-UI class *must* be a valid AbstractSubmissionStep, - // or else we'll have problems here - step = (AbstractSubmissionStep) stepClass - .newInstance(); - } - catch(ClassNotFoundException cnfe) - { - // means that we couldn't find a class by the given name - throw new ProcessingException("Class Not Found: " + this.transformerClassName, cnfe); - } - catch(Exception e) - { - // means we couldn't instantiate the class as an AbstractStep - throw new ProcessingException("Unable to instantiate class " + this.transformerClassName + ". " + - "Please make sure it extends org.dspace.app.xmlui.submission.AbstractSubmissionStep!", e); - } - - - // call the setup for this step - if(step!=null) + /** + * An instance of the current step's transformer class (which must extend + * org.dspace.app.xmlui.submission.AbstractStep). This class is + * used to generate the actual DRI for this step. + */ + private AbstractSubmissionStep step; + + + /** + * Grab all the step's parameters from the sitemap. This includes + * workspaceID, step, and a list of errored fields. + * + * If the implementer set any required parameters then ensure that + * they are all present. + */ + public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver,objectModel,src,parameters); + + // retrieve id and transformer information + // (This ID should always exist by this point, since the + // selection of the collection should have already happened!) + this.id = parameters.getParameter("id",null); + this.transformerClassName = parameters.getParameter("transformer",null); + + // even though its not used in this class, this "step" parameter + // is heavily used by the Transformers which extend the + // org.dspace.app.xmlui.submission.AbstractStep + this.stepAndPage = Double.valueOf(parameters.getParameter("step","-1")); + + // retrieve collection handle if it's there + this.collectionHandle = parameters.getParameter("handle",null); + + try + { + // retrieve an instance of the transformer class + ClassLoader loader = this.getClass().getClassLoader(); + Class stepClass = loader + .loadClass(this.transformerClassName); + + // this XML-UI class *must* be a valid AbstractSubmissionStep, + // or else we'll have problems here + step = (AbstractSubmissionStep) stepClass + .newInstance(); + } + catch (ClassNotFoundException cnfe) + { + // means that we couldn't find a class by the given name + throw new ProcessingException("Class Not Found: " + this.transformerClassName, cnfe); + } + catch (Exception e) + { + // means we couldn't instantiate the class as an AbstractStep + throw new ProcessingException("Unable to instantiate class " + + this.transformerClassName + ". " + + "Please make sure it extends org.dspace.app.xmlui.submission.AbstractSubmissionStep!", + e); + } + + + // call the setup for this step + if (step != null) { step.setup(resolver, objectModel, src, parameters); } - else + else { throw new ProcessingException("Step class is null! We do not have a valid AbstractStep in " + this.transformerClassName + ". "); } - } + } - /** What to add at the end of the body */ - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException, ProcessingException + /** What to add at the end of the body */ + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException, ProcessingException { //call addBody for this step - step.addBody(body); + step.addBody(body); } /** What to add to the options list */ - public void addOptions(Options options) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addOptions(Options options) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { //call addOptions for this step - step.addOptions(options); + step.addOptions(options); } /** What user metadata to add to the document */ - public void addUserMeta(UserMeta userMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public void addUserMeta(UserMeta userMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - //call addUserMeta for this step - step.addUserMeta(userMeta); + //call addUserMeta for this step + step.addUserMeta(userMeta); } /** What page metadata to add to the document */ - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - //call addPageMeta for this step - step.addPageMeta(pageMeta); + //call addPageMeta for this step + step.addPageMeta(pageMeta); } - /** - * Recycle - */ - public void recycle() - { - this.id = null; - this.transformerClassName = null; - this.collectionHandle = null; - this.stepAndPage = -1; - if(step!=null) - { - this.step.recycle(); - this.step = null; + /** + * Recycle + */ + public void recycle() + { + this.id = null; + this.transformerClassName = null; + this.collectionHandle = null; + this.stepAndPage = -1; + if (step != null) + { + this.step.recycle(); + this.step = null; } - super.recycle(); - } + super.recycle(); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java index 7097f72ef9..b3286ca768 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java @@ -40,53 +40,53 @@ import java.util.List; */ public class Submissions extends AbstractDSpaceTransformer { - /** General Language Strings */ - protected static final Message T_title = + /** General Language Strings */ + protected static final Message T_title = message("xmlui.Submission.Submissions.title"); - protected static final Message T_dspace_home = - message("xmlui.general.dspace_home"); - protected static final Message T_trail = + protected static final Message T_dspace_home = + message("xmlui.general.dspace_home"); + protected static final Message T_trail = message("xmlui.Submission.Submissions.trail"); - protected static final Message T_head = + protected static final Message T_head = message("xmlui.Submission.Submissions.head"); - protected static final Message T_untitled = + protected static final Message T_untitled = message("xmlui.Submission.Submissions.untitled"); - protected static final Message T_email = + protected static final Message T_email = message("xmlui.Submission.Submissions.email"); // used by the unfinished submissions section - protected static final Message T_s_head1 = - message("xmlui.Submission.Submissions.submit_head1"); - protected static final Message T_s_info1a = - message("xmlui.Submission.Submissions.submit_info1a"); - protected static final Message T_s_info1b = - message("xmlui.Submission.Submissions.submit_info1b"); - protected static final Message T_s_info1c = - message("xmlui.Submission.Submissions.submit_info1c"); - protected static final Message T_s_head2 = - message("xmlui.Submission.Submissions.submit_head2"); - protected static final Message T_s_info2a = - message("xmlui.Submission.Submissions.submit_info2a"); - protected static final Message T_s_info2b = - message("xmlui.Submission.Submissions.submit_info2b"); - protected static final Message T_s_info2c = - message("xmlui.Submission.Submissions.submit_info2c"); - protected static final Message T_s_column1 = - message("xmlui.Submission.Submissions.submit_column1"); - protected static final Message T_s_column2 = - message("xmlui.Submission.Submissions.submit_column2"); - protected static final Message T_s_column3 = - message("xmlui.Submission.Submissions.submit_column3"); - protected static final Message T_s_column4 = - message("xmlui.Submission.Submissions.submit_column4"); - protected static final Message T_s_head3 = - message("xmlui.Submission.Submissions.submit_head3"); - protected static final Message T_s_info3 = - message("xmlui.Submission.Submissions.submit_info3"); - protected static final Message T_s_head4 = - message("xmlui.Submission.Submissions.submit_head4"); - protected static final Message T_s_submit_remove = - message("xmlui.Submission.Submissions.submit_submit_remove"); + protected static final Message T_s_head1 = + message("xmlui.Submission.Submissions.submit_head1"); + protected static final Message T_s_info1a = + message("xmlui.Submission.Submissions.submit_info1a"); + protected static final Message T_s_info1b = + message("xmlui.Submission.Submissions.submit_info1b"); + protected static final Message T_s_info1c = + message("xmlui.Submission.Submissions.submit_info1c"); + protected static final Message T_s_head2 = + message("xmlui.Submission.Submissions.submit_head2"); + protected static final Message T_s_info2a = + message("xmlui.Submission.Submissions.submit_info2a"); + protected static final Message T_s_info2b = + message("xmlui.Submission.Submissions.submit_info2b"); + protected static final Message T_s_info2c = + message("xmlui.Submission.Submissions.submit_info2c"); + protected static final Message T_s_column1 = + message("xmlui.Submission.Submissions.submit_column1"); + protected static final Message T_s_column2 = + message("xmlui.Submission.Submissions.submit_column2"); + protected static final Message T_s_column3 = + message("xmlui.Submission.Submissions.submit_column3"); + protected static final Message T_s_column4 = + message("xmlui.Submission.Submissions.submit_column4"); + protected static final Message T_s_head3 = + message("xmlui.Submission.Submissions.submit_head3"); + protected static final Message T_s_info3 = + message("xmlui.Submission.Submissions.submit_info3"); + protected static final Message T_s_head4 = + message("xmlui.Submission.Submissions.submit_head4"); + protected static final Message T_s_submit_remove = + message("xmlui.Submission.Submissions.submit_submit_remove"); // Used in the completed submissions section protected static final Message T_c_head = @@ -110,19 +110,20 @@ public class Submissions extends AbstractDSpaceTransformer protected SupervisedItemService supervisedItemService = ContentServiceFactory.getInstance().getSupervisedItemService(); @Override - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException - { - pageMeta.addMetadata("title").addContent(T_title); + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - pageMeta.addTrailLink(null,T_trail); - } + pageMeta.addTrailLink(contextPath + "/",T_dspace_home); + pageMeta.addTrailLink(null,T_trail); + } @Override - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { Request request = ObjectModelHelper.getRequest(objectModel); boolean displayAll = false; @@ -143,37 +144,38 @@ public class Submissions extends AbstractDSpaceTransformer } /** - * If the user has any workflow tasks, either assigned to them or in an + * If the user has any workflow tasks, either assigned to them or in an * available pool of tasks, then build two tables listing each of these queues. - * + * * If the user doesn't have any workflows then don't do anything. - * + * * @param division The division to add the two queues too. */ - private void addWorkflowTasksDiv(Division division) throws SQLException, WingException, AuthorizeException, IOException { - division.addDivision("workflow-tasks"); - } + private void addWorkflowTasksDiv(Division division) + throws SQLException, WingException, AuthorizeException, IOException + { + division.addDivision("workflow-tasks"); + } /** - * There are two options: the user has some unfinished submissions + * There are two options: the user has some unfinished submissions * or the user does not. - * - * If the user does not, then we just display a simple paragraph + * + * If the user does not, then we just display a simple paragraph * explaining that the user may submit new items to dspace. - * - * If the user does have unfinished submissions then a table is + * + * If the user does have unfinished submissions then a table is * presented listing all the unfinished submissions that this user has. - * + * */ private void addUnfinishedSubmissions(Division division) throws SQLException, WingException { - // User's WorkflowItems - List unfinishedItems = workspaceItemService.findByEPerson(context, context.getCurrentUser()); - List supervisedItems = supervisedItemService.findbyEPerson(context, context.getCurrentUser()); + List unfinishedItems = workspaceItemService.findByEPerson(context, context.getCurrentUser()); + List supervisedItems = supervisedItemService.findbyEPerson(context, context.getCurrentUser()); - if (unfinishedItems.size() <= 0 && supervisedItems.size() <= 0) - { + if (unfinishedItems.size() <= 0 && supervisedItems.size() <= 0) + { List collections = collectionService.findAuthorizedOptimized(context, Constants.ADD); if (collections.size() > 0) @@ -187,28 +189,28 @@ public class Submissions extends AbstractDSpaceTransformer secondP.addContent(T_s_info1c); return; } - } + } - Division unfinished = division.addDivision("unfinished-submisions"); - unfinished.setHead(T_s_head2); - Para p = unfinished.addPara(); - p.addContent(T_s_info2a); - p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b); - p.addContent(T_s_info2c); + Division unfinished = division.addDivision("unfinished-submisions"); + unfinished.setHead(T_s_head2); + Para p = unfinished.addPara(); + p.addContent(T_s_info2a); + p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b); + p.addContent(T_s_info2c); - // Calculate the number of rows. - // Each list pluss the top header and bottom row for the button. - int rows = unfinishedItems.size() + supervisedItems.size() + 2; - if (supervisedItems.size() > 0 && unfinishedItems.size() > 0) + // Calculate the number of rows. + // Each list pluss the top header and bottom row for the button. + int rows = unfinishedItems.size() + supervisedItems.size() + 2; + if (supervisedItems.size() > 0 && unfinishedItems.size() > 0) { rows++; // Authoring heading row } - if (supervisedItems.size() > 0) + if (supervisedItems.size() > 0) { rows++; // Supervising heading row } - Table table = unfinished.addTable("unfinished-submissions",rows,5); + Table table = unfinished.addTable("unfinished-submissions",rows,5); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_s_column1); header.addCellContent(T_s_column2); @@ -223,7 +225,7 @@ public class Submissions extends AbstractDSpaceTransformer if (unfinishedItems.size() > 0) { - for (WorkspaceItem workspaceItem : unfinishedItems) + for (WorkspaceItem workspaceItem : unfinishedItems) { String title = workspaceItem.getItem().getName(); EPerson submitterEPerson = workspaceItem.getItem().getSubmitter(); @@ -252,7 +254,7 @@ public class Submissions extends AbstractDSpaceTransformer cell.addContent(T_email); cell.addXref("mailto:"+submitterEmail,submitterName); } - } + } else { header = table.addRow(); @@ -265,7 +267,7 @@ public class Submissions extends AbstractDSpaceTransformer header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4); } - for (WorkspaceItem workspaceItem : supervisedItems) + for (WorkspaceItem workspaceItem : supervisedItems) { String title = workspaceItem.getItem().getName(); @@ -310,7 +312,7 @@ public class Submissions extends AbstractDSpaceTransformer /** * This section lists all the submissions that this user has submitted which are currently under review. - * + * * If the user has none, this nothing is displayed. */ private void addSubmissionsInWorkflowDiv(Division division) @@ -321,11 +323,11 @@ public class Submissions extends AbstractDSpaceTransformer /** * Show the user's completed submissions. - * + * * If the user has no completed submissions, display nothing. * If 'displayAll' is true, then display all user's archived submissions. * Otherwise, default to only displaying 50 archived submissions. - * + * * @param division div to put archived submissions in * @param displayAll whether to display all or just a limited number. */ @@ -337,7 +339,7 @@ public class Submissions extends AbstractDSpaceTransformer Integer limit; - if(displayAll) { + if (displayAll) { limit = -1; } else { //Set a default limit of 50 @@ -346,7 +348,7 @@ public class Submissions extends AbstractDSpaceTransformer Iterator subs = itemService.findBySubmitterDateSorted(context, context.getCurrentUser(), limit); //NOTE: notice we are adding each item to this list in *reverse* order... - // this is a very basic attempt at making more recent submissions float + // this is a very basic attempt at making more recent submissions float // up to the top of the list (findBySubmitter() doesn't guarrantee // chronological order, but tends to return older items near top of the list) while (subs.hasNext()) @@ -356,7 +358,9 @@ public class Submissions extends AbstractDSpaceTransformer // No tasks, so don't show the table. if (!(subList.size() > 0)) + { return; + } Division completedSubmissions = division.addDivision("completed-submissions"); completedSubmissions.setHead(T_c_head); @@ -370,7 +374,7 @@ public class Submissions extends AbstractDSpaceTransformer header.addCellContent(T_c_column3); // COLLECTION NAME (LINKED) //Limit to showing just 50 archived submissions, unless overridden - //(This is a saftey measure for Admins who may have submitted + //(This is a saftey measure for Admins who may have submitted // thousands of items under their account via bulk ingest tools, etc.) int count = 0; @@ -380,8 +384,10 @@ public class Submissions extends AbstractDSpaceTransformer { count++; //exit loop if we've gone over our limit of submissions to display - if(count>limit && !displayAll) + if (count>limit && !displayAll) + { break; + } Item published = i.next(); String collUrl = contextPath+"/handle/"+published.getOwningCollection().getHandle(); @@ -409,7 +415,9 @@ public class Submissions extends AbstractDSpaceTransformer { String displayTitle = titles.get(0).getValue(); if (displayTitle.length() > 50) + { displayTitle = displayTitle.substring(0,50)+ " ..."; + } row.addCell().addXref(itemUrl,displayTitle); } else @@ -417,15 +425,14 @@ public class Submissions extends AbstractDSpaceTransformer // Owning Collection row.addCell().addXref(collUrl,collectionName); - }//end while + } //end while //Display limit text & link to allow user to override this default limit - if(!displayAll && count == limit) + if (!displayAll && count == limit) { Para limitedList = completedSubmissions.addPara(); limitedList.addContent(T_c_limit); limitedList.addXref(contextPath + "/submissions?all", T_c_displayall); - } + } } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/AccessStepUtil.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/AccessStepUtil.java index 4fcd84cebc..7843d8d9f3 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/AccessStepUtil.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/AccessStepUtil.java @@ -38,12 +38,12 @@ import java.sql.SQLException; * */ public class AccessStepUtil extends AbstractDSpaceTransformer { - private Context context=null; + private Context context = null; - protected static final Message T_name =message("xmlui.Submission.submit.AccessStep.name"); - protected static final Message T_name_help = message("xmlui.Submission.submit.AccessStep.name_help"); - protected static final Message T_reason = message("xmlui.Submission.submit.AccessStep.reason"); - protected static final Message T_reason_help = message("xmlui.Submission.submit.AccessStep.reason_help"); + protected static final Message T_name = message("xmlui.Submission.submit.AccessStep.name"); + protected static final Message T_name_help = message("xmlui.Submission.submit.AccessStep.name_help"); + protected static final Message T_reason = message("xmlui.Submission.submit.AccessStep.reason"); + protected static final Message T_reason_help = message("xmlui.Submission.submit.AccessStep.reason_help"); protected static final Message T_radios_embargo = message("xmlui.Submission.submit.AccessStep.embargo_visible"); protected static final Message T_groups = message("xmlui.Submission.submit.AccessStep.list_assigned_groups"); protected static final Message T_item_will_be_visible = message("xmlui.Submission.submit.AccessStep.open_access"); @@ -55,20 +55,20 @@ public class AccessStepUtil extends AbstractDSpaceTransformer { // Policies Table protected static final Message T_no_policies = message("xmlui.Submission.submit.AccessStep.no_policies"); protected static final Message T_head_policies_table = message("xmlui.Submission.submit.AccessStep.table_policies"); - protected static final Message T_policies_help = message("xmlui.Submission.submit.AccessStep.policies_help"); - protected static final Message T_column0 =message("xmlui.Submission.submit.AccessStep.column0"); - protected static final Message T_column1 =message("xmlui.Submission.submit.AccessStep.column1"); - protected static final Message T_column2 =message("xmlui.Submission.submit.AccessStep.column2"); - protected static final Message T_column3 =message("xmlui.Submission.submit.AccessStep.column3"); - protected static final Message T_column4 =message("xmlui.Submission.submit.AccessStep.column4"); - protected static final Message T_table_submit_edit =message("xmlui.Submission.submit.AccessStep.table_edit_button"); - protected static final Message T_table_submit_delete =message("xmlui.Submission.submit.AccessStep.table_delete_button"); - protected static final Message T_policy = message("xmlui.Submission.submit.AccessStep.review_policy_line"); + protected static final Message T_policies_help = message("xmlui.Submission.submit.AccessStep.policies_help"); + protected static final Message T_column0 = message("xmlui.Submission.submit.AccessStep.column0"); + protected static final Message T_column1 = message("xmlui.Submission.submit.AccessStep.column1"); + protected static final Message T_column2 = message("xmlui.Submission.submit.AccessStep.column2"); + protected static final Message T_column3 = message("xmlui.Submission.submit.AccessStep.column3"); + protected static final Message T_column4 = message("xmlui.Submission.submit.AccessStep.column4"); + protected static final Message T_table_submit_edit = message("xmlui.Submission.submit.AccessStep.table_edit_button"); + protected static final Message T_table_submit_delete = message("xmlui.Submission.submit.AccessStep.table_delete_button"); + protected static final Message T_policy = message("xmlui.Submission.submit.AccessStep.review_policy_line"); private static final Message T_label_date_help = - message("xmlui.administrative.authorization.AccessStep.label_date_help"); + message("xmlui.administrative.authorization.AccessStep.label_date_help"); private static final Message T_label_date_displayonly_help = - message("xmlui.administrative.authorization.AccessStep.label_date_displayonly_help"); + message("xmlui.administrative.authorization.AccessStep.label_date_displayonly_help"); public static final int RADIO_OPEN_ACCESS_ITEM_VISIBLE=0; public static final int RADIO_OPEN_ACCESS_ITEM_EMBARGOED=1; @@ -80,43 +80,63 @@ public class AccessStepUtil extends AbstractDSpaceTransformer { //public static final int CB_EMBARGOED=10; private String globalReason = null; - private boolean isAdvancedFormEnabled=false; + private boolean isAdvancedFormEnabled = false; - public AccessStepUtil(Context c){ - isAdvancedFormEnabled=DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.submission.restrictstep.enableAdvancedForm", false); - context=c; + public AccessStepUtil(Context c) + { + isAdvancedFormEnabled = DSpaceServicesFactory.getInstance() + .getConfigurationService().getBooleanProperty( + "webui.submission.restrictstep.enableAdvancedForm", false); + context = c; } - public void addName(String name_, List form, int errorFlag) throws WingException { - if(isAdvancedFormEnabled){ + public void addName(String name_, List form, int errorFlag) + throws WingException + { + if (isAdvancedFormEnabled) + { Text name = form.addItem().addText("name"); - name.setSize(0, 30); + name.setSize(0, 30); name.setLabel(T_name); - name.setHelp(T_name_help); + name.setHelp(T_name_help); - if(name_!=null && errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE) + if (name_!=null && + errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE) + { name.setValue(name_); + } } } - public void addReason(String reason_, List form, int errorFlag) throws WingException { + public void addReason(String reason_, List form, int errorFlag) + throws WingException + { TextArea reason = form.addItem("reason", null).addTextArea("reason"); reason.setLabel(T_reason); - reason.setHelp(T_reason_help); + reason.setHelp(T_reason_help); - if(!isAdvancedFormEnabled){ - if(globalReason!=null) + if (!isAdvancedFormEnabled) + { + if (globalReason!=null) + { reason.setValue(globalReason); + } } - else{ - if(reason_!=null && errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE) + else + { + if (reason_!=null && errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE) + { reason.setValue(reason_); + } } } - public void addListGroups(String groupID, List form, int errorFlag, Collection owningCollection) throws WingException, SQLException { + public void addListGroups(String groupID, List form, int errorFlag, Collection owningCollection) + throws WingException, SQLException + { - if(isAdvancedFormEnabled){ + if (isAdvancedFormEnabled) + { // currently set group form.addLabel(T_groups); Select groupSelect = form.addItem().addSelect("group_id"); @@ -125,51 +145,71 @@ public class AccessStepUtil extends AbstractDSpaceTransformer { java.util.List loadedGroups = null; // retrieve groups - String name = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("webui.submission.restrictstep.groups"); - if(name!=null){ + String name = DSpaceServicesFactory.getInstance() + .getConfigurationService().getProperty( + "webui.submission.restrictstep.groups"); + if (name != null) + { Group uiGroup = groupService.findByName(context, name); - if(uiGroup!=null) + if (uiGroup != null) + { loadedGroups= uiGroup.getMemberGroups(); + } } - if(loadedGroups==null || loadedGroups.size() ==0){ + if (loadedGroups == null || loadedGroups.size() == 0) + { loadedGroups = groupService.findAll(context, null); } // if no group selected for default set anonymous - if(groupID==null || groupID.equals("")) groupID= "0"; - // when we're just loading the main step, also default to anonymous - if (errorFlag == AccessStep.STATUS_COMPLETE) { - groupID = "0"; - } - for (Group group : loadedGroups){ - boolean selectGroup = group.getID().toString().equals(groupID); - groupSelect.addOption(selectGroup, group.getID().toString(), group.getName()); + if (groupID == null || groupID.equals("")) + { + groupID = "0"; + } + // when we're just loading the main step, also default to anonymous + if (errorFlag == AccessStep.STATUS_COMPLETE) + { + groupID = "0"; + } + for (Group group : loadedGroups) + { + boolean selectGroup = group.getID().toString().equals(groupID); + groupSelect.addOption(selectGroup, group.getID().toString(), group.getName()); } - if (errorFlag == AccessStep.STATUS_DUPLICATED_POLICY || errorFlag == AccessStep.EDIT_POLICY_STATUS_DUPLICATED_POLICY - || errorFlag == UploadWithEmbargoStep.STATUS_EDIT_POLICIES_DUPLICATED_POLICY || errorFlag == UploadWithEmbargoStep.STATUS_EDIT_POLICY_DUPLICATED_POLICY){ + if (errorFlag == AccessStep.STATUS_DUPLICATED_POLICY || + errorFlag == AccessStep.EDIT_POLICY_STATUS_DUPLICATED_POLICY || + errorFlag == UploadWithEmbargoStep.STATUS_EDIT_POLICIES_DUPLICATED_POLICY || + errorFlag == UploadWithEmbargoStep.STATUS_EDIT_POLICY_DUPLICATED_POLICY) + { groupSelect.addError(T_error_duplicated_policy); } } } - public void addAccessRadios(String selectedRadio, String date, List form, int errorFlag, DSpaceObject dso) throws WingException, SQLException { + public void addAccessRadios(String selectedRadio, String date, List form, int errorFlag, DSpaceObject dso) + throws WingException, SQLException + { - if(!isAdvancedFormEnabled){ + if (!isAdvancedFormEnabled) + { addEmbargoDateSimpleForm(dso, form, errorFlag); } - else{ - + else + { org.dspace.app.xmlui.wing.element.Item radiosAndDate = form.addItem(); Radio openAccessRadios = radiosAndDate.addRadio("open_access_radios"); openAccessRadios.setLabel(T_radios_embargo); - if(selectedRadio!=null && Integer.parseInt(selectedRadio)==RADIO_OPEN_ACCESS_ITEM_EMBARGOED - && errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE){ + if (selectedRadio != null && + Integer.parseInt(selectedRadio)==RADIO_OPEN_ACCESS_ITEM_EMBARGOED && + errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE) + { openAccessRadios.addOption(RADIO_OPEN_ACCESS_ITEM_VISIBLE, T_item_will_be_visible); openAccessRadios.addOption(true, RADIO_OPEN_ACCESS_ITEM_EMBARGOED, T_item_embargoed); } - else{ + else + { openAccessRadios.addOption(true, RADIO_OPEN_ACCESS_ITEM_VISIBLE, T_item_will_be_visible); openAccessRadios.addOption(RADIO_OPEN_ACCESS_ITEM_EMBARGOED, T_item_embargoed); } @@ -178,20 +218,25 @@ public class AccessStepUtil extends AbstractDSpaceTransformer { Text startDate = radiosAndDate.addText("embargo_until_date"); startDate.setLabel(""); startDate.setHelp(T_label_date_help); - if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_FORMAT_DATE){ + if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_FORMAT_DATE) + { startDate.addError(T_error_date_format); } - else if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_MISSING_DATE){ + else if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_MISSING_DATE) + { startDate.addError(T_error_missing_date); } - if(date!=null && errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE){ + if (date!=null && errorFlag != org.dspace.submit.step.AccessStep.STATUS_COMPLETE) + { startDate.setValue(date); } } } - public void addEmbargoDateDisplayOnly(final DSpaceObject dso, final List list) throws SQLException, WingException { + public void addEmbargoDateDisplayOnly(final DSpaceObject dso, final List list) + throws SQLException, WingException + { final Text text = list.addItem().addText("embargo"); text.setLabel(T_item_embargoed); text.setHelp(T_label_date_displayonly_help); @@ -200,8 +245,10 @@ public class AccessStepUtil extends AbstractDSpaceTransformer { } private void populateEmbargoDetail(final DSpaceObject dso, final Text text) throws SQLException, WingException { - for (final ResourcePolicy readPolicy : authorizeService.getPoliciesActionFilter(context, dso, Constants.READ)) { - if (Group.ANONYMOUS.equals(readPolicy.getGroup().getName()) && readPolicy.getStartDate() != null) { + for (final ResourcePolicy readPolicy : authorizeService.getPoliciesActionFilter(context, dso, Constants.READ)) + { + if (Group.ANONYMOUS.equals(readPolicy.getGroup().getName()) && readPolicy.getStartDate() != null) + { final String dateString = DateFormatUtils.format(readPolicy.getStartDate(), "yyyy-MM-dd"); text.setValue(dateString); globalReason = readPolicy.getRpDescription(); @@ -209,147 +256,186 @@ public class AccessStepUtil extends AbstractDSpaceTransformer { } } - public void addEmbargoDateSimpleForm(DSpaceObject dso, List form, int errorFlag) throws SQLException, WingException { + public void addEmbargoDateSimpleForm(DSpaceObject dso, List form, int errorFlag) + throws SQLException, WingException + { Text startDate = form.addItem().addText("embargo_until_date"); startDate.setLabel(T_item_embargoed); - if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_FORMAT_DATE){ + if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_FORMAT_DATE) + { startDate.addError(T_error_date_format); } - else if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_MISSING_DATE){ + else if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_MISSING_DATE) + { startDate.addError(T_error_missing_date); } - if (dso != null) { + if (dso != null) + { populateEmbargoDetail(dso, startDate); } startDate.setHelp(T_label_date_help); } - public void addTablePolicies(Division parent, DSpaceObject dso, Collection owningCollection) throws WingException, SQLException { - if (!isAdvancedFormEnabled) { - return; - } - Division div = parent.addDivision("access-existing-policies"); - div.setHead(T_head_policies_table); - div.addPara(T_policies_help.parameterize(owningCollection)); + public void addTablePolicies(Division parent, DSpaceObject dso, Collection owningCollection) + throws WingException, SQLException + { + if (!isAdvancedFormEnabled) { + return; + } + Division div = parent.addDivision("access-existing-policies"); + div.setHead(T_head_policies_table); + div.addPara(T_policies_help.parameterize(owningCollection)); - java.util.List resourcePolicies = authorizeService.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM); + java.util.List resourcePolicies = authorizeService + .findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM); - if (resourcePolicies.isEmpty()) - { - div.addPara(T_no_policies); - return; - } + if (resourcePolicies.isEmpty()) + { + div.addPara(T_no_policies); + return; + } - int cols = resourcePolicies.size(); - if(cols==0) cols=1; - Table policies = div.addTable("policies", 6, cols); - Row header = policies.addRow(Row.ROLE_HEADER); + int cols = resourcePolicies.size(); + if (cols == 0) + { + cols = 1; + } + Table policies = div.addTable("policies", 6, cols); + Row header = policies.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column0); // name - header.addCellContent(T_column1); // action - header.addCellContent(T_column2); // group - header.addCellContent(T_column3); // start_date - header.addCellContent(T_column4); // end_date + header.addCellContent(T_column0); // name + header.addCellContent(T_column1); // action + header.addCellContent(T_column2); // group + header.addCellContent(T_column3); // start_date + header.addCellContent(T_column4); // end_date - for (ResourcePolicy rp : resourcePolicies){ - int id = rp.getID(); + for (ResourcePolicy rp : resourcePolicies) + { + int id = rp.getID(); - String name = ""; - if(rp.getRpName()!=null) name=rp.getRpName(); + String name = ""; + if (rp.getRpName() != null) + { + name = rp.getRpName(); + } - String action = resourcePolicyService.getActionText(rp); + String action = resourcePolicyService.getActionText(rp); - // if it is the default policy for the Submitter don't show it. - if(dso instanceof org.dspace.content.Item){ - org.dspace.content.Item item = (org.dspace.content.Item)dso; - if(rp.getEPerson()!=null){ - if(item.getSubmitter().equals(rp.getEPerson())) - continue; - } - } + // if it is the default policy for the Submitter don't show it. + if (dso instanceof org.dspace.content.Item) + { + org.dspace.content.Item item = (org.dspace.content.Item)dso; + if (rp.getEPerson()!=null) + { + if (item.getSubmitter().equals(rp.getEPerson())) + { + continue; + } + } + } - String group = ""; - if(rp.getGroup()!=null) - group = rp.getGroup().getName(); + String group = ""; + if (rp.getGroup()!=null) + { + group = rp.getGroup().getName(); + } - Row row = policies.addRow(); + Row row = policies.addRow(); - row.addCellContent(name); - row.addCellContent(action); - row.addCellContent(group); + row.addCellContent(name); + row.addCellContent(action); + row.addCellContent(group); - // start - String startDate = ""; - if(rp.getStartDate() != null){ - startDate = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd"); - } - row.addCellContent(startDate); + // start + String startDate = ""; + if (rp.getStartDate() != null) + { + startDate = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd"); + } + row.addCellContent(startDate); - // endDate - String endDate = ""; - if(rp.getEndDate() != null){ - endDate = DateFormatUtils.format(rp.getEndDate(), "yyyy-MM-dd"); - } - row.addCellContent(endDate); + // endDate + String endDate = ""; + if (rp.getEndDate() != null) + { + endDate = DateFormatUtils.format(rp.getEndDate(), "yyyy-MM-dd"); + } + row.addCellContent(endDate); - Button edit = row.addCell().addButton("submit_edit_edit_policies_"+id); - edit.setValue(T_table_submit_edit); + Button edit = row.addCell().addButton("submit_edit_edit_policies_"+id); + edit.setValue(T_table_submit_edit); - Button delete = row.addCell().addButton("submit_delete_edit_policies_"+id); - delete.setValue(T_table_submit_delete); - } + Button delete = row.addCell().addButton("submit_delete_edit_policies_"+id); + delete.setValue(T_table_submit_delete); + } } - public void addListPolicies(List parent, DSpaceObject dso, Collection owningCollection) throws WingException, SQLException { - if (!isAdvancedFormEnabled) { - return; - } - parent.addLabel(T_head_policies_table); + public void addListPolicies(List parent, DSpaceObject dso, Collection owningCollection) + throws WingException, SQLException + { + if (!isAdvancedFormEnabled) { + return; + } + parent.addLabel(T_head_policies_table); - java.util.List resourcePolicies = authorizeService.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM); - if (resourcePolicies.isEmpty()) { - parent.addItem(T_no_policies); - return; - } + java.util.List resourcePolicies = + authorizeService.findPoliciesByDSOAndType( + context, dso, ResourcePolicy.TYPE_CUSTOM); + if (resourcePolicies.isEmpty()) + { + parent.addItem(T_no_policies); + return; + } - for (ResourcePolicy rp : resourcePolicies){ - int id = rp.getID(); + for (ResourcePolicy rp : resourcePolicies) + { + int id = rp.getID(); - String name = ""; - if(rp.getRpName()!=null) name=rp.getRpName(); + String name = ""; + if (rp.getRpName()!=null) + { + name = rp.getRpName(); + } - String action = resourcePolicyService.getActionText(rp); + String action = resourcePolicyService.getActionText(rp); - // if it is the default policy for the Submitter don't show it. - if(dso instanceof org.dspace.content.Item){ - org.dspace.content.Item item = (org.dspace.content.Item)dso; - if(rp.getEPerson() != null){ - if(item.getSubmitter().equals(rp.getEPerson())) - continue; - } - } + // if it is the default policy for the Submitter don't show it. + if (dso instanceof org.dspace.content.Item) + { + org.dspace.content.Item item = (org.dspace.content.Item)dso; + if (rp.getEPerson() != null) + { + if (item.getSubmitter().equals(rp.getEPerson())) + { + continue; + } + } + } - String group = ""; - if(rp.getGroup()!=null) - group = rp.getGroup().getName(); + String group = ""; + if (rp.getGroup()!=null) + { + group = rp.getGroup().getName(); + } - // start - String startDate = ""; - if(rp.getStartDate() != null){ - startDate = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd"); - } + // start + String startDate = ""; + if (rp.getStartDate() != null) + { + startDate = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd"); + } - // endDate - String endDate = ""; - if(rp.getEndDate() != null){ - endDate = DateFormatUtils.format(rp.getEndDate(), "yyyy-MM-dd"); - } + // endDate + String endDate = ""; + if (rp.getEndDate() != null) + { + endDate = DateFormatUtils.format(rp.getEndDate(), "yyyy-MM-dd"); + } - parent.addItem(T_policy.parameterize(name, action, group, startDate, endDate)); - } - - } + parent.addItem(T_policy.parameterize(name, action, group, startDate, endDate)); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CCLicenseStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CCLicenseStep.java index 46681d01d4..7458c3c10a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CCLicenseStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CCLicenseStep.java @@ -38,37 +38,37 @@ import org.dspace.license.service.CreativeCommonsService; import org.xml.sax.SAXException; /** - * This is an optional page of the item submission processes. The Creative - * Commons license may be added to an item in addition to the standard distribution - * license. This step will allow the user to go off to the creative commons website + * This is an optional page of the item submission processes. The Creative + * Commons license may be added to an item in addition to the standard distribution + * license. This step will allow the user to go off to the creative commons website * select a license and then when returned view what license was added to the item. *

    * This class is called by org.dspace.app.xmlui.submission.step.LicenseStep * when the Creative Commons license is enabled *

    - * The form is divided into three major divisions: 1) A global div surrounds the - * whole page, 2) a specific interactive div displays the button that goes off to the - * creative commons website to select a license, and 3) a local division that displays + * The form is divided into three major divisions: 1) A global div surrounds the + * whole page, 2) a specific interactive div displays the button that goes off to the + * creative commons website to select a license, and 3) a local division that displays * the selected license and standard action bar. - * + * * @author Scott Phillips * @author Tim Donohue (updated for Configurable Submission) * @author Wendy Bossons (updated for DSpace 1.8) */ public class CCLicenseStep extends AbstractSubmissionStep { - /** Language Strings **/ - protected static final Message T_head = + /** Language Strings **/ + protected static final Message T_head = message("xmlui.Submission.submit.CCLicenseStep.head"); protected static final Message T_select = message("xmlui.Submission.submit.CCLicenseStep.submit_choose_creative_commons"); - protected static final Message T_info1 = + protected static final Message T_info1 = message("xmlui.Submission.submit.CCLicenseStep.info1"); - protected static final Message T_submit_to_creative_commons = + protected static final Message T_submit_to_creative_commons = message("xmlui.Submission.submit.CCLicenseStep.submit_to_creative_commons"); protected static final Message T_submit_issue_creative_commons = message("xmlui.Submission.submit.CCLicenseStep.submit_issue_creative_commons"); - protected static final Message T_license = + protected static final Message T_license = message("xmlui.Submission.submit.CCLicenseStep.license"); protected static final Message T_submit_remove = message("xmlui.Submission.submit.CCLicenseStep.submit_remove"); protected static final Message T_no_license = message("xmlui.Submission.submit.CCLicenseStep.no_license"); @@ -79,147 +79,168 @@ public class CCLicenseStep extends AbstractSubmissionStep /** CC specific variables */ private String ccLocale; - protected CreativeCommonsService creativeCommonsService = LicenseServiceFactory.getInstance().getCreativeCommonsService(); + protected CreativeCommonsService creativeCommonsService = LicenseServiceFactory.getInstance().getCreativeCommonsService(); - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public CCLicenseStep() - { - this.requireSubmission = true; - this.requireStep = true; + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public CCLicenseStep() + { + this.requireSubmission = true; + this.requireStep = true; this.ccLocale = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("cc.license.locale"); /** Default locale to 'en' */ this.ccLocale = (this.ccLocale != null) ? this.ccLocale : "en"; - } - - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { - // Build the url to and from creative commons - Item item = submission.getItem(); - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; - Request request = ObjectModelHelper.getRequest(objectModel); - boolean https = request.isSecure(); - String server = request.getServerName(); - int port = request.getServerPort(); - String exitURL = (https) ? "https://" : "http://"; - exitURL += server; - if (! (port == 80 || port == 443)) - exitURL += ":"+port; - - exitURL += actionURL + "?submission-continue="+knot.getId()+"&cc_license_url=[license_url]"; - Division div = body.addInteractiveDivision("submit-cclicense", actionURL, Division.METHOD_POST, "primary submission"); - div.setHead(T_submission_head); - addSubmissionProgressList(div); - CCLookup cclookup = new CCLookup(); - HttpSession session = request.getSession(); - - // output the license selection options - String selectedLicense = request.getParameter("licenseclass_chooser"); - List list = div.addList("licenseclasslist", List.TYPE_FORM); - list.addItem(T_info1); - list.setHead(T_head); - list.addItem().addHidden("button_required"); - Select selectList = list.addItem().addSelect("licenseclass_chooser"); - selectList.setLabel(T_license); - selectList.setEvtBehavior("submitOnChange"); - Iterator iterator = cclookup.getLicenses(ccLocale).iterator(); - // build select List - first choice always 'choose a license', last always 'No license' - selectList.addOption(T_select_change.getKey(), T_select_change); - if(T_select_change.getKey().equals(selectedLicense)) { - selectList.setOptionSelected(T_select_change.getKey()); - } - while (iterator.hasNext()) { - CCLicense cclicense = iterator.next(); - selectList.addOption(cclicense.getLicenseId(), cclicense.getLicenseName()); - if (selectedLicense != null && selectedLicense.equals(cclicense.getLicenseId())) - { - selectList.setOptionSelected(cclicense.getLicenseId()); - } - } - selectList.addOption(T_no_license.getKey(), T_no_license); - if(T_no_license.getKey().equals(selectedLicense)) { - selectList.setOptionSelected(T_no_license.getKey()); - } - if (selectedLicense != null) { - // output the license fields chooser for the license class type - if (cclookup.getLicenseFields(selectedLicense, ccLocale) == null ) { - // do nothing - } - else - { - Iterator outerIterator = cclookup.getLicenseFields(selectedLicense, ccLocale).iterator(); - while (outerIterator.hasNext()) - { - CCLicenseField cclicensefield = (CCLicenseField)outerIterator.next(); - if (cclicensefield.getId().equals("jurisdiction")) - continue; - List edit = div.addList("selectlist", List.TYPE_SIMPLE, "horizontalVanilla"); - edit.addItem(cclicensefield.getLabel()); - edit.addItem().addFigure(contextPath + "/themes/Reference/images/information.png", "javascript:void(0)", cclicensefield.getDescription(), "information"); - List subList = div.addList("sublist", List.TYPE_SIMPLE, "horizontalVanilla"); - Radio radio = subList.addItem().addRadio(cclicensefield.getId() + "_chooser"); - radio.setRequired(); - Iterator fieldMapIterator = cclicensefield.getEnum().entrySet().iterator(); - while (fieldMapIterator.hasNext()) - { - Map.Entry pairs = (Map.Entry)fieldMapIterator.next(); - String key = (String) pairs.getKey(); - String value = (String) pairs.getValue(); - radio.addOption(key, value); - } - div.addSimpleHTMLFragment(true, " "); - } - } - } - Division statusDivision = div.addDivision("statusDivision"); - List statusList = statusDivision.addList("statusList", List.TYPE_FORM); - String licenseUri = creativeCommonsService.getCCField("uri").ccItemValue(item); - if (licenseUri != null) - { - statusList.addItem().addXref(licenseUri, licenseUri); - } - else - { - if (session.getAttribute("isFieldRequired") != null && - session.getAttribute("isFieldRequired").equals("TRUE") && - session.getAttribute("ccError") != null) - { - statusList.addItem().addHighlight("error").addContent(T_ccws_error.parameterize((String)session.getAttribute("ccError"))); - session.removeAttribute("ccError"); - session.removeAttribute("isFieldRequired"); - } - else if (session.getAttribute("inProgress") != null && ((String)session.getAttribute("inProgress")).equals("TRUE")) - { - statusList.addItem().addHighlight("italic").addContent(T_save_changes); - } - } - addControlButtons(statusList); - - } + } - /** + + public void addBody(Body body) throws SAXException, WingException, + UIException, SQLException, IOException, AuthorizeException + { + // Build the url to and from creative commons + Item item = submission.getItem(); + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/"+collection.getHandle() + + "/submit/" + knot.getId() + ".continue"; + Request request = ObjectModelHelper.getRequest(objectModel); + boolean https = request.isSecure(); + String server = request.getServerName(); + int port = request.getServerPort(); + String exitURL = (https) ? "https://" : "http://"; + exitURL += server; + if (! (port == 80 || port == 443)) + { + exitURL += ":"+port; + } + + exitURL += actionURL + "?submission-continue=" + knot.getId() + + "&cc_license_url=[license_url]"; + Division div = body.addInteractiveDivision("submit-cclicense", actionURL, Division.METHOD_POST, "primary submission"); + div.setHead(T_submission_head); + addSubmissionProgressList(div); + CCLookup cclookup = new CCLookup(); + HttpSession session = request.getSession(); + + // output the license selection options + String selectedLicense = request.getParameter("licenseclass_chooser"); + List list = div.addList("licenseclasslist", List.TYPE_FORM); + list.addItem(T_info1); + list.setHead(T_head); + list.addItem().addHidden("button_required"); + Select selectList = list.addItem().addSelect("licenseclass_chooser"); + selectList.setLabel(T_license); + selectList.setEvtBehavior("submitOnChange"); + Iterator iterator = cclookup.getLicenses(ccLocale).iterator(); + // build select List - first choice always 'choose a license', last always 'No license' + selectList.addOption(T_select_change.getKey(), T_select_change); + if (T_select_change.getKey().equals(selectedLicense)) + { + selectList.setOptionSelected(T_select_change.getKey()); + } + while (iterator.hasNext()) + { + CCLicense cclicense = iterator.next(); + selectList.addOption(cclicense.getLicenseId(), cclicense.getLicenseName()); + if (selectedLicense != null && + selectedLicense.equals(cclicense.getLicenseId())) + { + selectList.setOptionSelected(cclicense.getLicenseId()); + } + } + selectList.addOption(T_no_license.getKey(), T_no_license); + if (T_no_license.getKey().equals(selectedLicense)) + { + selectList.setOptionSelected(T_no_license.getKey()); + } + if (selectedLicense != null) + { + // output the license fields chooser for the license class type + if (cclookup.getLicenseFields(selectedLicense, ccLocale) == null ) + { + // do nothing + } + else + { + Iterator outerIterator = cclookup.getLicenseFields( + selectedLicense, ccLocale).iterator(); + while (outerIterator.hasNext()) + { + CCLicenseField cclicensefield = (CCLicenseField)outerIterator.next(); + if (cclicensefield.getId().equals("jurisdiction")) + { + continue; + } + List edit = div.addList("selectlist", List.TYPE_SIMPLE, "horizontalVanilla"); + edit.addItem(cclicensefield.getLabel()); + edit.addItem().addFigure(contextPath + + "/themes/Reference/images/information.png", + "javascript:void(0)", cclicensefield.getDescription(), + "information"); + List subList = div.addList("sublist", List.TYPE_SIMPLE, + "horizontalVanilla"); + Radio radio = subList.addItem() + .addRadio(cclicensefield.getId() + "_chooser"); + radio.setRequired(); + Iterator fieldMapIterator = + cclicensefield.getEnum().entrySet().iterator(); + while (fieldMapIterator.hasNext()) + { + Map.Entry pairs = (Map.Entry)fieldMapIterator.next(); + String key = (String) pairs.getKey(); + String value = (String) pairs.getValue(); + radio.addOption(key, value); + } + div.addSimpleHTMLFragment(true, " "); + } + } + } + Division statusDivision = div.addDivision("statusDivision"); + List statusList = statusDivision.addList("statusList", List.TYPE_FORM); + String licenseUri = creativeCommonsService.getCCField("uri").ccItemValue(item); + if (licenseUri != null) + { + statusList.addItem().addXref(licenseUri, licenseUri); + } + else + { + if (session.getAttribute("isFieldRequired") != null && + session.getAttribute("isFieldRequired").equals("TRUE") && + session.getAttribute("ccError") != null) + { + statusList.addItem().addHighlight("error").addContent( + T_ccws_error.parameterize((String)session.getAttribute("ccError"))); + session.removeAttribute("ccError"); + session.removeAttribute("isFieldRequired"); + } + else if (session.getAttribute("inProgress") != null && + ((String)session.getAttribute("inProgress")).equals("TRUE")) + { + statusList.addItem().addHighlight("italic").addContent( + T_save_changes); + } + } + addControlButtons(statusList); + } + + /** * Each submission step must define its own information to be reviewed * during the final Review/Verify Step in the submission process. *

    - * The information to review should be tacked onto the passed in + * The information to review should be tacked onto the passed in * List object. *

    * NOTE: To remain consistent across all Steps, you should first * add a sub-List object (with this step's name as the heading), * by using a call to reviewList.addList(). This sublist is * the list you return from this method! - * + * * @param reviewList * The List to which all reviewable information should be added - * @return + * @return * The new sub-List object created by this step, which contains * all the reviewable information. If this step has nothing to - * review, then return null! + * review, then return null! */ public List addReviewSection(List reviewList) throws SAXException, WingException, UIException, SQLException, IOException, @@ -228,13 +249,13 @@ public class CCLicenseStep extends AbstractSubmissionStep //nothing to review for CC License step return null; } - - - /** - * Recycle - */ - public void recycle() - { - super.recycle(); - } + + + /** + * Recycle + */ + public void recycle() + { + super.recycle(); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CompletedStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CompletedStep.java index 472443bc78..cbd54e897f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CompletedStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/CompletedStep.java @@ -32,37 +32,40 @@ import org.xml.sax.SAXException; public class CompletedStep extends AbstractSubmissionStep { - /** Language Strings **/ - protected static final Message T_head = + /** Language Strings **/ + protected static final Message T_head = message("xmlui.Submission.submit.CompletedStep.head"); - protected static final Message T_info1 = + protected static final Message T_info1 = message("xmlui.Submission.submit.CompletedStep.info1"); protected static final Message T_go_submission = message("xmlui.Submission.submit.CompletedStep.go_submission"); - protected static final Message T_submit_again = + protected static final Message T_submit_again = message("xmlui.Submission.submit.CompletedStep.submit_again"); - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public CompletedStep() - { - this.requireHandle = true; - } + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public CompletedStep() + { + this.requireHandle = true; + } - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { - Division div = body.addInteractiveDivision("submit-complete",contextPath+"/handle/"+handle+"/submit", Division.METHOD_POST,"primary submission"); - div.setHead(T_head); - - div.addPara(T_info1); - - div.addPara().addXref(contextPath+"/submissions",T_go_submission); - - div.addPara().addButton("submit_again").setValue(T_submit_again); - div.addHidden("handle").setValue(handle); - } + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + Division div = body.addInteractiveDivision("submit-complete", + contextPath + "/handle/" + handle + "/submit", Division.METHOD_POST, + "primary submission"); + div.setHead(T_head); + + div.addPara(T_info1); + + div.addPara().addXref(contextPath + "/submissions", T_go_submission); + + div.addPara().addButton("submit_again").setValue(T_submit_again); + div.addHidden("handle").setValue(handle); + } /** * Each submission step must define its own information to be reviewed @@ -83,9 +86,9 @@ public class CompletedStep extends AbstractSubmissionStep * all the reviewable information. If this step has nothing to * review, then return null! */ - public List addReviewSection(List reviewList) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public List addReviewSection(List reviewList) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { //nothing to review, since submission is now Completed! return null; diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditBitstreamPolicies.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditBitstreamPolicies.java index b4a774305b..8b38d445fa 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditBitstreamPolicies.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditBitstreamPolicies.java @@ -29,39 +29,43 @@ import java.util.Map; public class EditBitstreamPolicies extends AbstractStep { - /** Language Strings **/ + /** Language Strings **/ protected static final Message T_head =message("xmlui.Submission.submit.EditBitstreamPolicies.head"); protected static final Message T_submit_save = message("xmlui.general.save"); protected static final Message T_submit_add_policy = message("xmlui.Submission.submit.AccessStep.submit_add_policy"); /** - * Establish our required parameters, abstractStep will enforce these. - */ - public EditBitstreamPolicies() - { - this.requireSubmission = true; - this.requireStep = true; - } + * Establish our required parameters, abstractStep will enforce these. + */ + public EditBitstreamPolicies() + { + this.requireSubmission = true; + this.requireStep = true; + } - /** - * Get the bitstream we are editing - */ - public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) - throws ProcessingException, SAXException, IOException - { - super.setup(resolver,objectModel,src,parameters); - } + /** + * Get the bitstream we are editing + */ + public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver,objectModel,src,parameters); + } - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException{ + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + String actionURL = contextPath + "/handle/" + collection.getHandle() + + "/submit/" + knot.getId() + ".continue"; Request request = ObjectModelHelper.getRequest(objectModel); - Division div = body.addInteractiveDivision("submit-edit-bitstream-policy", actionURL, Division.METHOD_POST, "primary submission"); + Division div = body.addInteractiveDivision("submit-edit-bitstream-policy", + actionURL, Division.METHOD_POST, "primary submission"); div.setHead(T_submission_head); addSubmissionProgressList(div); @@ -76,16 +80,21 @@ public class EditBitstreamPolicies extends AbstractStep asu.addListGroups(request.getParameter("group_id"), form, errorFlag, collection); // radio buttons: Item will be visible / Embargo Access + date - asu.addAccessRadios(request.getParameter("open_access_radios"), request.getParameter("embargo_until_date"), form, errorFlag, submissionInfo.getBitstream()); + asu.addAccessRadios(request.getParameter("open_access_radios"), + request.getParameter("embargo_until_date"), form, errorFlag, + submissionInfo.getBitstream()); - asu.addName(request.getParameter("name"), form, errorFlag); + asu.addName(request.getParameter("name"), form, errorFlag); // Reason asu.addReason(request.getParameter("reason"), form, errorFlag); // Add Policy Button - boolean isAdvancedFormEnabled= DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.submission.restrictstep.enableAdvancedForm", false); - if(isAdvancedFormEnabled){ + boolean isAdvancedFormEnabled = DSpaceServicesFactory.getInstance() + .getConfigurationService().getBooleanProperty( + "webui.submission.restrictstep.enableAdvancedForm", false); + if (isAdvancedFormEnabled) + { Button addPolicy = form.addItem().addButton(org.dspace.submit.step.AccessStep.FORM_ACCESS_BUTTON_ADD); addPolicy.setValue(T_submit_add_policy); } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditFileStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditFileStep.java index b04ed7a1f5..e50c231064 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditFileStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditFileStep.java @@ -50,8 +50,8 @@ import org.xml.sax.SAXException; */ public class EditFileStep extends AbstractStep { - - /** Language Strings **/ + + /** Language Strings **/ protected static final Message T_head = message("xmlui.Submission.submit.EditFileStep.head"); protected static final Message T_file = @@ -80,55 +80,57 @@ public class EditFileStep extends AbstractStep message("xmlui.general.cancel"); /** The bitstream we are editing */ - private Bitstream bitstream; + private Bitstream bitstream; protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService(); - - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public EditFileStep() - { - this.requireSubmission = true; - this.requireStep = true; - } - - - /** - * Get the bitstream we are editing - */ - public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) - throws ProcessingException, SAXException, IOException - { - super.setup(resolver,objectModel,src,parameters); - - //the bitstream should be stored in our Submission Info object + + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public EditFileStep() + { + this.requireSubmission = true; + this.requireStep = true; + } + + + /** + * Get the bitstream we are editing + */ + public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver,objectModel,src,parameters); + + //the bitstream should be stored in our Submission Info object this.bitstream = submissionInfo.getBitstream(); - } + } - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/" + collection.getHandle() + + "/submit/" + knot.getId() + ".continue"; - // Get the bitstream and all the various formats - BitstreamFormat currentFormat = bitstream.getFormat(context); + // Get the bitstream and all the various formats + BitstreamFormat currentFormat = bitstream.getFormat(context); BitstreamFormat guessedFormat = bitstreamFormatService.guessFormat(context, bitstream); - java.util.List bitstreamFormats = bitstreamFormatService.findNonInternal(context); - + java.util.List bitstreamFormats = bitstreamFormatService.findNonInternal(context); + UUID itemID = submissionInfo.getSubmissionItem().getItem().getID(); - String fileUrl = contextPath + "/bitstream/item/" + itemID + "/" + bitstream.getName(); - String fileName = bitstream.getName(); - - // Build the form that describes an item. - Division div = body.addInteractiveDivision("submit-edit-file", actionURL, Division.METHOD_POST, "primary submission"); - div.setHead(T_submission_head); - addSubmissionProgressList(div); - - List edit = div.addList("submit-edit-file", List.TYPE_FORM); + String fileUrl = contextPath + "/bitstream/item/" + itemID + "/" + bitstream.getName(); + String fileName = bitstream.getName(); + + // Build the form that describes an item. + Division div = body.addInteractiveDivision("submit-edit-file", actionURL, Division.METHOD_POST, "primary submission"); + div.setHead(T_submission_head); + addSubmissionProgressList(div); + + List edit = div.addList("submit-edit-file", List.TYPE_FORM); edit.setHead(T_head); edit.addLabel(T_file); @@ -152,8 +154,8 @@ public class EditFileStep extends AbstractStep edit.addItem(T_info1); if (guessedFormat != null) { - edit.addLabel(T_format_detected); - edit.addItem(guessedFormat.getShortDescription()); + edit.addLabel(T_format_detected); + edit.addItem(guessedFormat.getShortDescription()); } // System supported formats @@ -163,31 +165,32 @@ public class EditFileStep extends AbstractStep format.addOption(-1,T_format_default); for (BitstreamFormat bitstreamFormat : bitstreamFormats) { - String supportLevel = "Unknown"; - if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN) + String supportLevel = "Unknown"; + if (bitstreamFormat.getSupportLevel() == BitstreamFormat.KNOWN) { supportLevel = "known"; } - else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED) + else if (bitstreamFormat.getSupportLevel() == BitstreamFormat.SUPPORTED) { supportLevel = "Supported"; } - String name = bitstreamFormat.getShortDescription()+" ("+supportLevel+")"; - int id = bitstreamFormat.getID(); + String name = bitstreamFormat.getShortDescription() + + " ("+supportLevel+")"; + int id = bitstreamFormat.getID(); - format.addOption(id,name); + format.addOption(id,name); } if (currentFormat != null) { - format.setOptionSelected(currentFormat.getID()); + format.setOptionSelected(currentFormat.getID()); } else if (guessedFormat != null) { - format.setOptionSelected(guessedFormat.getID()); + format.setOptionSelected(guessedFormat.getID()); } else { - format.setOptionSelected(-1); + format.setOptionSelected(-1); } edit.addItem(T_info2); @@ -204,7 +207,7 @@ public class EditFileStep extends AbstractStep // Note, not standard control actions, this page just goes back to the upload step. org.dspace.app.xmlui.wing.element.Item actions = edit.addItem(); actions.addButton("submit_save").setValue(T_submit_save); - actions.addButton("submit_edit_cancel").setValue(T_submit_cancel); + actions.addButton("submit_edit_cancel").setValue(T_submit_cancel); } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditPolicyStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditPolicyStep.java index c09c26c583..0f14196721 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditPolicyStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/EditPolicyStep.java @@ -31,43 +31,47 @@ import java.util.Map; public class EditPolicyStep extends AbstractStep { - /** Language Strings **/ + /** Language Strings **/ protected static final Message T_head =message("xmlui.Submission.submit.EditPolicyStep.head"); protected static final Message T_submit_save = message("xmlui.general.save"); protected static final Message T_submit_cancel =message("xmlui.general.cancel"); - private ResourcePolicy resourcePolicy; + private ResourcePolicy resourcePolicy; private Bitstream bitstream; - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public EditPolicyStep() - { - this.requireSubmission = true; - this.requireStep = true; - } - - - /** - * Get the bitstream we are editing - */ - public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) - throws ProcessingException, SAXException, IOException - { - super.setup(resolver,objectModel,src,parameters); - this.resourcePolicy = (ResourcePolicy) submissionInfo.get(org.dspace.submit.step.AccessStep.SUB_INFO_SELECTED_RP); - this.bitstream=submissionInfo.getBitstream(); - } + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public EditPolicyStep() + { + this.requireSubmission = true; + this.requireStep = true; + } - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException{ + + /** + * Get the bitstream we are editing + */ + public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver,objectModel,src,parameters); + this.resourcePolicy = (ResourcePolicy) submissionInfo.get(org.dspace.submit.step.AccessStep.SUB_INFO_SELECTED_RP); + this.bitstream=submissionInfo.getBitstream(); + } + + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; - Division div = body.addInteractiveDivision("submit-edit-policy", actionURL, Division.METHOD_POST, "primary submission"); + String actionURL = contextPath + "/handle/" + collection.getHandle() + + "/submit/" + knot.getId() + ".continue"; + Division div = body.addInteractiveDivision("submit-edit-policy", + actionURL, Division.METHOD_POST, "primary submission"); div.setHead(T_submission_head); addSubmissionProgressList(div); List edit = div.addList("submit-edit-file", List.TYPE_FORM); @@ -76,8 +80,10 @@ public class EditPolicyStep extends AbstractStep div.addHidden("policy_id").setValue(resourcePolicy.getID()); // if come from EditBitstreamPolicies - if(bitstream!=null) + if (bitstream!=null) + { div.addHidden("bitstream_id").setValue(bitstream.getID().toString()); + } AccessStepUtil asu = new AccessStepUtil(context); @@ -85,17 +91,20 @@ public class EditPolicyStep extends AbstractStep // radio buttons: Item will be visible / Embargo Access + date String selectedRadio=Integer.toString(AccessStep.RADIO_OPEN_ACCESS_ITEM_VISIBLE); - if(resourcePolicy.getStartDate()!=null) + if (resourcePolicy.getStartDate()!=null) + { selectedRadio = Integer.toString(AccessStep.RADIO_OPEN_ACCESS_ITEM_EMBARGOED); + } // this step is possible only in case of AdvancedForm String dateValue = ""; - if(resourcePolicy.getStartDate() != null){ + if (resourcePolicy.getStartDate() != null) + { dateValue = DateFormatUtils.format(resourcePolicy.getStartDate(), "yyyy-MM-dd"); } asu.addAccessRadios(selectedRadio, dateValue, edit, errorFlag, null); - asu.addName(resourcePolicy.getRpName(), edit, errorFlag); + asu.addName(resourcePolicy.getRpName(), edit, errorFlag); // Reason asu.addReason(resourcePolicy.getRpDescription(), edit, errorFlag); @@ -103,6 +112,6 @@ public class EditPolicyStep extends AbstractStep // Note, not standard control actions, this page just goes back to the upload step. org.dspace.app.xmlui.wing.element.Item actions = edit.addItem(); actions.addButton(org.dspace.submit.step.AccessStep.FORM_EDIT_BUTTON_SAVE).setValue(T_submit_save); - actions.addButton(org.dspace.submit.step.AccessStep.FORM_EDIT_BUTTON_CANCEL).setValue(T_submit_cancel); + actions.addButton(org.dspace.submit.step.AccessStep.FORM_EDIT_BUTTON_CANCEL).setValue(T_submit_cancel); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/InitialQuestionsStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/InitialQuestionsStep.java index f941315f69..b87f9cde3e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/InitialQuestionsStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/InitialQuestionsStep.java @@ -36,258 +36,259 @@ import org.xml.sax.SAXException; * that there may be multiple titles and then later comes back and unchecks * then multiple titles box. In this case these metadata entries are removed * from the item, a note is displayed informing the user of this discrepency. - * + * * Questions: * - Multiple titles * - Published Before - * + * * @author Scott Phillips * @author Tim Donohue (updated for Configurable Submission) */ public class InitialQuestionsStep extends AbstractSubmissionStep { - /** Language Strings **/ - protected static final Message T_head= + /** Language Strings **/ + protected static final Message T_head = message("xmlui.Submission.submit.InitialQuestionsStep.head"); - protected static final Message T_important_note= + protected static final Message T_important_note = message("xmlui.Submission.submit.InitialQuestionsStep.important_note"); - protected static final Message T_and= + protected static final Message T_and = message("xmlui.Submission.submit.InitialQuestionsStep.and"); - protected static final Message T_separator = + protected static final Message T_separator = message("xmlui.Submission.submit.InitialQuestionsStep.separator"); - protected static final Message T_open= + protected static final Message T_open = message("xmlui.Submission.submit.InitialQuestionsStep.open_set"); - protected static final Message T_close= + protected static final Message T_close = message("xmlui.Submission.submit.InitialQuestionsStep.close_set"); - protected static final Message T_multiple_titles= + protected static final Message T_multiple_titles = message("xmlui.Submission.submit.InitialQuestionsStep.multiple_titles"); - protected static final Message T_multiple_titles_help= + protected static final Message T_multiple_titles_help = message("xmlui.Submission.submit.InitialQuestionsStep.multiple_titles_help"); - protected static final Message T_multiple_titles_note= + protected static final Message T_multiple_titles_note = message("xmlui.Submission.submit.InitialQuestionsStep.multiple_titles_note"); - protected static final Message T_published_before= + protected static final Message T_published_before = message("xmlui.Submission.submit.InitialQuestionsStep.published_before"); - protected static final Message T_published_before_help= + protected static final Message T_published_before_help = message("xmlui.Submission.submit.InitialQuestionsStep.published_before_help"); - protected static final Message T_published_before_note= + protected static final Message T_published_before_note = message("xmlui.Submission.submit.InitialQuestionsStep.published_before_note"); - protected static final Message T_date_issued= + protected static final Message T_date_issued = message("xmlui.Submission.submit.InitialQuestionsStep.date_issued"); - protected static final Message T_citation= + protected static final Message T_citation = message("xmlui.Submission.submit.InitialQuestionsStep.citation"); - protected static final Message T_publisher= + protected static final Message T_publisher = message("xmlui.Submission.submit.InitialQuestionsStep.publisher"); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); /** - * Establish our required parameters, abstractStep will enforce these. - */ - public InitialQuestionsStep() - { - this.requireSubmission = true; - this.requireStep = true; - } - - - public void addBody(Body body) throws SAXException, WingException, + * Establish our required parameters, abstractStep will enforce these. + */ + public InitialQuestionsStep() + { + this.requireSubmission = true; + this.requireStep = true; + } + + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { - // Get any metadata that may be removed by unselecting one of these options. - Item item = submission.getItem(); - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + // Get any metadata that may be removed by unselecting one of these options. + Item item = submission.getItem(); + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + + java.util.List titles = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "title", "alternative", Item.ANY); - java.util.List titles = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "title", "alternative", Item.ANY); - java.util.List dateIssued = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "date", "issued", Item.ANY); java.util.List citation = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "identifier", "citation", Item.ANY); java.util.List publisher = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "publisher", null, Item.ANY); - - - // Generate a from asking the user two questions: multiple + + + // Generate a from asking the user two questions: multiple // titles & published before. - Division div = body.addInteractiveDivision("submit-initial-questions", actionURL, Division.METHOD_POST, "primary submission"); - div.setHead(T_submission_head); - addSubmissionProgressList(div); - - List form = div.addList("submit-initial-questions", List.TYPE_FORM); - form.setHead(T_head); - + Division div = body.addInteractiveDivision("submit-initial-questions", actionURL, Division.METHOD_POST, "primary submission"); + div.setHead(T_submission_head); + addSubmissionProgressList(div); + + List form = div.addList("submit-initial-questions", List.TYPE_FORM); + form.setHead(T_head); + CheckBox multipleTitles = form.addItem().addCheckBox("multiple_titles"); multipleTitles.setLabel(T_multiple_titles); multipleTitles.setHelp(T_multiple_titles_help); multipleTitles.addOption("true"); if (submission.hasMultipleTitles()) { - multipleTitles.setOptionSelected("true"); + multipleTitles.setOptionSelected("true"); } - - // If any titles would be removed if the user unselected this box then + + // If any titles would be removed if the user unselected this box then // warn the user! if (titles.size() > 0) { - org.dspace.app.xmlui.wing.element.Item note = form.addItem(); - note.addHighlight("bold").addContent(T_important_note); - note.addContent(T_multiple_titles_note); - for (int i=0; i< titles.size(); i++) - { - if (i > 0) + org.dspace.app.xmlui.wing.element.Item note = form.addItem(); + note.addHighlight("bold").addContent(T_important_note); + note.addContent(T_multiple_titles_note); + for (int i=0; i< titles.size(); i++) + { + if (i > 0) { note.addContent(T_separator); } - note.addContent("\""); - note.addHighlight("bold").addContent(titles.get(i).getValue()); - note.addContent("\""); - } + note.addContent("\""); + note.addHighlight("bold").addContent(titles.get(i).getValue()); + note.addContent("\""); + } } - + CheckBox publishedBefore = form.addItem().addCheckBox("published_before"); publishedBefore.setLabel(T_published_before); publishedBefore.setHelp(T_published_before_help); publishedBefore.addOption("true"); if (submission.isPublishedBefore()) { - publishedBefore.setOptionSelected("true"); + publishedBefore.setOptionSelected("true"); } - - // If any metadata would be removed if the user unselected the box then warn + + // If any metadata would be removed if the user unselected the box then warn // the user about what will be removed. if (dateIssued.size() > 0 || citation.size() > 0 || publisher.size() > 0) { - org.dspace.app.xmlui.wing.element.Item note = form.addItem(); - note.addHighlight("bold").addContent(T_important_note); - note.addContent(T_published_before_note); - - // Start a convoluted processes to build an english list of values. - // Format: Date Issued (value, value, value), Citation (value, value, value), Publisher (value, value, value) - if (dateIssued.size() > 0) - { - note.addHighlight("bold").addContent(T_date_issued); - note.addContent(T_open); - for (int i=0; i< dateIssued.size(); i++) - { - if (i > 0) + org.dspace.app.xmlui.wing.element.Item note = form.addItem(); + note.addHighlight("bold").addContent(T_important_note); + note.addContent(T_published_before_note); + + // Start a convoluted processes to build an english list of values. + // Format: Date Issued (value, value, value), Citation (value, value, value), Publisher (value, value, value) + if (dateIssued.size() > 0) + { + note.addHighlight("bold").addContent(T_date_issued); + note.addContent(T_open); + for (int i=0; i< dateIssued.size(); i++) + { + if (i > 0) { note.addContent(T_separator); } - note.addContent(dateIssued.get(i).getValue()); - } - note.addContent(T_close); - } - - // Conjunction - if (dateIssued.size() > 0 && (citation.size() > 0 || publisher.size() > 0)) + note.addContent(dateIssued.get(i).getValue()); + } + note.addContent(T_close); + } + + // Conjunction + if (dateIssued.size() > 0 && (citation.size() > 0 || publisher.size() > 0)) { note.addContent(T_separator); } - - if (dateIssued.size() > 0 && citation.size() > 0 && publisher.size() == 0) - { - note.addContent(T_and); - } - - // Citation - if (citation.size() > 0) - { - note.addHighlight("bold").addContent(T_citation); - note.addContent(T_open); - for (int i=0; i< citation.size(); i++) - { - if (i > 0) + + if (dateIssued.size() > 0 && citation.size() > 0 && publisher.size() == 0) + { + note.addContent(T_and); + } + + // Citation + if (citation.size() > 0) + { + note.addHighlight("bold").addContent(T_citation); + note.addContent(T_open); + for (int i=0; i< citation.size(); i++) + { + if (i > 0) { note.addContent(T_separator); } - note.addContent(citation.get(i).getValue()); - } - note.addContent(T_close); - } - - - // Conjunction - if (citation.size() > 0 && publisher.size() > 0) - { - note.addContent(T_separator); - } - - if ((dateIssued.size() > 0 || citation.size() > 0) && publisher.size() > 0) - { - note.addContent(T_and); - } - - - // Publisher - if (publisher.size() > 0) - { - note.addHighlight("bold").addContent(T_publisher); - note.addContent(T_open); - for (int i=0; i< publisher.size(); i++) - { - if (i > 0) + note.addContent(citation.get(i).getValue()); + } + note.addContent(T_close); + } + + + // Conjunction + if (citation.size() > 0 && publisher.size() > 0) + { + note.addContent(T_separator); + } + + if ((dateIssued.size() > 0 || citation.size() > 0) && publisher.size() > 0) + { + note.addContent(T_and); + } + + + // Publisher + if (publisher.size() > 0) + { + note.addHighlight("bold").addContent(T_publisher); + note.addContent(T_open); + for (int i=0; i< publisher.size(); i++) + { + if (i > 0) { note.addContent(T_separator); } - note.addContent(publisher.get(i).getValue()); - } - note.addContent(T_close); - } + note.addContent(publisher.get(i).getValue()); + } + note.addContent(T_close); + } } - + //add standard control/paging buttons addControlButtons(form); - + //Since we already warn users about the metadata pruning to happen //if they uncheck an already checked box, then //we can let the prune process occur immediately! div.addHidden("prune").setValue("true"); - + } - - /** + + /** * Each submission step must define its own information to be reviewed * during the final Review/Verify Step in the submission process. *

    - * The information to review should be tacked onto the passed in + * The information to review should be tacked onto the passed in * List object. *

    * NOTE: To remain consistent across all Steps, you should first * add a sub-List object (with this step's name as the heading), * by using a call to reviewList.addList(). This sublist is * the list you return from this method! - * + * * @param reviewList * The List to which all reviewable information should be added - * @return + * @return * The new sub-List object created by this step, which contains * all the reviewable information. If this step has nothing to - * review, then return null! + * review, then return null! */ - public List addReviewSection(List reviewList) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public List addReviewSection(List reviewList) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { //Create a new section for this Initial Questions information List initSection = reviewList.addList("submit-review-" + this.stepAndPage, List.TYPE_FORM); initSection.setHead(T_head); - + //add information to review Message multipleTitles = ReviewStep.T_no; if (submission.hasMultipleTitles()) { multipleTitles = ReviewStep.T_yes; } - + Message publishedBefore = ReviewStep.T_no; if (submission.isPublishedBefore()) { publishedBefore = ReviewStep.T_yes; } - + initSection.addLabel(T_multiple_titles); initSection.addItem(multipleTitles); initSection.addLabel(T_published_before); initSection.addItem(publishedBefore); - + //return this new review section return initSection; } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/LicenseStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/LicenseStep.java index 92cb0f5341..abef64b5c1 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/LicenseStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/LicenseStep.java @@ -30,117 +30,116 @@ import org.xml.sax.SAXException; * step the user must agree to the collection's standard distribution * license. If the user can not agree to the license they they may either * save the submission until a later time or remove the submission completely. - * + * * This step will include the full license text inside the page using the * HTML fragment method. - * - * + * + * * @author Scott Phillips * @author Tim Donohue (updated for Configurable Submission) */ public class LicenseStep extends AbstractSubmissionStep { private static final Logger log = Logger.getLogger(LicenseStep.class); - + /** Language Strings **/ - protected static final Message T_head = + protected static final Message T_head = message("xmlui.Submission.submit.LicenseStep.head"); - protected static final Message T_info1 = + protected static final Message T_info1 = message("xmlui.Submission.submit.LicenseStep.info1"); - protected static final Message T_info2 = + protected static final Message T_info2 = message("xmlui.Submission.submit.LicenseStep.info2"); - protected static final Message T_info3 = + protected static final Message T_info3 = message("xmlui.Submission.submit.LicenseStep.info3"); - protected static final Message T_decision_label = + protected static final Message T_decision_label = message("xmlui.Submission.submit.LicenseStep.decision_label"); - protected static final Message T_decision_checkbox = + protected static final Message T_decision_checkbox = message("xmlui.Submission.submit.LicenseStep.decision_checkbox"); - protected static final Message T_decision_error = + protected static final Message T_decision_error = message("xmlui.Submission.submit.LicenseStep.decision_error"); - protected static final Message T_submit_remove = + protected static final Message T_submit_remove = message("xmlui.Submission.submit.LicenseStep.submit_remove"); - protected static final Message T_submit_complete = + protected static final Message T_submit_complete = message("xmlui.Submission.submit.LicenseStep.submit_complete"); - - + /** - * Establish our required parameters, abstractStep will enforce these. - */ - public LicenseStep() - { - this.requireSubmission = true; - this.requireStep = true; - } + * Establish our required parameters, abstractStep will enforce these. + */ + public LicenseStep() + { + this.requireSubmission = true; + this.requireStep = true; + } - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { - // Get the full text for the actual licese - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; - String licenseText = LicenseUtils.getLicenseText(context - .getCurrentLocale(), collection, submission.getItem(), - submission.getSubmitter()); - - Division div = body.addInteractiveDivision("submit-license",actionURL, Division.METHOD_POST,"primary submission"); - div.setHead(T_submission_head); - addSubmissionProgressList(div); - - Division inner = div.addDivision("submit-license-inner"); - inner.setHead(T_head); - inner.addPara(T_info1); - inner.addPara(T_info2); - - - // Add the actual text of the license: - Division displayLicense = inner.addDivision("submit-license-standard-text","license-text"); - displayLicense.addSimpleHTMLFragment(true, licenseText); - - inner.addPara(T_info3); - - List controls = inner.addList("submit-review", List.TYPE_FORM); - - CheckBox decision = controls.addItem().addCheckBox("decision"); - decision.setLabel(T_decision_label); - decision.addOption("accept",T_decision_checkbox); + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + // Get the full text for the actual licese + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/" + collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + String licenseText = LicenseUtils.getLicenseText(context + .getCurrentLocale(), collection, submission.getItem(), + submission.getSubmitter()); - // If user did not check the "I accept" checkbox - if(this.errorFlag==org.dspace.submit.step.LicenseStep.STATUS_LICENSE_REJECTED) - { - log.info(LogManager.getHeader(context, "reject_license", submissionInfo.getSubmissionLogInfo())); - - decision.addError(T_decision_error); - } - - // add standard control/paging buttons - addControlButtons(controls); - } - - /** + Division div = body.addInteractiveDivision("submit-license", actionURL, Division.METHOD_POST, "primary submission"); + div.setHead(T_submission_head); + addSubmissionProgressList(div); + + Division inner = div.addDivision("submit-license-inner"); + inner.setHead(T_head); + inner.addPara(T_info1); + inner.addPara(T_info2); + + + // Add the actual text of the license: + Division displayLicense = inner.addDivision("submit-license-standard-text", "license-text"); + displayLicense.addSimpleHTMLFragment(true, licenseText); + + inner.addPara(T_info3); + + List controls = inner.addList("submit-review", List.TYPE_FORM); + + CheckBox decision = controls.addItem().addCheckBox("decision"); + decision.setLabel(T_decision_label); + decision.addOption("accept",T_decision_checkbox); + + // If user did not check the "I accept" checkbox + if (this.errorFlag==org.dspace.submit.step.LicenseStep.STATUS_LICENSE_REJECTED) + { + log.info(LogManager.getHeader(context, "reject_license", submissionInfo.getSubmissionLogInfo())); + + decision.addError(T_decision_error); + } + + // add standard control/paging buttons + addControlButtons(controls); + } + + /** * Each submission step must define its own information to be reviewed * during the final Review/Verify Step in the submission process. *

    - * The information to review should be tacked onto the passed in + * The information to review should be tacked onto the passed in * List object. *

    * NOTE: To remain consistent across all Steps, you should first * add a sub-List object (with this step's name as the heading), * by using a call to reviewList.addList(). This sublist is * the list you return from this method! - * + * * @param reviewList * The List to which all reviewable information should be added - * @return + * @return * The new sub-List object created by this step, which contains * all the reviewable information. If this step has nothing to - * review, then return null! + * review, then return null! */ - public List addReviewSection(List reviewList) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public List addReviewSection(List reviewList) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { // License step doesn't require reviewing return null; diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemoveSubmissionsAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemoveSubmissionsAction.java index 41b77e71cb..c9f852e72a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemoveSubmissionsAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemoveSubmissionsAction.java @@ -22,16 +22,16 @@ import org.dspace.content.service.WorkspaceItemService; import org.dspace.core.Context; /** - * Remove all selected submissions. This action is used by the - * submission page, the user may check each unfinished submission - * and when he clicks the remove submissions button this action - * will remove them all. - * + * Remove all selected submissions. This action is used by the + * submission page, the user may check each unfinished submission + * and when he clicks the remove submissions button this action + * will remove them all. + * * @author Scott Phillips */ public class RemoveSubmissionsAction extends AbstractAction { - protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); + protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); /** * Remove all selected submissions. @@ -47,26 +47,26 @@ public class RemoveSubmissionsAction extends AbstractAction */ @Override public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, - String source, Parameters parameters) throws Exception + String source, Parameters parameters) + throws Exception { - + Context context = ContextUtil.obtainContext(objectModel); Request request = ObjectModelHelper.getRequest(objectModel); - - - String[] workspaceIDs = request.getParameterValues("workspaceID"); - - if (workspaceIDs != null) - { - for (String workspaceID : workspaceIDs) - { - // If they selected to remove the item then delete everything. - WorkspaceItem workspaceItem = workspaceItemService.find(context, Integer.valueOf(workspaceID)); - workspaceItemService.deleteAll(context, workspaceItem); - } - } - + + + String[] workspaceIDs = request.getParameterValues("workspaceID"); + + if (workspaceIDs != null) + { + for (String workspaceID : workspaceIDs) + { + // If they selected to remove the item then delete everything. + WorkspaceItem workspaceItem = workspaceItemService.find(context, Integer.valueOf(workspaceID)); + workspaceItemService.deleteAll(context, workspaceItem); + } + } + return null; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemovedStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemovedStep.java index 68a208a624..9ef7652f82 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemovedStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/RemovedStep.java @@ -24,31 +24,29 @@ import org.xml.sax.SAXException; * successfully removed their submission. *

    * As such, it's not a true "step" in the submission process - * + * * @author Scott Phillips */ public class RemovedStep extends AbstractStep { - /** Language Strings **/ - protected static final Message T_head = + /** Language Strings **/ + protected static final Message T_head = message("xmlui.Submission.submit.RemovedStep.head"); - protected static final Message T_info1 = + protected static final Message T_info1 = message("xmlui.Submission.submit.RemovedStep.info1"); - protected static final Message T_go_submissions = + protected static final Message T_go_submissions = message("xmlui.Submission.submit.RemovedStep.go_submission"); - - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { - Division div = body.addInteractiveDivision("submit-removed",contextPath+"/submit", Division.METHOD_POST,"primary submission"); - - div.setHead(T_head); - - div.addPara(T_info1); - - div.addPara().addXref(contextPath+"/submissions",T_go_submissions); - } + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + Division div = body.addInteractiveDivision("submit-removed", + contextPath + "/submit", Division.METHOD_POST, "primary submission"); + div.setHead(T_head); + div.addPara(T_info1); + div.addPara().addXref(contextPath+"/submissions",T_go_submissions); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ResumeStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ResumeStep.java index 29e4a46f36..8c89540be9 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ResumeStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ResumeStep.java @@ -26,77 +26,78 @@ import org.dspace.content.Item; import org.xml.sax.SAXException; /** - * This step is used when the a user clicks an unfinished submission - * from the submissions page. Here we present the full item and then + * This step is used when the a user clicks an unfinished submission + * from the submissions page. Here we present the full item and then * give the user the option to resume the item's submission. *

    * This is not a true "step" in the submission process, it just * kicks off editing an unfinished submission. - * - * FIXME: We should probably give the user the option to remove the + * + * FIXME: We should probably give the user the option to remove the * submission as well. - * + * * @author Scott Phillips * @author Tim Donohue (small updates for Configurable Submission) */ public class ResumeStep extends AbstractStep { - /** Language Strings **/ - protected static final Message T_submit_resume = + /** Language Strings **/ + protected static final Message T_submit_resume = message("xmlui.Submission.submit.ResumeStep.submit_resume"); - protected static final Message T_submit_cancel = + protected static final Message T_submit_cancel = message("xmlui.general.cancel"); - - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public ResumeStep() - { - this.requireWorkspace = true; - } + + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public ResumeStep() + { + this.requireWorkspace = true; + } - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { - // Get any metadata that may be removed by unselecting one of these options. - Item item = submission.getItem(); - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + // Get any metadata that may be removed by unselecting one of these options. + Item item = submission.getItem(); + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; - Request request = ObjectModelHelper.getRequest(objectModel); - String showfull = request.getParameter("showfull"); + Request request = ObjectModelHelper.getRequest(objectModel); + String showfull = request.getParameter("showfull"); - // if the user selected showsimple, remove showfull. - if (showfull != null && request.getParameter("showsimple") != null) + // if the user selected showsimple, remove showfull. + if (showfull != null && request.getParameter("showsimple") != null) { showfull = null; } - Division div = body.addInteractiveDivision("resume-submission", actionURL, Division.METHOD_POST, "primary submission"); - div.setHead(T_submission_head); + Division div = body.addInteractiveDivision("resume-submission", actionURL, Division.METHOD_POST, "primary submission"); + div.setHead(T_submission_head); - if (showfull == null) - { - ReferenceSet referenceSet = div.addReferenceSet("submission",ReferenceSet.TYPE_SUMMARY_VIEW); - referenceSet.addReference(item); - div.addPara().addButton("showfull").setValue(T_showfull); - } - else - { - ReferenceSet referenceSet = div.addReferenceSet("submission",ReferenceSet.TYPE_DETAIL_VIEW); - referenceSet.addReference(item); - div.addPara().addButton("showsimple").setValue(T_showsimple); + if (showfull == null) + { + ReferenceSet referenceSet = div.addReferenceSet("submission", ReferenceSet.TYPE_SUMMARY_VIEW); + referenceSet.addReference(item); + div.addPara().addButton("showfull").setValue(T_showfull); + } + else + { + ReferenceSet referenceSet = div.addReferenceSet("submission", ReferenceSet.TYPE_DETAIL_VIEW); + referenceSet.addReference(item); + div.addPara().addButton("showsimple").setValue(T_showsimple); - div.addHidden("showfull").setValue("true"); - } + div.addHidden("showfull").setValue("true"); + } - List form = div.addList("resume-submission",List.TYPE_FORM); + List form = div.addList("resume-submission", List.TYPE_FORM); - org.dspace.app.xmlui.wing.element.Item actions = form.addItem(); - actions.addButton("submit_resume").setValue(T_submit_resume); - actions.addButton("submit_cancel").setValue(T_submit_cancel); - } + org.dspace.app.xmlui.wing.element.Item actions = form.addItem(); + actions.addButton("submit_resume").setValue(T_submit_resume); + actions.addButton("submit_cancel").setValue(T_submit_cancel); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ReviewStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ReviewStep.java index f277e2f772..55e31cbe6f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ReviewStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/ReviewStep.java @@ -49,7 +49,7 @@ import org.xml.sax.SAXException; public class ReviewStep extends AbstractSubmissionStep { - /** Language Strings **/ + /** Language Strings **/ protected static final Message T_head = message("xmlui.Submission.submit.ReviewStep.head"); protected static final Message T_yes = @@ -78,14 +78,14 @@ public class ReviewStep extends AbstractSubmissionStep private static Logger log = Logger.getLogger(UploadStep.class); - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public ReviewStep() - { - this.requireSubmission = true; - this.requireStep = true; - } + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public ReviewStep() + { + this.requireSubmission = true; + this.requireStep = true; + } /** * Save these setup parameters, to use for loading up @@ -100,12 +100,14 @@ public class ReviewStep extends AbstractSubmissionStep this.src = src; } - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { - // Get actionable URL - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + // Get actionable URL + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/" + collection.getHandle() + + "/submit/" + knot.getId() + ".continue"; SubmissionConfig subConfig = submissionInfo.getSubmissionConfig(); @@ -128,14 +130,14 @@ public class ReviewStep extends AbstractSubmissionStep //loop through each page in progress bar, //adding each as a separate section to the review form - for(int i=0; i * At any time during submission the user may leave the processe and either * leave it for later or remove the submission. *

    - * This form presents three options, 1) Go back, 2) save the work, + * This form presents three options, 1) Go back, 2) save the work, * or 3) remove it. - * + * * @author Scott Phillips * @author Tim Donohue (small updates for Configurable Submission) */ public class SaveOrRemoveStep extends AbstractStep { - /** Language Strings **/ - protected static final Message T_head = + /** Language Strings **/ + protected static final Message T_head = message("xmlui.Submission.submit.SaveOrRemoveStep.head"); - protected static final Message T_info1 = + protected static final Message T_info1 = message("xmlui.Submission.submit.SaveOrRemoveStep.info1"); - protected static final Message T_submit_back = + protected static final Message T_submit_back = message("xmlui.Submission.submit.SaveOrRemoveStep.submit_back"); - protected static final Message T_submit_save = + protected static final Message T_submit_save = message("xmlui.Submission.submit.SaveOrRemoveStep.submit_save"); - protected static final Message T_submit_remove = + protected static final Message T_submit_remove = message("xmlui.Submission.submit.SaveOrRemoveStep.submit_remove"); - - - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public SaveOrRemoveStep() - { - this.requireSubmission = true; - this.requireStep = true; - } - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException - { - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; - Division div = body.addInteractiveDivision("submit-save-or-cancel",actionURL, Division.METHOD_POST,"primary submission"); - div.setHead(T_submission_head); - addSubmissionProgressList(div); - - List saveOrCancel = div.addList("submit-review", List.TYPE_FORM); - - saveOrCancel.setHead(T_head); - saveOrCancel.addItem(T_info1); - + + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public SaveOrRemoveStep() + { + this.requireSubmission = true; + this.requireStep = true; + } + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/" + collection.getHandle() + + "/submit/" + knot.getId() + ".continue"; + + Division div = body.addInteractiveDivision("submit-save-or-cancel", + actionURL, Division.METHOD_POST, "primary submission"); + div.setHead(T_submission_head); + addSubmissionProgressList(div); + + List saveOrCancel = div.addList("submit-review", List.TYPE_FORM); + + saveOrCancel.setHead(T_head); + saveOrCancel.addItem(T_info1); + org.dspace.app.xmlui.wing.element.Item actions = saveOrCancel.addItem(); actions.addButton("submit_back").setValue(T_submit_back); actions.addButton("submit_save").setValue(T_submit_save); - actions.addButton("submit_remove").setValue(T_submit_remove); - } + actions.addButton("submit_remove").setValue(T_submit_remove); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadStep.java index a3d64166f4..34638c5460 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadStep.java @@ -508,7 +508,7 @@ public class UploadStep extends AbstractSubmissionStep * * @param item The DSpace Item that the bitstream is part of * @param bitstream The bitstream to link to - * @returns a String link to the bitstream + * @return a String link to the bitstream */ private String makeBitstreamLink(Item item, Bitstream bitstream) { diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadWithEmbargoStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadWithEmbargoStep.java index 7456674e03..852be8edbc 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadWithEmbargoStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/UploadWithEmbargoStep.java @@ -39,14 +39,14 @@ import java.util.*; */ public class UploadWithEmbargoStep extends UploadStep { - /** Language Strings for Uploading **/ - protected static final Message T_head = + /** Language Strings for Uploading **/ + protected static final Message T_head = message("xmlui.Submission.submit.UploadWithEmbargoStep.head"); - protected static final Message T_file = + protected static final Message T_file = message("xmlui.Submission.submit.UploadWithEmbargoStep.file"); - protected static final Message T_file_help = + protected static final Message T_file_help = message("xmlui.Submission.submit.UploadWithEmbargoStep.file_help"); - protected static final Message T_file_error = + protected static final Message T_file_error = message("xmlui.Submission.submit.UploadWithEmbargoStep.file_error"); protected static final Message T_upload_error = message("xmlui.Submission.submit.UploadWithEmbargoStep.upload_error"); @@ -56,47 +56,47 @@ public class UploadWithEmbargoStep extends UploadStep protected static final Message T_virus_error = message("xmlui.Submission.submit.UploadWithEmbargoStep.virus_error"); - protected static final Message T_description = + protected static final Message T_description = message("xmlui.Submission.submit.UploadWithEmbargoStep.description"); - protected static final Message T_description_help = + protected static final Message T_description_help = message("xmlui.Submission.submit.UploadWithEmbargoStep.description_help"); - protected static final Message T_submit_upload = + protected static final Message T_submit_upload = message("xmlui.Submission.submit.UploadWithEmbargoStep.submit_upload"); - protected static final Message T_head2 = + protected static final Message T_head2 = message("xmlui.Submission.submit.UploadWithEmbargoStep.head2"); - protected static final Message T_column0 = + protected static final Message T_column0 = message("xmlui.Submission.submit.UploadWithEmbargoStep.column0"); - protected static final Message T_column1 = + protected static final Message T_column1 = message("xmlui.Submission.submit.UploadWithEmbargoStep.column1"); - protected static final Message T_column2 = + protected static final Message T_column2 = message("xmlui.Submission.submit.UploadWithEmbargoStep.column2"); - protected static final Message T_column3 = + protected static final Message T_column3 = message("xmlui.Submission.submit.UploadWithEmbargoStep.column3"); - protected static final Message T_column4 = + protected static final Message T_column4 = message("xmlui.Submission.submit.UploadWithEmbargoStep.column4"); - protected static final Message T_column5 = + protected static final Message T_column5 = message("xmlui.Submission.submit.UploadWithEmbargoStep.column5"); - protected static final Message T_column6 = + protected static final Message T_column6 = message("xmlui.Submission.submit.UploadWithEmbargoStep.column6"); - protected static final Message T_unknown_name = + protected static final Message T_unknown_name = message("xmlui.Submission.submit.UploadWithEmbargoStep.unknown_name"); - protected static final Message T_unknown_format = + protected static final Message T_unknown_format = message("xmlui.Submission.submit.UploadWithEmbargoStep.unknown_format"); - protected static final Message T_supported = + protected static final Message T_supported = message("xmlui.Submission.submit.UploadWithEmbargoStep.supported"); - protected static final Message T_known = + protected static final Message T_known = message("xmlui.Submission.submit.UploadWithEmbargoStep.known"); - protected static final Message T_unsupported = + protected static final Message T_unsupported = message("xmlui.Submission.submit.UploadWithEmbargoStep.unsupported"); protected static final Message T_submit_edit = message("xmlui.Submission.submit.UploadWithEmbargoStep.submit_edit"); protected static final Message T_submit_policy = - message("xmlui.Submission.submit.UploadWithEmbargoStep.submit_policy"); + message("xmlui.Submission.submit.UploadWithEmbargoStep.submit_policy"); - protected static final Message T_checksum = + protected static final Message T_checksum = message("xmlui.Submission.submit.UploadWithEmbargoStep.checksum"); - protected static final Message T_submit_remove = + protected static final Message T_submit_remove = message("xmlui.Submission.submit.UploadWithEmbargoStep.submit_remove"); /** @@ -110,42 +110,44 @@ public class UploadWithEmbargoStep extends UploadStep private EditPolicyStep editPolicy = null; private boolean isAdvancedFormEnabled=true; - + /** - * Establish our required parameters, abstractStep will enforce these. - */ - public UploadWithEmbargoStep() - { - this.requireSubmission = true; - this.requireStep = true; - } + * Establish our required parameters, abstractStep will enforce these. + */ + public UploadWithEmbargoStep() + { + this.requireSubmission = true; + this.requireStep = true; + } /** * Check if user has requested to edit information about an * uploaded file */ - public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) - throws ProcessingException, SAXException, IOException - { - super.setup(resolver,objectModel,src,parameters); - + public void setup(SourceResolver resolver, Map objectModel, String src, Parameters parameters) + throws ProcessingException, SAXException, IOException + { + super.setup(resolver, objectModel, src, parameters); + // If this page for editing an uploaded file's information // was requested, then we need to load EditFileStep instead! - if(this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_BITSTREAM) + if (this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_BITSTREAM) { this.editFile = new EditFileStep(); - this.editFile.setup(resolver, objectModel, src, parameters); + this.editFile.setup(resolver, objectModel, src, parameters); } - else if(this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICIES - || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICIES_ERROR_SELECT_GROUP - || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICIES_DUPLICATED_POLICY){ + else if (this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICIES + || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICIES_ERROR_SELECT_GROUP + || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICIES_DUPLICATED_POLICY) + { this.editBitstreamPolicies = new EditBitstreamPolicies(); this.editBitstreamPolicies.setup(resolver, objectModel, src, parameters); } - else if(this.errorFlag==org.dspace.submit.step.AccessStep.STATUS_EDIT_POLICY - || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICY_ERROR_SELECT_GROUP - || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICY_DUPLICATED_POLICY){ + else if (this.errorFlag==org.dspace.submit.step.AccessStep.STATUS_EDIT_POLICY + || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICY_ERROR_SELECT_GROUP + || this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_EDIT_POLICY_DUPLICATED_POLICY) + { this.editPolicy = new EditPolicyStep(); this.editPolicy.setup(resolver, objectModel, src, parameters); } @@ -163,60 +165,62 @@ public class UploadWithEmbargoStep extends UploadStep super.addPageMeta(pageMeta); pageMeta.addMetadata("javascript", "static").addContent("static/js/accessFormUtil.js"); } - + public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // If we are actually editing information of an uploaded file, // then display that body instead! - if(this.editFile!=null) + if (this.editFile != null) { editFile.addBody(body); return; } - else if(editBitstreamPolicies!=null && isAdvancedFormEnabled){ + else if (editBitstreamPolicies != null && isAdvancedFormEnabled) + { editBitstreamPolicies.addBody(body); return; } - else if(editPolicy!=null && isAdvancedFormEnabled){ + else if (editPolicy!=null && isAdvancedFormEnabled) + { editPolicy.addBody(body); return; } - + // Get a list of all files in the original bundle - Item item = submission.getItem(); - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/submit/" + knot.getId() + ".continue"; - boolean disableFileEditing = (submissionInfo.isInWorkflow()) && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("workflow.reviewer.file-edit"); + Item item = submission.getItem(); + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/" + collection.getHandle() + "/submit/" + knot.getId() + ".continue"; + boolean disableFileEditing = (submissionInfo.isInWorkflow()) && !DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("workflow.reviewer.file-edit"); java.util.List bundles = itemService.getBundles(item, "ORIGINAL"); java.util.List bitstreams = new ArrayList<>(); - if (bundles.size() > 0) - { - bitstreams = bundles.get(0).getBitstreams(); - } - - // Part A: - // First ask the user if they would like to upload a new file (may be the first one) - Division div = body.addInteractiveDivision("submit-upload", actionURL, Division.METHOD_MULTIPART, "primary submission"); - div.setHead(T_submission_head); - addSubmissionProgressList(div); - - - List upload = null; - if (!disableFileEditing) - { - // Only add the upload capabilities for new item submissions - upload = div.addList("submit-upload-new", List.TYPE_FORM); - upload.setHead(T_head); - - File file = upload.addItem().addFile("file"); - file.setLabel(T_file); - file.setHelp(T_file_help); - file.setRequired(); - - // if no files found error was thrown by processing class, display it! - if (this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_NO_FILES_ERROR) - { + if (bundles.size() > 0) + { + bitstreams = bundles.get(0).getBitstreams(); + } + + // Part A: + // First ask the user if they would like to upload a new file (may be the first one) + Division div = body.addInteractiveDivision("submit-upload", actionURL, Division.METHOD_MULTIPART, "primary submission"); + div.setHead(T_submission_head); + addSubmissionProgressList(div); + + + List upload = null; + if (!disableFileEditing) + { + // Only add the upload capabilities for new item submissions + upload = div.addList("submit-upload-new", List.TYPE_FORM); + upload.setHead(T_head); + + File file = upload.addItem().addFile("file"); + file.setLabel(T_file); + file.setHelp(T_file_help); + file.setRequired(); + + // if no files found error was thrown by processing class, display it! + if (this.errorFlag==org.dspace.submit.step.UploadWithEmbargoStep.STATUS_NO_FILES_ERROR) + { file.addError(T_file_error); } @@ -237,175 +241,178 @@ public class UploadWithEmbargoStep extends UploadStep { file.addError(T_virus_error); } - - Text description = upload.addItem().addText("description"); - description.setLabel(T_description); - description.setHelp(T_description_help); + + Text description = upload.addItem().addText("description"); + description.setLabel(T_description); + description.setHelp(T_description_help); // if AdvancedAccessPolicy=false: add simpleForm in UploadWithEmbargoStep - if(!isAdvancedFormEnabled){ + if (!isAdvancedFormEnabled) + { AccessStepUtil asu = new AccessStepUtil(context); // if the item is embargoed default value will be displayed. asu.addEmbargoDateSimpleForm(item, upload, errorFlag); asu.addReason(null, upload, errorFlag); } - Button uploadSubmit = upload.addItem().addButton("submit_upload"); - uploadSubmit.setValue(T_submit_upload); + Button uploadSubmit = upload.addItem().addButton("submit_upload"); + uploadSubmit.setValue(T_submit_upload); - } + } make_sherpaRomeo_submission(item, div); - + // Part B: // If the user has already uploaded files provide a list for the user. if (bitstreams.size() > 0 || disableFileEditing) - { - Table summary = div.addTable("submit-upload-summary",(bitstreams.size() * 2) + 2,7); - summary.setHead(T_head2); - - Row header = summary.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column0); // primary bitstream - header.addCellContent(T_column1); // select checkbox - header.addCellContent(T_column2); // file name - header.addCellContent(T_column3); // size - header.addCellContent(T_column4); // description - header.addCellContent(T_column5); // format - header.addCellContent(T_column6); // edit button - - for (Bitstream bitstream : bitstreams) - { + { + Table summary = div.addTable("submit-upload-summary", + (bitstreams.size() * 2) + 2, 7); + summary.setHead(T_head2); + + Row header = summary.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column0); // primary bitstream + header.addCellContent(T_column1); // select checkbox + header.addCellContent(T_column2); // file name + header.addCellContent(T_column3); // size + header.addCellContent(T_column4); // description + header.addCellContent(T_column5); // format + header.addCellContent(T_column6); // edit button + + for (Bitstream bitstream : bitstreams) + { UUID id = bitstream.getID(); - String name = bitstream.getName(); - String url = makeBitstreamLink(item, bitstream); - long bytes = bitstream.getSize(); - String desc = bitstream.getDescription(); - String algorithm = bitstream.getChecksumAlgorithm(); - String checksum = bitstream.getChecksum(); + String name = bitstream.getName(); + String url = makeBitstreamLink(item, bitstream); + long bytes = bitstream.getSize(); + String desc = bitstream.getDescription(); + String algorithm = bitstream.getChecksumAlgorithm(); + String checksum = bitstream.getChecksum(); - - Row row = summary.addRow(); - // Add radio-button to select this as the primary bitstream + Row row = summary.addRow(); + + // Add radio-button to select this as the primary bitstream Radio primary = row.addCell().addRadio("primary_bitstream_id"); primary.addOption(String.valueOf(id)); - + // If this bitstream is already marked as the primary bitstream // mark it as such. - if(bundles.get(0).getPrimaryBitstream() != null && bundles.get(0).getPrimaryBitstream().getID().equals(id)) { + if (bundles.get(0).getPrimaryBitstream() != null && bundles.get(0).getPrimaryBitstream().getID().equals(id)) + { primary.setOptionSelected(String.valueOf(id)); } - - if (!disableFileEditing) - { - // Workflow users can not remove files. - CheckBox remove = row.addCell().addCheckBox("remove"); - remove.setLabel("remove"); - remove.addOption(id.toString()); - } - else - { - row.addCell(); - } - - row.addCell().addXref(url,name); - row.addCellContent(bytes + " bytes"); - if (desc == null || desc.length() == 0) + + if (!disableFileEditing) + { + // Workflow users can not remove files. + CheckBox remove = row.addCell().addCheckBox("remove"); + remove.setLabel("remove"); + remove.addOption(id.toString()); + } + else + { + row.addCell(); + } + + row.addCell().addXref(url,name); + row.addCellContent(bytes + " bytes"); + if (desc == null || desc.length() == 0) { row.addCellContent(T_unknown_name); } - else + else { row.addCellContent(desc); } - - BitstreamFormat format = bitstream.getFormat(context); - if (format == null) - { - row.addCellContent(T_unknown_format); - } - else - { - int support = format.getSupportLevel(); - Cell cell = row.addCell(); - cell.addContent(format.getMIMEType()); - cell.addContent(" "); - switch (support) - { - case 1: - cell.addContent(T_supported); - break; - case 2: - cell.addContent(T_known); - break; - case 3: - cell.addContent(T_unsupported); - break; - } - } - - Button edit = row.addCell().addButton("submit_edit_"+id); - edit.setValue(T_submit_edit); - if(isAdvancedFormEnabled){ + BitstreamFormat format = bitstream.getFormat(context); + if (format == null) + { + row.addCellContent(T_unknown_format); + } + else + { + int support = format.getSupportLevel(); + Cell cell = row.addCell(); + cell.addContent(format.getMIMEType()); + cell.addContent(" "); + switch (support) + { + case 1: + cell.addContent(T_supported); + break; + case 2: + cell.addContent(T_known); + break; + case 3: + cell.addContent(T_unsupported); + break; + } + } + + Button edit = row.addCell().addButton("submit_edit_"+id); + edit.setValue(T_submit_edit); + + if (isAdvancedFormEnabled) + { Button policy = row.addCell().addButton("submit_editPolicy_"+id); policy.setValue(T_submit_policy); } Row checksumRow = summary.addRow(); - checksumRow.addCell(); - Cell checksumCell = checksumRow.addCell(null, null, 0, 6, null); - checksumCell.addHighlight("bold").addContent(T_checksum); - checksumCell.addContent(" "); - checksumCell.addContent(algorithm + ":" + checksum); - } - - if (!disableFileEditing) - { - // Workflow users can not remove files. - Row actionRow = summary.addRow(); - actionRow.addCell(); - Button removeSeleceted = actionRow.addCell(null, null, 0, 6, null).addButton("submit_remove_selected"); - removeSeleceted.setValue(T_submit_remove); - } - - upload = div.addList("submit-upload-new-part2", List.TYPE_FORM); + checksumRow.addCell(); + Cell checksumCell = checksumRow.addCell(null, null, 0, 6, null); + checksumCell.addHighlight("bold").addContent(T_checksum); + checksumCell.addContent(" "); + checksumCell.addContent(algorithm + ":" + checksum); + } - } + if (!disableFileEditing) + { + // Workflow users can not remove files. + Row actionRow = summary.addRow(); + actionRow.addCell(); + Button removeSeleceted = actionRow.addCell(null, null, 0, 6, null).addButton("submit_remove_selected"); + removeSeleceted.setValue(T_submit_remove); + } + + upload = div.addList("submit-upload-new-part2", List.TYPE_FORM); + } // Part C: // add standard control/paging buttons addControlButtons(upload); } - - /** + + /** * Each submission step must define its own information to be reviewed * during the final Review/Verify Step in the submission process. *

    - * The information to review should be tacked onto the passed in + * The information to review should be tacked onto the passed in * List object. *

    * NOTE: To remain consistent across all Steps, you should first * add a sub-List object (with this step's name as the heading), * by using a call to reviewList.addList(). This sublist is * the list you return from this method! - * + * * @param reviewList * The List to which all reviewable information should be added - * @return + * @return * The new sub-List object created by this step, which contains * all the reviewable information. If this step has nothing to - * review, then return null! + * review, then return null! */ - public List addReviewSection(List reviewList) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + public List addReviewSection(List reviewList) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { // Create a new list section for this step (and set its heading) List uploadSection = reviewList.addList("submit-review-" + this.stepAndPage, List.TYPE_FORM); uploadSection.setHead(T_head); - + // Review all uploaded files Item item = submission.getItem(); java.util.List bundles = itemService.getBundles(item, "ORIGINAL"); @@ -414,11 +421,11 @@ public class UploadWithEmbargoStep extends UploadStep { bitstreams = bundles.get(0).getBitstreams(); } - + for (Bitstream bitstream : bitstreams) { BitstreamFormat bitstreamFormat = bitstream.getFormat(context); - + String name = bitstream.getName(); String url = makeBitstreamLink(item, bitstream); String format = bitstreamFormat.getShortDescription(); @@ -431,14 +438,14 @@ public class UploadWithEmbargoStep extends UploadStep { support = T_supported; } - + org.dspace.app.xmlui.wing.element.Item file = uploadSection.addItem(); file.addXref(url,name); file.addContent(" - "+ format + " "); file.addContent(support); - + } - + // return this new "upload" section return uploadSection; } @@ -448,7 +455,7 @@ public class UploadWithEmbargoStep extends UploadStep * * @param item The DSpace Item that the bitstream is part of * @param bitstream The bitstream to link to - * @returns a String link to the bitstream + * @return a String link to the bitstream */ private String makeBitstreamLink(Item item, Bitstream bitstream) { @@ -474,4 +481,3 @@ public class UploadWithEmbargoStep extends UploadStep return result.toString(); } } - diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/DeleteVersionsConfirm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/DeleteVersionsConfirm.java index aad326f256..7f46fcc3da 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/DeleteVersionsConfirm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/DeleteVersionsConfirm.java @@ -35,48 +35,56 @@ import java.sql.SQLException; public class DeleteVersionsConfirm extends AbstractDSpaceTransformer { /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_title = message("xmlui.aspect.versioning.DeleteVersionsConfirm.title"); - private static final Message T_trail = message("xmlui.aspect.versioning.DeleteVersionsConfirm.trail"); - private static final Message T_head1 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.head1"); - private static final Message T_para1 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.para1"); - private static final Message T_para2 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.para2"); - private static final Message T_column1 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column1"); - private static final Message T_column2 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column2"); - private static final Message T_column3 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column3"); + private static final Message T_title = message("xmlui.aspect.versioning.DeleteVersionsConfirm.title"); + private static final Message T_trail = message("xmlui.aspect.versioning.DeleteVersionsConfirm.trail"); + private static final Message T_head1 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.head1"); + private static final Message T_para1 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.para1"); + private static final Message T_para2 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.para2"); + private static final Message T_column1 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column1"); + private static final Message T_column2 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column2"); + private static final Message T_column3 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column3"); private static final Message T_column4 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column4"); private static final Message T_column5 = message("xmlui.aspect.versioning.DeleteVersionsConfirm.column5"); private static final Message T_submit_delete = message("xmlui.general.delete"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); protected VersioningService versioningService = VersionServiceFactory.getInstance().getVersionService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - public void addPageMeta(PageMeta pageMeta) throws WingException { - pageMeta.addMetadata("title").addContent(T_title); + public void addPageMeta(PageMeta pageMeta) + throws WingException + { + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - //pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + //pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } - public void addBody(Body body) throws WingException, AuthorizeException, SQLException { - Division main = createMainDivision(body); + public void addBody(Body body) + throws WingException, AuthorizeException, SQLException + { + Division main = createMainDivision(body); - createTable(main); + createTable(main); addButtons(main); - main.addHidden("versioning-continue").setValue(knot.getId()); - } + main.addHidden("versioning-continue").setValue(knot.getId()); + } - private Division createMainDivision(Body body) throws WingException { - Division main = body.addInteractiveDivision("versions-confirm-delete", contextPath+"/item/versionhistory", Division.METHOD_POST, "delete version"); - main.setHead(T_head1); + private Division createMainDivision(Body body) + throws WingException + { + Division main = body.addInteractiveDivision("versions-confirm-delete", + contextPath + "/item/versionhistory", Division.METHOD_POST, + "delete version"); + main.setHead(T_head1); Para helpPara = main.addPara(); helpPara.addContent(T_para1); helpPara.addHighlight("bold").addContent(T_para2); @@ -84,16 +92,18 @@ public class DeleteVersionsConfirm extends AbstractDSpaceTransformer { } - private void createTable(Division main) throws WingException, SQLException { + private void createTable(Division main) + throws WingException, SQLException + { // Get all our parameters - String idsString = parameters.getParameter("versionIDs", null); + String idsString = parameters.getParameter("versionIDs", null); Table table = main.addTable("versions-confirm-delete", 1, 1); - Row header = table.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column1); - header.addCellContent(T_column2); - header.addCellContent(T_column3); + Row header = table.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column1); + header.addCellContent(T_column2); + header.addCellContent(T_column3); header.addCellContent(T_column4); header.addCellContent(T_column5); @@ -102,15 +112,15 @@ public class DeleteVersionsConfirm extends AbstractDSpaceTransformer { { Version version = null; - if(StringUtils.isNotBlank(id)) + if (StringUtils.isNotBlank(id)) { version = versioningService.getVersion(context, Integer.parseInt(id)); } - if(version!=null) + if (version != null) { Row row = table.addRow(); - row.addCell().addContent(version.getVersionNumber()); + row.addCell().addContent(version.getVersionNumber()); addItemIdentifier(row.addCell(), version.getItem()); EPerson editor = version.getEPerson(); @@ -118,30 +128,37 @@ public class DeleteVersionsConfirm extends AbstractDSpaceTransformer { row.addCell().addContent(new DCDate(version.getVersionDate()).toString()); row.addCell().addContent(version.getSummary()); } - } + } } - private void addButtons(Division main) throws WingException { + private void addButtons(Division main) + throws WingException + { Para buttons = main.addPara(); - buttons.addButton("submit_confirm").setValue(T_submit_delete); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); + buttons.addButton("submit_confirm").setValue(T_submit_delete); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); } - private void addItemIdentifier(Cell cell, org.dspace.content.Item item) throws WingException { + private void addItemIdentifier(Cell cell, org.dspace.content.Item item) + throws WingException { String itemHandle = item.getHandle(); - java.util.List identifiers = itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "identifier", null, org.dspace.content.Item.ANY); - String itemIdentifier=null; - if(identifiers!=null && identifiers.size() > 0) + java.util.List identifiers = itemService.getMetadata( + item, MetadataSchema.DC_SCHEMA, "identifier", null, + org.dspace.content.Item.ANY); + String itemIdentifier = null; + if (identifiers != null && identifiers.size() > 0) { itemIdentifier = identifiers.get(0).getValue(); } - if(itemIdentifier!=null) + if (itemIdentifier != null) { cell.addXref(contextPath + "/resource/" + itemIdentifier, itemIdentifier); - }else{ + } + else + { cell.addXref(contextPath + "/handle/" + itemHandle, itemHandle); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/Navigation.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/Navigation.java index 3cac71ac4d..81d92d4108 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/Navigation.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/Navigation.java @@ -60,14 +60,14 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr private static final Message T_context_show_version_history= message("xmlui.aspect.versioning.VersioningNavigation.context_show_version_history"); /** Cached validity object */ - private SourceValidity validity; + private SourceValidity validity; protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected VersionHistoryService versionHistoryService = VersionServiceFactory.getInstance().getVersionHistoryService(); - /** + /** * Generate the unique cache key. * * @return The generated key hashes the src @@ -82,8 +82,8 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr // succeded or failed. So we don't know whether to cache this // under the user's specific cache or under the anonymous user. if (request.getParameter("login_email") != null || - request.getParameter("login_password") != null || - request.getParameter("login_realm") != null ) + request.getParameter("login_password") != null || + request.getParameter("login_realm") != null ) { return "0"; } @@ -91,10 +91,12 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr String key; if (context.getCurrentUser() != null) { - key = context.getCurrentUser().getEmail(); + key = context.getCurrentUser().getEmail(); } else - key = "anonymous"; + { + key = "anonymous"; + } return HashUtil.hash(key); } @@ -107,48 +109,52 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr */ public SourceValidity getValidity() { - if (this.validity == null) - { - // Only use the DSpaceValidity object is someone is logged in. - if (context.getCurrentUser() != null) - { - try { - DSpaceValidity validity = new DSpaceValidity(); + if (this.validity == null) + { + // Only use the DSpaceValidity object is someone is logged in. + if (context.getCurrentUser() != null) + { + try + { + DSpaceValidity validity = new DSpaceValidity(); - validity.add(context, eperson); + validity.add(context, eperson); - java.util.List groups = groupService.allMemberGroups(context, eperson); - for (Group group : groups) - { - validity.add(context, group); - } + java.util.List groups = groupService.allMemberGroups( + context, eperson); + for (Group group : groups) + { + validity.add(context, group); + } DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - if(dso != null) + if (dso != null) { validity.add(context, dso); } - this.validity = validity.complete(); - } - catch (SQLException sqle) - { - // Just ignore it and return invalid. - } - } - else - { - this.validity = NOPValidity.SHARED_INSTANCE; - } - } - return this.validity; + this.validity = validity.complete(); + } + catch (SQLException sqle) + { + // Just ignore it and return invalid. + } + } + else + { + this.validity = NOPValidity.SHARED_INSTANCE; + } + } + return this.validity; } - public void addOptions(Options options) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException { - /* Create skeleton menu structure to ensure consistent order between aspects, - * even if they are never used - */ + public void addOptions(Options options) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + /* Create skeleton menu structure to ensure consistent order between aspects, + * even if they are never used + */ options.addList("browse"); options.addList("account"); @@ -159,7 +165,7 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - if(dso==null) + if (dso==null) { // case: internal-item http://localhost:8100/internal-item?itemID=3085 // case: admin http://localhost:8100/admin/item?itemID=3340 @@ -167,33 +173,38 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr dso = getItemById(); } - if (dso != null && dso.getType() == Constants.ITEM) + if (dso != null && dso.getType() == Constants.ITEM) { - Item item = (Item) dso; - if(authorizeService.isAdmin(this.context, item.getOwningCollection())) + Item item = (Item) dso; + if (authorizeService.isAdmin(this.context, item.getOwningCollection())) { boolean headAdded=false; - if(versionHistoryService.isLastVersion(this.context, item) && item.isArchived()) + if (versionHistoryService.isLastVersion(this.context, item) && item.isArchived()) { context.setHead(T_context_head); headAdded=true; - context.addItem().addXref(contextPath+"/item/version?itemID="+item.getID(), T_context_create_version); + context.addItem().addXref(contextPath + + "/item/version?itemID=" + item.getID(), + T_context_create_version); } - if(versionHistoryService.hasVersionHistory(this.context, item)) + if (versionHistoryService.hasVersionHistory(this.context, item)) { - if(!headAdded) + if (!headAdded) { context.setHead(T_context_head); } - context.addItem().addXref(contextPath+"/item/versionhistory?itemID="+item.getID(), T_context_show_version_history); + context.addItem().addXref(contextPath + + "/item/versionhistory?itemID=" + item.getID(), + T_context_show_version_history); } } - } + } } - private Item getItemById() throws SQLException + private Item getItemById() + throws SQLException { Request request = ObjectModelHelper.getRequest(objectModel); Item item = null; @@ -213,5 +224,4 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr this.validity = null; super.recycle(); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/RestoreVersionForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/RestoreVersionForm.java index 0a90f194d7..8ca67b4046 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/RestoreVersionForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/RestoreVersionForm.java @@ -28,62 +28,68 @@ import java.sql.SQLException; */ public class RestoreVersionForm extends AbstractDSpaceTransformer { - /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); + /** Language strings */ + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_item_trail = message("xmlui.administrative.item.general.item_trail"); - private static final Message T_title = message("xmlui.aspect.versioning.RestoreVersionForm.title"); - private static final Message T_trail = message("xmlui.aspect.versioning.RestoreVersionForm.trail"); - private static final Message T_head1 = message("xmlui.aspect.versioning.RestoreVersionForm.head1"); - private static final Message T_para1 = message("xmlui.aspect.versioning.RestoreVersionForm.para1"); - private static final Message T_column1 = message("xmlui.aspect.versioning.RestoreVersionForm.column1"); - private static final Message T_column2 = message("xmlui.aspect.versioning.RestoreVersionForm.column2"); - private static final Message T_column3 = message("xmlui.aspect.versioning.RestoreVersionForm.column3"); + private static final Message T_title = message("xmlui.aspect.versioning.RestoreVersionForm.title"); + private static final Message T_trail = message("xmlui.aspect.versioning.RestoreVersionForm.trail"); + private static final Message T_head1 = message("xmlui.aspect.versioning.RestoreVersionForm.head1"); + private static final Message T_para1 = message("xmlui.aspect.versioning.RestoreVersionForm.para1"); + private static final Message T_column1 = message("xmlui.aspect.versioning.RestoreVersionForm.column1"); + private static final Message T_column2 = message("xmlui.aspect.versioning.RestoreVersionForm.column2"); + private static final Message T_column3 = message("xmlui.aspect.versioning.RestoreVersionForm.column3"); private static final Message T_column4 = message("xmlui.aspect.versioning.RestoreVersionForm.column4"); private static final Message T_submit_restore = message("xmlui.aspect.versioning.RestoreVersionForm.restore"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); protected VersioningService versioningService = VersionServiceFactory.getInstance().getVersionService(); - public void addPageMeta(PageMeta pageMeta) throws WingException + public void addPageMeta(PageMeta pageMeta) + throws WingException { - pageMeta.addMetadata("title").addContent(T_title); + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); - pageMeta.addTrail().addContent(T_trail); - } + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrailLink(contextPath + "/admin/item",T_item_trail); + pageMeta.addTrail().addContent(T_trail); + } - public void addBody(Body body) throws WingException, AuthorizeException, SQLException + public void addBody(Body body) + throws WingException, AuthorizeException, SQLException { - Division main = createMainDivision(body); - createTable(main); + Division main = createMainDivision(body); + createTable(main); addButtons(main); - main.addHidden("versioning-continue").setValue(knot.getId()); - } + main.addHidden("versioning-continue").setValue(knot.getId()); + } - private Division createMainDivision(Body body) throws WingException + private Division createMainDivision(Body body) + throws WingException { - Division main = body.addInteractiveDivision("restore-version", contextPath+"/item/versionhistory", Division.METHOD_POST, "restore version"); - main.setHead(T_head1); - main.addPara(T_para1); + Division main = body.addInteractiveDivision("restore-version", + contextPath + "/item/versionhistory", Division.METHOD_POST, + "restore version"); + main.setHead(T_head1); + main.addPara(T_para1); return main; } - private void createTable(Division main) throws WingException, SQLException + private void createTable(Division main) + throws WingException, SQLException { // Get all our parameters - String id = parameters.getParameter("versionID", null); + String id = parameters.getParameter("versionID", null); Table table = main.addTable("version", 1, 1); - Row header = table.addRow(Row.ROLE_HEADER); - header.addCellContent(T_column1); - header.addCellContent(T_column2); - header.addCellContent(T_column3); + Row header = table.addRow(Row.ROLE_HEADER); + header.addCellContent(T_column1); + header.addCellContent(T_column2); + header.addCellContent(T_column3); header.addCellContent(T_column4); Version version = versioningService.getVersion(context, Integer.parseInt(id)); @@ -101,11 +107,11 @@ public class RestoreVersionForm extends AbstractDSpaceTransformer addComposite.addTextArea("summary"); } - private void addButtons(Division main) throws WingException + private void addButtons(Division main) + throws WingException { Para buttons = main.addPara(); - buttons.addButton("submit_restore").setValue(T_submit_restore); - buttons.addButton("submit_cancel").setValue(T_submit_cancel); + buttons.addButton("submit_restore").setValue(T_submit_restore); + buttons.addButton("submit_cancel").setValue(T_submit_cancel); } } - diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionItemForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionItemForm.java index 1306bc6532..c9fda09d11 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionItemForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionItemForm.java @@ -37,14 +37,14 @@ import java.util.UUID; public class VersionItemForm extends AbstractDSpaceTransformer { /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); - private static final Message T_title = message("xmlui.aspect.versioning.VersionItemForm.title"); - private static final Message T_trail = message("xmlui.aspect.versioning.VersionItemForm.trail"); - private static final Message T_head1 = message("xmlui.aspect.versioning.VersionItemForm.head1"); + private static final Message T_title = message("xmlui.aspect.versioning.VersionItemForm.title"); + private static final Message T_trail = message("xmlui.aspect.versioning.VersionItemForm.trail"); + private static final Message T_head1 = message("xmlui.aspect.versioning.VersionItemForm.head1"); private static final Message T_submit_version= message("xmlui.aspect.versioning.VersionItemForm.submit_version"); - private static final Message T_submit_update_version= message("xmlui.aspect.versioning.VersionItemForm.submit_update_version"); + private static final Message T_submit_update_version= message("xmlui.aspect.versioning.VersionItemForm.submit_update_version"); private static final Message T_summary = message("xmlui.aspect.versioning.VersionItemForm.summary"); @@ -52,38 +52,47 @@ public class VersionItemForm extends AbstractDSpaceTransformer { protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected VersionHistoryService versionHistoryService = VersionServiceFactory.getInstance().getVersionHistoryService(); - public void addPageMeta(PageMeta pageMeta) throws WingException, SQLException { - pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - //pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail); + public void addPageMeta(PageMeta pageMeta) + throws WingException, SQLException + { + pageMeta.addMetadata("title").addContent(T_title); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + //pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail); Item item = getItem(); - if(item != null) + if (item != null) { HandleUtil.buildHandleTrail(context, item, pageMeta, contextPath); pageMeta.addTrailLink(contextPath + "/handle/" + item.getHandle(), item.getName()); } pageMeta.addTrail().addContent(T_trail); - } + } - public void addBody(Body body) throws WingException, SQLException, AuthorizeException { + public void addBody(Body body) + throws WingException, SQLException, AuthorizeException + { // Get our parameters and state Item item = getItem(); //Only (collection) admins should be able to create a new version - if(!authorizeService.isAdmin(context, item.getOwningCollection())){ + if (!authorizeService.isAdmin(context, item.getOwningCollection())){ throw new AuthorizeException(); } String summary; - try { + try + { summary = parameters.getParameter("summary"); - } catch (ParameterException e) { + } + catch (ParameterException e) + { throw new RuntimeException(e); } // DIVISION: Main - Division main = body.addInteractiveDivision("version-item", contextPath+"/item/version", Division.METHOD_POST, "primary administrative version"); + Division main = body.addInteractiveDivision("version-item", + contextPath + "/item/version", Division.METHOD_POST, + "primary administrative version"); main.setHead(T_head1.parameterize(item.getHandle())); // Fields @@ -91,7 +100,7 @@ public class VersionItemForm extends AbstractDSpaceTransformer { Composite addComposite = fields.addItem().addComposite("summary"); addComposite.setLabel(T_summary); TextArea addValue = addComposite.addTextArea("summary"); - if(summary!=null) + if (summary!=null) { addValue.setValue(summary); } @@ -101,7 +110,7 @@ public class VersionItemForm extends AbstractDSpaceTransformer { Para actions = main.addPara(); org.dspace.versioning.VersionHistory history = retrieveVersionHistory(item); - if(history!=null && versionHistoryService.hasNext(context, history ,item)) + if (history != null && versionHistoryService.hasNext(context, history, item)) { actions.addButton("submit_update_version").setValue(T_submit_update_version); } @@ -112,16 +121,18 @@ public class VersionItemForm extends AbstractDSpaceTransformer { actions.addButton("submit_cancel").setValue(T_submit_cancel); - main.addHidden("versioning-continue").setValue(knot.getId()); - } + main.addHidden("versioning-continue").setValue(knot.getId()); + } - private Item getItem() throws SQLException { + private Item getItem() + throws SQLException + { UUID itemID = UUID.fromString(parameters.getParameter("itemID",null)); return itemService.find(context, itemID); } - - private org.dspace.versioning.VersionHistory retrieveVersionHistory(Item item) throws SQLException + private org.dspace.versioning.VersionHistory retrieveVersionHistory(Item item) + throws SQLException { return versionHistoryService.findByItem(context, item); } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionUpdateForm.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionUpdateForm.java index cb91b94f8b..bf6a1af2b9 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionUpdateForm.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionUpdateForm.java @@ -29,32 +29,37 @@ import java.sql.SQLException; public class VersionUpdateForm extends AbstractDSpaceTransformer { /** Language strings */ - private static final Message T_dspace_home = message("xmlui.general.dspace_home"); - private static final Message T_submit_cancel = message("xmlui.general.cancel"); + private static final Message T_dspace_home = message("xmlui.general.dspace_home"); + private static final Message T_submit_cancel = message("xmlui.general.cancel"); - private static final Message T_title = message("xmlui.aspect.versioning.VersionUpdateForm.title"); - private static final Message T_trail = message("xmlui.aspect.versioning.VersionUpdateForm.trail"); - private static final Message T_head1 = message("xmlui.aspect.versioning.VersionUpdateForm.head1"); + private static final Message T_title = message("xmlui.aspect.versioning.VersionUpdateForm.title"); + private static final Message T_trail = message("xmlui.aspect.versioning.VersionUpdateForm.trail"); + private static final Message T_head1 = message("xmlui.aspect.versioning.VersionUpdateForm.head1"); private static final Message T_submit_version= message("xmlui.aspect.versioning.VersionUpdateForm.submit_version"); - private static final Message T_submit_update_version= message("xmlui.aspect.versioning.VersionUpdateForm.submit_update_version"); + private static final Message T_submit_update_version= message("xmlui.aspect.versioning.VersionUpdateForm.submit_update_version"); private static final Message T_summary = message("xmlui.aspect.versioning.VersionUpdateForm.summary"); protected VersioningService versioningService = VersionServiceFactory.getInstance().getVersionService(); - public void addPageMeta(PageMeta pageMeta) throws WingException { - pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/", T_dspace_home); - pageMeta.addTrail().addContent(T_trail); - } + public void addPageMeta(PageMeta pageMeta) + throws WingException { + pageMeta.addMetadata("title").addContent(T_title); + pageMeta.addTrailLink(contextPath + "/", T_dspace_home); + pageMeta.addTrail().addContent(T_trail); + } - public void addBody(Body body) throws WingException, SQLException{ + public void addBody(Body body) + throws WingException, SQLException + { int versionID = parameters.getParameterAsInteger("versionID",-1); org.dspace.versioning.Version version = getVersion(versionID); Item item = version.getItem(); // DIVISION: Main - Division main = body.addInteractiveDivision("version-item", contextPath+"/item/versionhistory", Division.METHOD_POST, "primary administrative version"); + Division main = body.addInteractiveDivision("version-item", + contextPath + "/item/versionhistory", Division.METHOD_POST, + "primary administrative version"); main.setHead(T_head1.parameterize(item.getHandle())); // Fields @@ -64,17 +69,17 @@ public class VersionUpdateForm extends AbstractDSpaceTransformer { TextArea addValue = addComposite.addTextArea("summary"); addValue.setValue(version.getSummary()); - // Buttons Para actions = main.addPara(); actions.addButton("submit_update").setValue(T_submit_update_version); actions.addButton("submit_cancel").setValue(T_submit_cancel); - main.addHidden("versioning-continue").setValue(knot.getId()); - } + main.addHidden("versioning-continue").setValue(knot.getId()); + } - private org.dspace.versioning.Version getVersion(int versionID) throws SQLException + private org.dspace.versioning.Version getVersion(int versionID) + throws SQLException { return versioningService.getVersion(context, versionID); } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/ClaimTasksAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/ClaimTasksAction.java index 730a801640..7d5937352d 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/ClaimTasksAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/ClaimTasksAction.java @@ -24,16 +24,16 @@ import org.dspace.workflowbasic.service.BasicWorkflowItemService; import org.dspace.workflowbasic.service.BasicWorkflowService; /** - * Claim all the selected workflows. This action is used by the + * Claim all the selected workflows. This action is used by the * submission page, when the user clicks the claim tasks button. - * + * * @author Scott Phillips */ public class ClaimTasksAction extends AbstractAction { - protected BasicWorkflowService basicWorkflowService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowService(); - protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService(); + protected BasicWorkflowService basicWorkflowService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowService(); + protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService(); /** * Claim-tasks action. @@ -49,31 +49,31 @@ public class ClaimTasksAction extends AbstractAction */ @Override public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, - String source, Parameters parameters) throws Exception + String source, Parameters parameters) + throws Exception { Request request = ObjectModelHelper.getRequest(objectModel); Context context = ContextUtil.obtainContext(objectModel); - - // Or the user selected a checkbox full of workflow IDs - String[] workflowIDs = request.getParameterValues("workflowID"); - if (workflowIDs != null) - { - for (String workflowID : workflowIDs) - { - BasicWorkflowItem workflowItem = basicWorkflowItemService.find(context, Integer.valueOf(workflowID)); - - int state = workflowItem.getState(); - // Only unclaim tasks that are already claimed. - if ( state == BasicWorkflowServiceImpl.WFSTATE_STEP1POOL || - state == BasicWorkflowServiceImpl.WFSTATE_STEP2POOL || - state == BasicWorkflowServiceImpl.WFSTATE_STEP3POOL) - { - basicWorkflowService.claim(context, workflowItem, context.getCurrentUser()); - } - } - } - - return null; - } + // Or the user selected a checkbox full of workflow IDs + String[] workflowIDs = request.getParameterValues("workflowID"); + if (workflowIDs != null) + { + for (String workflowID : workflowIDs) + { + BasicWorkflowItem workflowItem = basicWorkflowItemService.find(context, Integer.valueOf(workflowID)); + + int state = workflowItem.getState(); + // Only unclaim tasks that are already claimed. + if ( state == BasicWorkflowServiceImpl.WFSTATE_STEP1POOL || + state == BasicWorkflowServiceImpl.WFSTATE_STEP2POOL || + state == BasicWorkflowServiceImpl.WFSTATE_STEP3POOL) + { + basicWorkflowService.claim(context, workflowItem, context.getCurrentUser()); + } + } + } + + return null; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/FlowUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/FlowUtils.java index ae125c71c0..f883f3e216 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/FlowUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/FlowUtils.java @@ -56,27 +56,28 @@ public class FlowUtils { private static final Logger log = Logger.getLogger(FlowUtils.class); - /** - * Update the provided workflowItem to advance to the next workflow - * step. If this was the last thing needed before the item is - * committed to the repository then return true, otherwise false. - * - * @param context The current DSpace content - * @param id The unique ID of the current workflow + /** + * Update the provided workflowItem to advance to the next workflow + * step. If this was the last thing needed before the item is + * committed to the repository then return true, otherwise false. + * + * @param context The current DSpace content + * @param id The unique ID of the current workflow * @return whether the workflow is completed. * @throws java.sql.SQLException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws javax.servlet.ServletException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static boolean processApproveTask(Context context, String id) - throws SQLException, UIException, ServletException, AuthorizeException, IOException - { - BasicWorkflowItem workflowItem = findWorkflow(context, id); - Item item = workflowItem.getItem(); + */ + public static boolean processApproveTask(Context context, String id) + throws SQLException, UIException, ServletException, AuthorizeException, + IOException + { + BasicWorkflowItem workflowItem = findWorkflow(context, id); + Item item = workflowItem.getItem(); - // Advance the item along the workflow + // Advance the item along the workflow basicWorkflowService.advance(context, workflowItem, context.getCurrentUser()); // FIXME: This should be a return value from advance() @@ -93,57 +94,60 @@ public class FlowUtils { { return false; } - } + } - /** - * Return the given task to the pool of unclaimed tasks for another user - * to select and perform. - * - * @param context The current DSpace content - * @param id The unique ID of the current workflow + /** + * Return the given task to the pool of unclaimed tasks for another user + * to select and perform. + * + * @param context The current DSpace content + * @param id The unique ID of the current workflow * @throws java.sql.SQLException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws javax.servlet.ServletException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static void processUnclaimTask(Context context, String id) - throws SQLException, UIException, ServletException, AuthorizeException, IOException - { - BasicWorkflowItem workflowItem = findWorkflow(context, id); + */ + public static void processUnclaimTask(Context context, String id) + throws SQLException, UIException, ServletException, AuthorizeException, + IOException + { + BasicWorkflowItem workflowItem = findWorkflow(context, id); // Return task to pool basicWorkflowService.unclaim(context, workflowItem, context.getCurrentUser()); // Log this unclaim action log.info(LogManager.getHeader(context, "unclaim_workflow", - "workflow_item_id=" + workflowItem.getID() + ",item_id=" - + workflowItem.getItem().getID() + ",collection_id=" - + workflowItem.getCollection().getID() - + ",new_state=" + workflowItem.getState())); - } + "workflow_item_id=" + workflowItem.getID() + ",item_id=" + + workflowItem.getItem().getID() + ",collection_id=" + + workflowItem.getCollection().getID() + + ",new_state=" + workflowItem.getState())); + } - /** - * Claim this task from the pool of unclaimed task so that this user may - * perform the task by either approving or rejecting it. - * - * @param context The current DSpace content - * @param id The unique ID of the current workflow + /** + * Claim this task from the pool of unclaimed task so that this user may + * perform the task by either approving or rejecting it. + * + * @param context The current DSpace content + * @param id The unique ID of the current workflow * @throws java.sql.SQLException passed through. * @throws org.dspace.app.xmlui.utils.UIException passed through. * @throws javax.servlet.ServletException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static void processClaimTask(Context context, String id) - throws SQLException, UIException, ServletException, AuthorizeException, IOException - { - BasicWorkflowItem workflowItem = findWorkflow(context, id); - if(workflowItem.getState() != BasicWorkflowService.WFSTATE_STEP1POOL && - workflowItem.getState() != BasicWorkflowService.WFSTATE_STEP2POOL && - workflowItem.getState() != BasicWorkflowService.WFSTATE_STEP3POOL){ + */ + public static void processClaimTask(Context context, String id) + throws SQLException, UIException, ServletException, AuthorizeException, + IOException + { + BasicWorkflowItem workflowItem = findWorkflow(context, id); + if (workflowItem.getState() != BasicWorkflowService.WFSTATE_STEP1POOL && + workflowItem.getState() != BasicWorkflowService.WFSTATE_STEP2POOL && + workflowItem.getState() != BasicWorkflowService.WFSTATE_STEP3POOL) + { // Only allow tasks in the pool to be claimed ! throw new AuthorizeException("Error while claiming task: this task has already been claimed !"); } @@ -158,7 +162,7 @@ public class FlowUtils { + "collection_id=" + workflowItem.getCollection().getID() + "newowner_id=" + workflowItem.getOwner().getID() + "new_state=" + workflowItem.getState())); - } + } /** * Verifies if the currently logged in user has proper rights to perform the workflow task on the item @@ -167,25 +171,34 @@ public class FlowUtils { * @throws org.dspace.authorize.AuthorizeException thrown if the user doesn't have sufficient rights to perform the task at hand * @throws java.sql.SQLException is thrown when something is wrong with the database */ - public static void authorizeWorkflowItem(Context context, String workflowItemId) throws AuthorizeException, SQLException { + public static void authorizeWorkflowItem(Context context, String workflowItemId) + throws AuthorizeException, SQLException + { BasicWorkflowItem workflowItem = basicWorkflowItemService.find(context, Integer.parseInt(workflowItemId.substring(1))); - if((workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP1 || - workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP2 || - workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP3) && workflowItem.getOwner().getID() != context.getCurrentUser().getID()){ + if ((workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP1 || + workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP2 || + workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP3) && + workflowItem.getOwner().getID() != context.getCurrentUser().getID()) + { throw new AuthorizeException("You are not allowed to perform this task."); - }else - if((workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP1POOL || - workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP2POOL || - workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP3POOL)){ + } + else + if ((workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP1POOL || + workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP2POOL || + workflowItem.getState() == BasicWorkflowService.WFSTATE_STEP3POOL)) + { // Verify if the current user has the current workflowItem among his pooled tasks boolean hasPooledTask = false; List pooledTasks = basicWorkflowService.getPooledTasks(context, context.getCurrentUser()); - for (BasicWorkflowItem pooledItem : pooledTasks) { - if(pooledItem.getID() == workflowItem.getID()){ + for (BasicWorkflowItem pooledItem : pooledTasks) + { + if (pooledItem.getID() == workflowItem.getID()) + { hasPooledTask = true; } } - if(!hasPooledTask){ + if (!hasPooledTask) + { throw new AuthorizeException("You are not allowed to perform this task."); } @@ -193,12 +206,12 @@ public class FlowUtils { } - /** - * Reject the given task for the given reason. If the user did not provide - * a reason then an error is generated placing that field in error. - * - * @param context The current DSpace content - * @param id The unique ID of the current workflow + /** + * Reject the given task for the given reason. If the user did not provide + * a reason then an error is generated placing that field in error. + * + * @param context The current DSpace content + * @param id The unique ID of the current workflow * @param request The current request object * @return error if any. * @throws java.sql.SQLException passed through. @@ -206,16 +219,18 @@ public class FlowUtils { * @throws javax.servlet.ServletException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. * @throws java.io.IOException passed through. - */ - public static String processRejectTask(Context context, String id,Request request) + */ + public static String processRejectTask(Context context, String id,Request request) throws SQLException, UIException, ServletException, AuthorizeException, IOException - { - BasicWorkflowItem workflowItem = findWorkflow(context, id); + { + BasicWorkflowItem workflowItem = findWorkflow(context, id); - String reason = request.getParameter("reason"); + String reason = request.getParameter("reason"); - if (reason != null && reason.length() > 1) { - WorkspaceItem wsi = basicWorkflowService.sendWorkflowItemBackSubmission(context, workflowItem, context.getCurrentUser(), null, reason); + if (reason != null && reason.length() > 1) + { + WorkspaceItem wsi = basicWorkflowService.sendWorkflowItemBackSubmission( + context, workflowItem, context.getCurrentUser(), null, reason); // Load the Submission Process for the collection this WSI is associated with Collection c = wsi.getCollection(); @@ -231,21 +246,22 @@ public class FlowUtils { workspaceItemService.update(context, wsi); // Submission rejected. Log this information - log.info(LogManager.getHeader(context, "reject_workflow", "workflow_item_id=" - + wsi.getID() + "item_id=" + wsi.getItem().getID() - + "collection_id=" + wsi.getCollection().getID() - + "eperson_id=" + context.getCurrentUser().getID())); + log.info(LogManager.getHeader(context, "reject_workflow", + "workflow_item_id=" + wsi.getID() + + "item_id=" + wsi.getItem().getID() + + "collection_id=" + wsi.getCollection().getID() + + "eperson_id=" + context.getCurrentUser().getID())); - // Return no errors. - return null; - } - else - { - // If the user did not supply a reason then - // place the reason field in error. - return "reason"; - } - } + // Return no errors. + return null; + } + else + { + // If the user did not supply a reason then + // place the reason field in error. + return "reason"; + } + } /** * Return the workflow identified by the given id, the id should be @@ -260,7 +276,8 @@ public class FlowUtils { * @throws java.io.IOException passed through. */ public static BasicWorkflowItem findWorkflow(Context context, String inProgressSubmissionID) - throws SQLException, AuthorizeException, IOException { + throws SQLException, AuthorizeException, IOException + { int id = Integer.valueOf(inProgressSubmissionID.substring(1)); return basicWorkflowItemService.find(context, id); } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/PerformTaskStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/PerformTaskStep.java index ccf3281c60..3e7224f61c 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/PerformTaskStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/PerformTaskStep.java @@ -29,185 +29,190 @@ import org.dspace.workflowbasic.BasicWorkflowServiceImpl; import org.xml.sax.SAXException; /** - * + * * This step displays a workflow item to the user and and presents several * possible actions that they may perform on the task. - * + * * In general, the user may accept the item, reject the item, or edit the item's * metadata before accepting or rejecting. The user is also given the option * of taking the task or returning it to the pool. - * + * * @author Scott Phillips */ public class PerformTaskStep extends AbstractStep { - + /** Language Strings **/ - protected static final Message T_info1= + protected static final Message T_info1= message("xmlui.Submission.workflow.PerformTaskStep.info1"); - protected static final Message T_take_help = + protected static final Message T_take_help = message("xmlui.Submission.workflow.PerformTaskStep.take_help"); - protected static final Message T_take_submit = + protected static final Message T_take_submit = message("xmlui.Submission.workflow.PerformTaskStep.take_submit"); - protected static final Message T_leave_help = + protected static final Message T_leave_help = message("xmlui.Submission.workflow.PerformTaskStep.leave_help"); - protected static final Message T_leave_submit = + protected static final Message T_leave_submit = message("xmlui.Submission.workflow.PerformTaskStep.leave_submit"); - protected static final Message T_approve_help = + protected static final Message T_approve_help = message("xmlui.Submission.workflow.PerformTaskStep.approve_help"); - protected static final Message T_approve_submit = + protected static final Message T_approve_submit = message("xmlui.Submission.workflow.PerformTaskStep.approve_submit"); - protected static final Message T_commit_help = + protected static final Message T_commit_help = message("xmlui.Submission.workflow.PerformTaskStep.commit_help"); - protected static final Message T_commit_submit = + protected static final Message T_commit_submit = message("xmlui.Submission.workflow.PerformTaskStep.commit_submit"); - protected static final Message T_reject_help = + protected static final Message T_reject_help = message("xmlui.Submission.workflow.PerformTaskStep.reject_help"); protected static final Message T_reject_submit = message("xmlui.Submission.workflow.PerformTaskStep.reject_submit"); - protected static final Message T_edit_help = + protected static final Message T_edit_help = message("xmlui.Submission.workflow.PerformTaskStep.edit_help"); - protected static final Message T_edit_submit = + protected static final Message T_edit_submit = message("xmlui.Submission.workflow.PerformTaskStep.edit_submit"); - protected static final Message T_return_help = + protected static final Message T_return_help = message("xmlui.Submission.workflow.PerformTaskStep.return_help"); - protected static final Message T_return_submit = + protected static final Message T_return_submit = message("xmlui.Submission.workflow.PerformTaskStep.return_submit"); - protected static final Message T_cancel_submit = + protected static final Message T_cancel_submit = message("xmlui.general.cancel"); - - - /** Copy the workflow manager's state values so that we can reference them easier. */ - private static final int WFSTATE_STEP1POOL = BasicWorkflowServiceImpl.WFSTATE_STEP1POOL; - private static final int WFSTATE_STEP1 = BasicWorkflowServiceImpl.WFSTATE_STEP1; - private static final int WFSTATE_STEP2POOL = BasicWorkflowServiceImpl.WFSTATE_STEP2POOL; - private static final int WFSTATE_STEP2 = BasicWorkflowServiceImpl.WFSTATE_STEP2; - private static final int WFSTATE_STEP3POOL = BasicWorkflowServiceImpl.WFSTATE_STEP3POOL; - private static final int WFSTATE_STEP3 = BasicWorkflowServiceImpl.WFSTATE_STEP3; - - - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public PerformTaskStep() - { - this.requireWorkflow = true; - } - - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + + + /** Copy the workflow manager's state values so that we can reference them easier. */ + private static final int WFSTATE_STEP1POOL = BasicWorkflowServiceImpl.WFSTATE_STEP1POOL; + private static final int WFSTATE_STEP1 = BasicWorkflowServiceImpl.WFSTATE_STEP1; + private static final int WFSTATE_STEP2POOL = BasicWorkflowServiceImpl.WFSTATE_STEP2POOL; + private static final int WFSTATE_STEP2 = BasicWorkflowServiceImpl.WFSTATE_STEP2; + private static final int WFSTATE_STEP3POOL = BasicWorkflowServiceImpl.WFSTATE_STEP3POOL; + private static final int WFSTATE_STEP3 = BasicWorkflowServiceImpl.WFSTATE_STEP3; + + + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public PerformTaskStep() { - // Get any metadata that may be removed by unselecting one of these options. - Item item = submission.getItem(); - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/workflow"; - int state = ((BasicWorkflowItem) submission).getState(); - - Request request = ObjectModelHelper.getRequest(objectModel); - String showfull = request.getParameter("showfull"); - - // if the user selected showsimple, remove showfull. - if (showfull != null && request.getParameter("showsimple") != null) + this.requireWorkflow = true; + } + + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + // Get any metadata that may be removed by unselecting one of these options. + Item item = submission.getItem(); + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/" + collection.getHandle() + + "/workflow"; + int state = ((BasicWorkflowItem) submission).getState(); + + Request request = ObjectModelHelper.getRequest(objectModel); + String showfull = request.getParameter("showfull"); + + // if the user selected showsimple, remove showfull. + if (showfull != null && request.getParameter("showsimple") != null) { showfull = null; } - - - // Generate a from asking the user two questions: multiple + + + // Generate a from asking the user two questions: multiple // titles & published before. - Division div = body.addInteractiveDivision("perform-task", actionURL, Division.METHOD_POST, "primary workflow"); + Division div = body.addInteractiveDivision("perform-task", actionURL, + Division.METHOD_POST, "primary workflow"); div.setHead(T_workflow_head); - - + + if (showfull == null) { - ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW); - referenceSet.addReference(item); - div.addPara().addButton("showfull").setValue(T_showfull); - } + ReferenceSet referenceSet = div.addReferenceSet("narf", + ReferenceSet.TYPE_SUMMARY_VIEW); + referenceSet.addReference(item); + div.addPara().addButton("showfull").setValue(T_showfull); + } else { - ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_DETAIL_VIEW); + ReferenceSet referenceSet = div.addReferenceSet("narf", + ReferenceSet.TYPE_DETAIL_VIEW); referenceSet.addReference(item); div.addPara().addButton("showsimple").setValue(T_showsimple); - + div.addHidden("showfull").setValue("true"); } - - + + // FIXME: set the correct table size. Table table = div.addTable("workflow-actions", 1, 1); table.setHead(T_info1); - + // Header Row row; if (state == WFSTATE_STEP1POOL || - state == WFSTATE_STEP2POOL || - state == WFSTATE_STEP3POOL) + state == WFSTATE_STEP2POOL || + state == WFSTATE_STEP3POOL) { - // Take task - row = table.addRow(); - row.addCellContent(T_take_help); - row.addCell().addButton("submit_take_task").setValue(T_take_submit); - - // Leave task - row = table.addRow(); - row.addCellContent(T_leave_help); - row.addCell().addButton("submit_leave").setValue(T_leave_submit); + // Take task + row = table.addRow(); + row.addCellContent(T_take_help); + row.addCell().addButton("submit_take_task").setValue(T_take_submit); + + // Leave task + row = table.addRow(); + row.addCellContent(T_leave_help); + row.addCell().addButton("submit_leave").setValue(T_leave_submit); } - + if (state == WFSTATE_STEP1 || - state == WFSTATE_STEP2) + state == WFSTATE_STEP2) { - // Approve task - row = table.addRow(); - row.addCellContent(T_approve_help); - row.addCell().addButton("submit_approve").setValue(T_approve_submit); + // Approve task + row = table.addRow(); + row.addCellContent(T_approve_help); + row.addCell().addButton("submit_approve").setValue(T_approve_submit); } - + if (state == WFSTATE_STEP3) { - // Commit to archive - row = table.addRow(); - row.addCellContent(T_commit_help); - row.addCell().addButton("submit_approve").setValue(T_commit_submit); + // Commit to archive + row = table.addRow(); + row.addCellContent(T_commit_help); + row.addCell().addButton("submit_approve").setValue(T_commit_submit); } - + if (state == WFSTATE_STEP1 || - state == WFSTATE_STEP2) + state == WFSTATE_STEP2) { - // Reject item - row = table.addRow(); - row.addCellContent(T_reject_help); - row.addCell().addButton("submit_reject").setValue(T_reject_submit); + // Reject item + row = table.addRow(); + row.addCellContent(T_reject_help); + row.addCell().addButton("submit_reject").setValue(T_reject_submit); } - + if (state == WFSTATE_STEP2 || - state == WFSTATE_STEP3 ) + state == WFSTATE_STEP3 ) { - // Edit metadata - row = table.addRow(); - row.addCellContent(T_edit_help); - row.addCell().addButton("submit_edit").setValue(T_edit_submit); + // Edit metadata + row = table.addRow(); + row.addCellContent(T_edit_help); + row.addCell().addButton("submit_edit").setValue(T_edit_submit); } - + if (state == WFSTATE_STEP1 || state == WFSTATE_STEP2 || state == WFSTATE_STEP3 ) { - // Return to pool - row = table.addRow(); - row.addCellContent(T_return_help); - row.addCell().addButton("submit_return").setValue(T_return_submit); + // Return to pool + row = table.addRow(); + row.addCellContent(T_return_help); + row.addCell().addButton("submit_return").setValue(T_return_submit); } - - + + // Everyone can just cancel row = table.addRow(); row.addCell(0, 2).addButton("submit_leave").setValue(T_cancel_submit); - - div.addHidden("submission-continue").setValue(knot.getId()); + + div.addHidden("submission-continue").setValue(knot.getId()); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/RejectTaskStep.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/RejectTaskStep.java index f8d04e8194..462ad4b2b0 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/RejectTaskStep.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/RejectTaskStep.java @@ -32,7 +32,7 @@ import org.xml.sax.SAXException; * This step is used when the user has selected to * reject the item. Here they are asked to enter * a reason why the item should be rejected. - * + * * @author Scott Phillips */ public class RejectTaskStep extends AbstractStep @@ -40,70 +40,72 @@ public class RejectTaskStep extends AbstractStep private static final Logger log = Logger.getLogger(RejectTaskStep.class); /** Language Strings **/ - protected static final Message T_info1 = + protected static final Message T_info1 = message("xmlui.Submission.workflow.RejectTaskStep.info1"); - protected static final Message T_reason = + protected static final Message T_reason = message("xmlui.Submission.workflow.RejectTaskStep.reason"); - protected static final Message T_reason_required = + protected static final Message T_reason_required = message("xmlui.Submission.workflow.RejectTaskStep.reason_required"); - protected static final Message T_submit_reject = + protected static final Message T_submit_reject = message("xmlui.Submission.workflow.RejectTaskStep.submit_reject"); - protected static final Message T_submit_cancel = + protected static final Message T_submit_cancel = message("xmlui.general.cancel"); - - - - - /** - * Establish our required parameters, abstractStep will enforce these. - */ - public RejectTaskStep() - { - this.requireWorkflow = true; - } - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + + + + + /** + * Establish our required parameters, abstractStep will enforce these. + */ + public RejectTaskStep() { - Item item = submission.getItem(); - Collection collection = submission.getCollection(); - String actionURL = contextPath + "/handle/"+collection.getHandle() + "/workflow"; - - Request request = ObjectModelHelper.getRequest(objectModel); - String showfull = request.getParameter("showfull"); - - // if the user selected showsimple, remove showfull. - if (showfull != null && request.getParameter("showsimple") != null) + this.requireWorkflow = true; + } + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + Item item = submission.getItem(); + Collection collection = submission.getCollection(); + String actionURL = contextPath + "/handle/"+collection.getHandle() + "/workflow"; + + Request request = ObjectModelHelper.getRequest(objectModel); + String showfull = request.getParameter("showfull"); + + // if the user selected showsimple, remove showfull. + if (showfull != null && request.getParameter("showsimple") != null) { showfull = null; } - - - Division div = body.addInteractiveDivision("reject-task", actionURL, Division.METHOD_POST, "primary workflow"); + + + Division div = body.addInteractiveDivision("reject-task", actionURL, + Division.METHOD_POST, "primary workflow"); div.setHead(T_workflow_head); - - + + if (showfull == null) { - ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW); - referenceSet.addReference(item); - div.addPara().addButton("showfull").setValue(T_showfull); - } + ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW); + referenceSet.addReference(item); + div.addPara().addButton("showfull").setValue(T_showfull); + } else { ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_DETAIL_VIEW); referenceSet.addReference(item); div.addPara().addButton("showsimple").setValue(T_showsimple); - + div.addHidden("showfull").setValue("true"); } - + List form = div.addList("reject-workflow",List.TYPE_FORM); - + form.addItem(T_info1); - + TextArea reason = form.addItem().addTextArea("reason"); reason.setLabel(T_reason); reason.setRequired(); @@ -112,15 +114,15 @@ public class RejectTaskStep extends AbstractStep { reason.addError(T_reason_required); } - + org.dspace.app.xmlui.wing.element.Item actions = form.addItem(); actions.addButton("submit_reject").setValue(T_submit_reject); actions.addButton("submit_cancel").setValue(T_submit_cancel); - - div.addHidden("submission-continue").setValue(knot.getId()); + + div.addHidden("submission-continue").setValue(knot.getId()); log.info(LogManager.getHeader(context, "get_reject_reason", - "workflow_id=" + submission.getID() + ",item_id=" - + item.getID())); + "workflow_id=" + submission.getID() + + ",item_id=" + item.getID())); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/Submissions.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/Submissions.java index 9a72f48705..2ec545b026 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/Submissions.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/Submissions.java @@ -30,7 +30,7 @@ import java.util.List; */ public class Submissions extends AbstractDSpaceTransformer { - /** General Language Strings */ + /** General Language Strings */ protected static final Message T_title = message("xmlui.Submission.Submissions.title"); protected static final Message T_dspace_home = @@ -72,7 +72,7 @@ public class Submissions extends AbstractDSpaceTransformer protected static final Message T_w_info3 = message("xmlui.Submission.Submissions.workflow_info3"); - // Used in the in progress section + // Used in the in progress section protected static final Message T_p_head1 = message("xmlui.Submission.Submissions.progress_head1"); protected static final Message T_p_info1 = @@ -109,22 +109,24 @@ public class Submissions extends AbstractDSpaceTransformer @Override - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException - { - pageMeta.addMetadata("title").addContent(T_title); + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + pageMeta.addMetadata("title").addContent(T_title); - pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - pageMeta.addTrailLink(contextPath + "/submissions",T_trail); - } + pageMeta.addTrailLink(contextPath + "/",T_dspace_home); + pageMeta.addTrailLink(contextPath + "/submissions",T_trail); + } @Override - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - Division div = body.addInteractiveDivision("submissions", contextPath+"/submissions", Division.METHOD_POST,"primary"); + Division div = body.addInteractiveDivision("submissions", + contextPath + "/submissions", Division.METHOD_POST, "primary"); div.setHead(T_head); this.addWorkflowTasks(div); @@ -142,28 +144,29 @@ public class Submissions extends AbstractDSpaceTransformer * * @param division The division to add the two queues too. */ - private void addWorkflowTasks(Division division) throws SQLException, WingException + private void addWorkflowTasks(Division division) + throws SQLException, WingException { - @SuppressWarnings("unchecked") // This cast is correct - List ownedItems = basicWorkflowService.getOwnedTasks(context, context - .getCurrentUser()); - @SuppressWarnings("unchecked") // This cast is correct. - List pooledItems = basicWorkflowService.getPooledTasks(context, context - .getCurrentUser()); + @SuppressWarnings("unchecked") // This cast is correct + List ownedItems = basicWorkflowService.getOwnedTasks( + context, context.getCurrentUser()); + @SuppressWarnings("unchecked") // This cast is correct. + List pooledItems = basicWorkflowService.getPooledTasks( + context, context.getCurrentUser()); - if (!(ownedItems.size() > 0 || pooledItems.size() > 0)) - // No tasks, so don't show the table. + if (!(ownedItems.size() > 0 || pooledItems.size() > 0)) + // No tasks, so don't show the table. { return; } - Division workflow = division.addDivision("workflow-tasks"); - workflow.setHead(T_w_head1); - workflow.addPara(T_w_info1); + Division workflow = division.addDivision("workflow-tasks"); + workflow.setHead(T_w_head1); + workflow.addPara(T_w_info1); - // Tasks you own - Table table = workflow.addTable("workflow-tasks",ownedItems.size() + 2,5); + // Tasks you own + Table table = workflow.addTable("workflow-tasks",ownedItems.size() + 2,5); table.setHead(T_w_head2); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_w_column1); @@ -174,65 +177,66 @@ public class Submissions extends AbstractDSpaceTransformer if (ownedItems.size() > 0) { - for (BasicWorkflowItem owned : ownedItems) - { - int workflowItemID = owned.getID(); - String collectionUrl = contextPath + "/handle/" + owned.getCollection().getHandle(); - String ownedWorkflowItemUrl = contextPath + "/handle/" + owned.getCollection().getHandle() + "/workflow?workflowID=" + workflowItemID; - String title = owned.getItem().getName(); - String collectionName = owned.getCollection().getName(); - EPerson submitter = owned.getSubmitter(); - String submitterName = submitter.getFullName(); - String submitterEmail = submitter.getEmail(); + for (BasicWorkflowItem owned : ownedItems) + { + int workflowItemID = owned.getID(); + String collectionUrl = contextPath + "/handle/" + + owned.getCollection().getHandle(); + String ownedWorkflowItemUrl = contextPath + "/handle/" + + owned.getCollection().getHandle() + + "/workflow?workflowID=" + workflowItemID; + String title = owned.getItem().getName(); + String collectionName = owned.getCollection().getName(); + EPerson submitter = owned.getSubmitter(); + String submitterName = submitter.getFullName(); + String submitterEmail = submitter.getEmail(); - Message state = getWorkflowStateMessage(owned); + Message state = getWorkflowStateMessage(owned); - Row row = table.addRow(); + Row row = table.addRow(); - CheckBox remove = row.addCell().addCheckBox("workflowID"); - remove.setLabel("selected"); - remove.addOption(workflowItemID); + CheckBox remove = row.addCell().addCheckBox("workflowID"); + remove.setLabel("selected"); + remove.addOption(workflowItemID); - // The task description - row.addCell().addXref(ownedWorkflowItemUrl, state); + // The task description + row.addCell().addXref(ownedWorkflowItemUrl, state); - // The item description - if (StringUtils.isNotBlank(title)) - { - String displayTitle = title; - if (displayTitle.length() > 50) + // The item description + if (StringUtils.isNotBlank(title)) + { + String displayTitle = title; + if (displayTitle.length() > 50) { displayTitle = displayTitle.substring(0, 50) + " ..."; } - row.addCell().addXref(ownedWorkflowItemUrl, displayTitle); - } - else + row.addCell().addXref(ownedWorkflowItemUrl, displayTitle); + } + else { row.addCell().addXref(ownedWorkflowItemUrl, T_untitled); } - // Submitted too - row.addCell().addXref(collectionUrl, collectionName); + // Submitted too + row.addCell().addXref(collectionUrl, collectionName); - // Submitted by - Cell cell = row.addCell(); - cell.addContent(T_email); - cell.addXref("mailto:"+submitterEmail,submitterName); - } + // Submitted by + Cell cell = row.addCell(); + cell.addContent(T_email); + cell.addXref("mailto:"+submitterEmail,submitterName); + } - Row row = table.addRow(); - row.addCell(0,5).addButton("submit_return_tasks").setValue(T_w_submit_return); + Row row = table.addRow(); + row.addCell(0,5).addButton("submit_return_tasks").setValue(T_w_submit_return); } else { - Row row = table.addRow(); - row.addCell(0,5).addHighlight("italic").addContent(T_w_info2); + Row row = table.addRow(); + row.addCell(0,5).addHighlight("italic").addContent(T_w_info2); } - - // Tasks in the pool table = workflow.addTable("workflow-tasks",pooledItems.size()+2,5); table.setHead(T_w_head3); @@ -247,64 +251,65 @@ public class Submissions extends AbstractDSpaceTransformer if (pooledItems.size() > 0) { - for (BasicWorkflowItem pooled : pooledItems) - { - int workflowItemID = pooled.getID(); - String collectionUrl = contextPath + "/handle/" + pooled.getCollection().getHandle(); - String pooledItemUrl = contextPath + "/handle/" + pooled.getCollection().getHandle() + "/workflow?workflowID=" + workflowItemID; - String title = pooled.getItem().getName(); - String collectionName = pooled.getCollection().getName(); - EPerson submitter = pooled.getSubmitter(); - String submitterName = submitter.getFullName(); - String submitterEmail = submitter.getEmail(); + for (BasicWorkflowItem pooled : pooledItems) + { + int workflowItemID = pooled.getID(); + String collectionUrl = contextPath + "/handle/" + pooled.getCollection().getHandle(); + String pooledItemUrl = contextPath + "/handle/" + pooled.getCollection().getHandle() + "/workflow?workflowID=" + workflowItemID; + String title = pooled.getItem().getName(); + String collectionName = pooled.getCollection().getName(); + EPerson submitter = pooled.getSubmitter(); + String submitterName = submitter.getFullName(); + String submitterEmail = submitter.getEmail(); - Message state = getWorkflowStateMessage(pooled); + Message state = getWorkflowStateMessage(pooled); - Row row = table.addRow(); + Row row = table.addRow(); - CheckBox remove = row.addCell().addCheckBox("workflowID"); - remove.setLabel("selected"); - remove.addOption(workflowItemID); + CheckBox remove = row.addCell().addCheckBox("workflowID"); + remove.setLabel("selected"); + remove.addOption(workflowItemID); - // The task description - row.addCell().addXref(pooledItemUrl, state); + // The task description + row.addCell().addXref(pooledItemUrl, state); - // The item description - if (StringUtils.isNotBlank(title)) - { - String displayTitle = title; - if (displayTitle.length() > 50) + // The item description + if (StringUtils.isNotBlank(title)) + { + String displayTitle = title; + if (displayTitle.length() > 50) { displayTitle = displayTitle.substring(0, 50) + " ..."; } - row.addCell().addXref(pooledItemUrl, displayTitle); - } - else + row.addCell().addXref(pooledItemUrl, displayTitle); + } + else { row.addCell().addXref(pooledItemUrl, T_untitled); } - // Submitted too - row.addCell().addXref(collectionUrl, collectionName); + // Submitted too + row.addCell().addXref(collectionUrl, collectionName); - // Submitted by - Cell cell = row.addCell(); - cell.addContent(T_email); - cell.addXref("mailto:"+submitterEmail,submitterName); + // Submitted by + Cell cell = row.addCell(); + cell.addContent(T_email); + cell.addXref("mailto:"+submitterEmail,submitterName); - } - Row row = table.addRow(); - row.addCell(0,5).addButton("submit_take_tasks").setValue(T_w_submit_take); + } + Row row = table.addRow(); + row.addCell(0,5).addButton("submit_take_tasks").setValue(T_w_submit_take); } else { - Row row = table.addRow(); - row.addCell(0,5).addHighlight("italic").addContent(T_w_info3); + Row row = table.addRow(); + row.addCell(0,5).addHighlight("italic").addContent(T_w_info3); } } + /** * There are two options, the user has some unfinished submissions * or the user does not. @@ -316,33 +321,36 @@ public class Submissions extends AbstractDSpaceTransformer * presented listing all the unfinished submissions that this user has. * */ - private void addUnfinishedSubmissions(Division division) throws SQLException, WingException + private void addUnfinishedSubmissions(Division division) + throws SQLException, WingException { - division.addInteractiveDivision("unfinished-submisions", contextPath+"/submit", Division.METHOD_POST); - + division.addInteractiveDivision("unfinished-submisions", + contextPath + "/submit", Division.METHOD_POST); } + /** * This section lists all the submissions that this user has submitted which are currently under review. * * If the user has none, this nothing is displayed. */ - private void addSubmissionsInWorkflow(Division division) throws SQLException, WingException + private void addSubmissionsInWorkflow(Division division) + throws SQLException, WingException { - List inprogressItems = basicWorkflowItemService.findBySubmitter(context, context.getCurrentUser()); + List inprogressItems = basicWorkflowItemService.findBySubmitter(context, context.getCurrentUser()); - // If there is nothing in progress then don't add anything. - if (!(inprogressItems.size() > 0)) + // If there is nothing in progress then don't add anything. + if (!(inprogressItems.size() > 0)) { return; } - Division inprogress = division.addDivision("submissions-inprogress"); - inprogress.setHead(T_p_head1); - inprogress.addPara(T_p_info1); + Division inprogress = division.addDivision("submissions-inprogress"); + inprogress.setHead(T_p_head1); + inprogress.addPara(T_p_info1); - Table table = inprogress.addTable("submissions-inprogress",inprogressItems.size()+1,3); + Table table = inprogress.addTable("submissions-inprogress",inprogressItems.size()+1,3); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_p_column1); header.addCellContent(T_p_column2); @@ -353,38 +361,35 @@ public class Submissions extends AbstractDSpaceTransformer { String title = workflowItem.getItem().getName(); String collectionName = workflowItem.getCollection().getName(); - Message state = getWorkflowStateMessage(workflowItem); + Message state = getWorkflowStateMessage(workflowItem); - Row row = table.addRow(); + Row row = table.addRow(); - // Add the title column - if (title.length() > 0) - { - String displayTitle = title; - if (displayTitle.length() > 50) + // Add the title column + if (title.length() > 0) + { + String displayTitle = title; + if (displayTitle.length() > 50) { displayTitle = displayTitle.substring(0, 50) + " ..."; } - row.addCellContent(displayTitle); - } - else + row.addCellContent(displayTitle); + } + else { row.addCellContent(T_untitled); } - // Collection name column - row.addCellContent(collectionName); + // Collection name column + row.addCellContent(collectionName); - // Status column - row.addCellContent(state); + // Status column + row.addCellContent(state); } } - - - /** * Determine the correct message that describes this workflow item's state. * @@ -392,27 +397,27 @@ public class Submissions extends AbstractDSpaceTransformer */ private Message getWorkflowStateMessage(BasicWorkflowItem workflowItem) { - switch (workflowItem.getState()) - { - case BasicWorkflowService.WFSTATE_SUBMIT: - return T_status_0; - case BasicWorkflowService.WFSTATE_STEP1POOL: - return T_status_1; - case BasicWorkflowService.WFSTATE_STEP1: - return T_status_2; - case BasicWorkflowService.WFSTATE_STEP2POOL: - return T_status_3; - case BasicWorkflowService.WFSTATE_STEP2: - return T_status_4; - case BasicWorkflowService.WFSTATE_STEP3POOL: - return T_status_5; - case BasicWorkflowService.WFSTATE_STEP3: - return T_status_6; - case BasicWorkflowService.WFSTATE_ARCHIVE: - return T_status_7; - default: - return T_status_unknown; - } + switch (workflowItem.getState()) + { + case BasicWorkflowService.WFSTATE_SUBMIT: + return T_status_0; + case BasicWorkflowService.WFSTATE_STEP1POOL: + return T_status_1; + case BasicWorkflowService.WFSTATE_STEP1: + return T_status_2; + case BasicWorkflowService.WFSTATE_STEP2POOL: + return T_status_3; + case BasicWorkflowService.WFSTATE_STEP2: + return T_status_4; + case BasicWorkflowService.WFSTATE_STEP3POOL: + return T_status_5; + case BasicWorkflowService.WFSTATE_STEP3: + return T_status_6; + case BasicWorkflowService.WFSTATE_ARCHIVE: + return T_status_7; + default: + return T_status_unknown; + } } /** @@ -425,9 +430,8 @@ public class Submissions extends AbstractDSpaceTransformer * @param division div to put archived submissions in */ private void addPreviousSubmissions(Division division) - throws SQLException,WingException + throws SQLException,WingException { division.addDivision("completed-submissions"); - } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/UnclaimTasksAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/UnclaimTasksAction.java index c44c0b06cb..2804f226cc 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/UnclaimTasksAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/workflow/UnclaimTasksAction.java @@ -28,16 +28,16 @@ import org.dspace.workflowbasic.service.BasicWorkflowService; /** * Unclaim all the selected workflows. This action returns these * tasks to the general pool for other users to select from. - * - * + * + * * @author Scott Phillips */ public class UnclaimTasksAction extends AbstractAction { private static final Logger log = Logger.getLogger(UnclaimTasksAction.class); - protected BasicWorkflowService basicWorkflowService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowService(); - protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService(); + protected BasicWorkflowService basicWorkflowService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowService(); + protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService(); /** * Unclaim-tasks action. @@ -57,33 +57,33 @@ public class UnclaimTasksAction extends AbstractAction */ @Override public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, - String source, Parameters parameters) throws Exception + String source, Parameters parameters) + throws Exception { Request request = ObjectModelHelper.getRequest(objectModel); Context context = ContextUtil.obtainContext(objectModel); - - // Or the user selected a checkbox full of workflow IDs - String[] workflowIDs = request.getParameterValues("workflowID"); - if (workflowIDs != null) - { - for (String workflowID : workflowIDs) - { - BasicWorkflowItem workflowItem = basicWorkflowItemService.find(context, Integer.valueOf(workflowID)); - //workflowItem.get - - int state = workflowItem.getState(); - // only claim tasks that are in the pool. - if ( state == BasicWorkflowServiceImpl.WFSTATE_STEP1 || - state == BasicWorkflowServiceImpl.WFSTATE_STEP2 || - state == BasicWorkflowServiceImpl.WFSTATE_STEP3 ) - { - log.info(LogManager.getHeader(context, "unclaim_workflow", "workflow_id=" + workflowItem.getID())); - basicWorkflowService.unclaim(context, workflowItem, context.getCurrentUser()); - } - } - } - - return null; - } + // Or the user selected a checkbox full of workflow IDs + String[] workflowIDs = request.getParameterValues("workflowID"); + if (workflowIDs != null) + { + for (String workflowID : workflowIDs) + { + BasicWorkflowItem workflowItem = basicWorkflowItemService.find(context, Integer.valueOf(workflowID)); + //workflowItem.get + + int state = workflowItem.getState(); + // only claim tasks that are in the pool. + if ( state == BasicWorkflowServiceImpl.WFSTATE_STEP1 || + state == BasicWorkflowServiceImpl.WFSTATE_STEP2 || + state == BasicWorkflowServiceImpl.WFSTATE_STEP3 ) + { + log.info(LogManager.getHeader(context, "unclaim_workflow", "workflow_id=" + workflowItem.getID())); + basicWorkflowService.unclaim(context, workflowItem, context.getCurrentUser()); + } + } + } + + return null; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/AdvancedFormTest.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/AdvancedFormTest.java index 988f16afb2..ead6d2d5d9 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/AdvancedFormTest.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/AdvancedFormTest.java @@ -28,136 +28,139 @@ import org.dspace.authorize.AuthorizeException; import org.xml.sax.SAXException; /** - * This is a class to test the advanced form capabilities of DRI. - * All the fields on this page will either be composite or have + * This is a class to test the advanced form capabilities of DRI. + * All the fields on this page will either be composite or have * multiple instances. - * + * * This class is not internationalized because it is never intended * to be used in production. It is merely a tool to aid developers of * aspects and themes. - * + * * @author Scott Phillips */ public class AdvancedFormTest extends AbstractDSpaceTransformer { - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException { - pageMeta.addMetadata("title").addContent("Advanced Form Test"); + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + pageMeta.addMetadata("title").addContent("Advanced Form Test"); - pageMeta.addTrailLink(contextPath + "/", "DSpace Home"); - pageMeta.addTrail().addContent("Advanced Form Test"); - } + pageMeta.addTrailLink(contextPath + "/", "DSpace Home"); + pageMeta.addTrail().addContent("Advanced Form Test"); + } - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException { - - Request request = ObjectModelHelper.getRequest(objectModel); - boolean help = false, error = false; - if (request.getParameter("help") != null) + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + + Request request = ObjectModelHelper.getRequest(objectModel); + boolean help = false, error = false; + if (request.getParameter("help") != null) { help = true; } - if (request.getParameter("error") != null) + if (request.getParameter("error") != null) { error = true; } - - Division div = body.addInteractiveDivision("test", "", "post", "primary"); - div.setHead("Advanced form test"); - div.addPara("There are two options you can use to control how this page is generated. First is the help parameter, if this is present then help text will be provided for all fields. Next is the error parameter, if it is provided then all fields will be generated in error conditions."); - - if (help) + + Division div = body.addInteractiveDivision("test", "", "post", "primary"); + div.setHead("Advanced form test"); + div.addPara("There are two options you can use to control how this page is generated. First is the help parameter, if this is present then help text will be provided for all fields. Next is the error parameter, if it is provided then all fields will be generated in error conditions."); + + if (help) { div.addPara().addXref(makeURL(false, error), "Turn help OFF"); } - else + else { div.addPara().addXref(makeURL(true, error), "Turn help ON"); } - - if (error) + + if (error) { div.addPara().addXref(makeURL(help, false), "Turn errors OFF"); } - else + else { div.addPara().addXref(makeURL(help, true), "Turn errors ON"); } - - - List list = div.addList("fieldTest",List.TYPE_FORM); - list.setHead("Tests"); - - // text - Text text = list.addItem().addText("text"); - text.setLabel("Text"); - text.enableAddOperation(); - text.enableDeleteOperation(); - if (help) + + + List list = div.addList("fieldTest",List.TYPE_FORM); + list.setHead("Tests"); + + // text + Text text = list.addItem().addText("text"); + text.setLabel("Text"); + text.enableAddOperation(); + text.enableDeleteOperation(); + if (help) { text.setHelp("This is helpful text."); } - if (error) + if (error) { text.addError("This field is in error."); } - text.setValue("First is special"); - Instance instance = text.addInstance(); - instance.setValue("Second raw"); - instance.setInterpretedValue("Second interpreted"); - instance = text.addInstance(); - instance.setValue("Third raw"); - instance.setInterpretedValue("Third interpreted"); + text.setValue("First is special"); + Instance instance = text.addInstance(); + instance.setValue("Second raw"); + instance.setInterpretedValue("Second interpreted"); + instance = text.addInstance(); + instance.setValue("Third raw"); + instance.setInterpretedValue("Third interpreted"); - // Select - Select select = list.addItem().addSelect("select"); - select.setLabel("Text"); - select.enableAddOperation(); - select.enableDeleteOperation(); - select.setMultiple(); - select.setSize(4); - if (help) + // Select + Select select = list.addItem().addSelect("select"); + select.setLabel("Text"); + select.enableAddOperation(); + select.enableDeleteOperation(); + select.setMultiple(); + select.setSize(4); + if (help) { select.setHelp("This is helpful text."); } - if (error) + if (error) { select.addError("This field is in error."); } - select.addOption("one", "uno"); - select.addOption("two", "dos"); - select.addOption("three", "tres"); - select.addOption("four", "cuatro"); - select.addOption("five", "cinco"); - - instance = select.addInstance(); - instance.setOptionSelected("one"); - - instance = select.addInstance(); - instance.setOptionSelected("one"); - instance.setOptionSelected("two"); - - instance = select.addInstance(); - instance.setOptionSelected("one"); - instance.setOptionSelected("two"); - instance.setOptionSelected("three"); - - instance = select.addInstance(); - instance.setOptionSelected("one"); - instance.setOptionSelected("two"); - instance.setOptionSelected("three"); - instance.setOptionSelected("four"); - - instance = select.addInstance(); - instance.setOptionSelected("one"); - instance.setOptionSelected("two"); - instance.setOptionSelected("three"); - instance.setOptionSelected("four"); - instance.setOptionSelected("five"); - + select.addOption("one", "uno"); + select.addOption("two", "dos"); + select.addOption("three", "tres"); + select.addOption("four", "cuatro"); + select.addOption("five", "cinco"); - // composite two text fields + instance = select.addInstance(); + instance.setOptionSelected("one"); + + instance = select.addInstance(); + instance.setOptionSelected("one"); + instance.setOptionSelected("two"); + + instance = select.addInstance(); + instance.setOptionSelected("one"); + instance.setOptionSelected("two"); + instance.setOptionSelected("three"); + + instance = select.addInstance(); + instance.setOptionSelected("one"); + instance.setOptionSelected("two"); + instance.setOptionSelected("three"); + instance.setOptionSelected("four"); + + instance = select.addInstance(); + instance.setOptionSelected("one"); + instance.setOptionSelected("two"); + instance.setOptionSelected("three"); + instance.setOptionSelected("four"); + instance.setOptionSelected("five"); + + + // composite two text fields Composite composite = list.addItem().addComposite("compositeA"); composite.setLabel("Composite (two text fields)"); composite.enableAddOperation(); @@ -178,7 +181,7 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { text.addInstance().setValue("1, Raw A"); text.addInstance().setValue("2, Raw A"); text.addInstance().setValue("3, Raw A"); - + text = composite.addText("secondA"); if (help) { @@ -187,7 +190,7 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { text.addInstance().setValue("1, Raw B"); text.addInstance().setValue("2, Raw B"); text.addInstance().setValue("3, Raw B"); - + // composite select & text fields composite = list.addItem().addComposite("compositeB"); composite.setLabel("Composite (select & text fields)"); @@ -197,7 +200,7 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { { composite.setHelp("This field is composed of a select and text field, select one and type the other."); } - + select = composite.addSelect("selectB"); if (help) { @@ -213,11 +216,11 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { select.addOption("four","cuatro"); select.addOption("five","cinco"); select.setOptionSelected("one"); - + select.addInstance().addOptionValue("one"); select.addInstance().addOptionValue("two"); select.addInstance().addOptionValue("three"); - + text = composite.addText("TextB"); if (help) { @@ -230,11 +233,11 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { text.addInstance().setValue("1, Raw B"); text.addInstance().setValue("2, Raw B"); text.addInstance().setValue("3, Raw B"); - + composite.addInstance().setInterpretedValue("One interpreted."); composite.addInstance().setInterpretedValue("Two interpreted."); composite.addInstance().setInterpretedValue("Three interpreted."); - + // Composite (date) composite = list.addItem().addComposite("composite-date"); composite.setLabel("Composite (date)"); @@ -248,7 +251,7 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { { composite.setHelp("The composite is in error."); } - + text = composite.addText("day"); if (help) { @@ -259,13 +262,13 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { text.setHelp("The first text field is in error."); } text.setSize(4,2); - + text.addInstance().setValue("1"); text.addInstance().setValue("2"); text.addInstance().setValue("3"); text.addInstance().setValue("4"); text.addInstance().setValue("5"); - + select = composite.addSelect("month"); if (error) { @@ -285,13 +288,13 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { select.addOption(11,"October"); select.addOption(12,"November"); select.addOption(13,"December"); - + select.addInstance().setOptionSelected(1); select.addInstance().setOptionSelected(2); select.addInstance().setOptionSelected(3); select.addInstance().setOptionSelected(4); select.addInstance().setOptionSelected(5); - + text = composite.addText("year"); text.setSize(4,4); if (help) @@ -307,35 +310,34 @@ public class AdvancedFormTest extends AbstractDSpaceTransformer { text.addInstance().setValue("2003"); text.addInstance().setValue("2004"); text.addInstance().setValue("2005"); - + // Buttons one typical finds at the end of forums Item actions = list.addItem(); actions.addButton("submit_save").setValue("Save"); actions.addButton("submit_cancel").setValue("Cancel"); - } - + } + /** - * Helpful method to generate the return url to this page given the - * error & help parameters. + * Helpful method to generate the return url to this page given the + * error and help parameters. */ - private String makeURL(boolean help, boolean error) - { - if (help && error) + private String makeURL(boolean help, boolean error) + { + if (help && error) { return "?help&error"; } - - if (help) + + if (help) { return "?help"; } - - if (error) + + if (error) { return "?error"; } - - return "?neither"; - } - + + return "?neither"; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/BasicFormTest.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/BasicFormTest.java index 8865c55519..fb6c71bb62 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/BasicFormTest.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/BasicFormTest.java @@ -37,68 +37,69 @@ import org.xml.sax.SAXException; * This is a class to test the basic form capabilities of DRI. All * the fields used here will be simple and only used inside the * context of a form. - * + * * This class is not internationalized because it is never intended * to be used in production. It is merely a tool to aid developers of * aspects and themes. - * + * * @author Scott Phillips */ public class BasicFormTest extends AbstractDSpaceTransformer { - - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { pageMeta.addMetadata("title").addContent("Basic Form Test"); - + pageMeta.addTrailLink(contextPath + "/","DSpace Home"); pageMeta.addTrail().addContent("Basic form test"); } - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - Request request = ObjectModelHelper.getRequest(objectModel); - boolean help = false, error = false; - if (request.getParameter("help") != null) + Request request = ObjectModelHelper.getRequest(objectModel); + boolean help = false, error = false; + if (request.getParameter("help") != null) { help = true; } - if (request.getParameter("error") != null) + if (request.getParameter("error") != null) { error = true; } - - + + Division div = body.addInteractiveDivision("test", "", "post", "primary"); div.setHead("Basic form test"); div.addPara("There are two options you can use to control how this page is generated. First is the help parameter, if this is present then help text will be provided for all fields. Next is the error parameter, if it is provided then all fields will be generated in error conditions."); - - if (help) + + if (help) { div.addPara().addXref(makeURL(false, error), "Turn help OFF"); } - else + else { div.addPara().addXref(makeURL(true, error), "Turn help ON"); } - - if (error) + + if (error) { div.addPara().addXref(makeURL(help, false), "Turn errors OFF"); } - else + else { div.addPara().addXref(makeURL(help, true), "Turn errors ON"); } - + List list = div.addList("fieldTest",List.TYPE_FORM); list.setHead("Fields"); - + // Text field Text text = list.addItem().addText("text"); text.setLabel("Text"); @@ -111,7 +112,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer text.addError("This field is in error."); } text.setValue("Current raw value"); - + // Long help Text longHelp = list.addItem().addText("longHelp"); longHelp.setLabel("Long Help"); @@ -124,7 +125,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer longHelp.addError("This field is in error."); } longHelp.setValue("Current raw value"); - + // Long error Text longError = list.addItem().addText("longError"); longError.setLabel("Long Error"); @@ -137,7 +138,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer longError.addError("This field is very much is serious trouble, it's so horrible wrong that i now have to give you a very long stern message that may break across multiple lines! To fix this problem you should examine what you are attempting to do and consider other factors like what might have lead you to this path vs another path. Are you sure you even want this field or might another one work just as well?"); } longError.setValue("Current raw value"); - + // Text Area Field TextArea textArea = list.addItem().addTextArea("textarea"); textArea.setLabel("Text Area"); @@ -150,7 +151,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer textArea.addError("This field is in error."); } textArea.setValue("This is the raw value"); - + // Blank Text Area Field TextArea emptyTextArea = list.addItem().addTextArea("emptyTextarea"); emptyTextArea.setLabel("Empty Text Area"); @@ -162,8 +163,8 @@ public class BasicFormTest extends AbstractDSpaceTransformer { emptyTextArea.addError("This field is in error."); } - - + + // Password field Password password = list.addItem().addPassword("password"); password.setLabel("password"); @@ -175,7 +176,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer { password.addError("This field is in error."); } - + // Hidden field Hidden hidden = list.addItem().addHidden("hidden"); hidden.setLabel("Hidden"); @@ -188,7 +189,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer { hidden.addError("This a hidden error - I have no idea what this means?"); } - + // Checkbox field CheckBox checkBox = list.addItem().addCheckBox("fruit"); if (help) @@ -205,11 +206,11 @@ public class BasicFormTest extends AbstractDSpaceTransformer checkBox.addOption("pear","Pears"); checkBox.addOption("tootsie","Tootsie Roll"); checkBox.addOption(true,"cherry","Cherry"); - + // Radio buttons - + Radio radio = list.addItem().addRadio("sex"); - radio.setLabel("Football colors"); + radio.setLabel("Football colors"); if (help) { radio.setHelp("Select the colors of the best (college) football team."); @@ -224,7 +225,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer radio.addOption("baylor","Green & Gold"); radio.addOption("rice","Blue & Gray"); radio.addOption("uh","Scarlet Red & Albino White"); - + // File File file = list.addItem().addFile("file"); file.setLabel("File"); @@ -236,7 +237,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer { file.addError("This field is in error."); } - + // Select (single) Select select = list.addItem().addSelect("select"); select.setLabel("Select (single)"); @@ -273,13 +274,13 @@ public class BasicFormTest extends AbstractDSpaceTransformer select.addOption("four","cuatro"); select.addOption("five","cinco"); select.setOptionSelected("one"); - select.setOptionSelected("three"); + select.setOptionSelected("three"); select.setOptionSelected("five"); - + // Non-Field-item list.addLabel("Non-Field"); list.addItem().addContent("This is just text, not a field, but it has a list label."); - + // Button Button button = list.addItem().addButton("button"); button.setLabel("Button"); @@ -292,10 +293,10 @@ public class BasicFormTest extends AbstractDSpaceTransformer { button.addError("This button is in error."); } - + // Non-field-unlabeled-item list.addItem().addContent("The following fields are all various use cases of composites. Also note that this item is an item inside a list of type form that 1) does not contain a field and 2) does not have a label."); - + // Composite Composite composite = list.addItem().addComposite("composite-2text"); composite.setLabel("Composite (two text fields)"); @@ -321,15 +322,15 @@ public class BasicFormTest extends AbstractDSpaceTransformer { text.setHelp("Part B"); } - - // composite select & text fields + + // composite select & text fields composite = list.addItem().addComposite("compositeB"); composite.setLabel("Composite (select & text fields)"); if (help) { composite.setHelp("This field is composed of a select and text field, select one and type the other."); } - + select = composite.addSelect("selectB"); select.setLabel("Numbers"); if (help) @@ -346,7 +347,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer select.addOption("four","cuatro"); select.addOption("five","cinco"); select.setOptionSelected("one"); - + text = composite.addText("TextB"); text.setLabel("Spanish Numbers"); if (help) @@ -357,9 +358,9 @@ public class BasicFormTest extends AbstractDSpaceTransformer { text.addError("The composite components are in error."); } - - - // Composite + + + // Composite composite = list.addItem().addComposite("composite-date"); composite.setLabel("Composite (date)"); if (help) @@ -370,7 +371,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer { composite.addError("The date is in error."); } - + text = composite.addText("year"); text.setLabel("Year"); text.setSize(4,4); @@ -382,8 +383,8 @@ public class BasicFormTest extends AbstractDSpaceTransformer { text.addError("The year is in error"); } - - + + select = composite.addSelect("month"); select.setLabel("Month"); if (error) @@ -408,7 +409,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer select.addOption(11,"October"); select.addOption(12,"November"); select.addOption(13,"December"); - + text = composite.addText("day"); text.setLabel("Day"); if (help) @@ -420,26 +421,24 @@ public class BasicFormTest extends AbstractDSpaceTransformer text.addError("The day is in error."); } text.setSize(4,2); - + // Buttons one typical finds at the end of forums Item actions = list.addItem(); actions.addButton("submit_save").setValue("Save"); actions.addButton("submit_cancel").setValue("Cancel"); - - - - + + ///////////////////////////////////////////////// - /// Multi section + /// Multi section //////////////////////////////////////////////// - + div.addPara("This next test will use form sections. Sections are logical groupings of related fields that together form the entire set."); - + list = div.addList("sectionTest",List.TYPE_FORM); list.setHead("Multi-Section form"); List identity = list.addList("identity",List.TYPE_FORM); identity.setHead("Identity"); - + Text name = identity.addItem().addText("name"); name.setLabel("Username"); if (help) @@ -450,7 +449,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer { name.addError("Sorry, that username is already used by another user."); } - + Composite ssn = identity.addItem().addComposite("ssn"); ssn.setLabel("SSN"); if (help) @@ -467,10 +466,10 @@ public class BasicFormTest extends AbstractDSpaceTransformer ssn2.setSize(2,2); Text ssn3 = ssn.addText("ssn3"); ssn3.setSize(4,4); - + List interests = list.addList("interests",List.TYPE_FORM); interests.setHead("Interests"); - + CheckBox interest = interests.addItem().addCheckBox("interests"); interest.setLabel("Interests"); if (help) @@ -486,10 +485,10 @@ public class BasicFormTest extends AbstractDSpaceTransformer interest.addOption("IM","Information Managment"); interest.addOption("ID","Information Discovery"); interest.addOption("SI","Social Impact"); - + List affiliation = list.addList("affiliation",List.TYPE_FORM); affiliation.setHead("Affiliation"); - + Text institution = affiliation.addItem().addText("institution"); institution.setLabel("Institution"); if (help) @@ -500,7 +499,7 @@ public class BasicFormTest extends AbstractDSpaceTransformer { name.addError("That institution is an invalid option."); } - + Radio geography = affiliation.addItem().addRadio("geography"); geography.setLabel("Geography"); if (help) @@ -516,35 +515,35 @@ public class BasicFormTest extends AbstractDSpaceTransformer geography.addOption("eu","Europe"); geography.addOption("af","Africa"); geography.addOption("ai","Asia"); - geography.addOption("pi","Pacific Island"); + geography.addOption("pi","Pacific Island"); geography.addOption("an","Antarctica"); - + Item buttons = list.addItem(); buttons.addButton("submit_save2").setValue("Save"); buttons.addButton("submit_cancel2").setValue("Cancel"); } - + /** - * Helpful method to generate the return url to this page given the - * error & help parameters. + * Helpful method to generate the return url to this page given the + * error and help parameters. */ private String makeURL(boolean help, boolean error) - { - if (help && error) + { + if (help && error) { return "?help&error"; } - - if (help) + + if (help) { return "?help"; } - - if (error) + + if (error) { return "?error"; } - - return "?neither"; - } + + return "?neither"; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/InlineFormTest.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/InlineFormTest.java index cf8a1a87b6..90c1627357 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/InlineFormTest.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmltest/InlineFormTest.java @@ -31,74 +31,75 @@ import org.dspace.authorize.AuthorizeException; import org.xml.sax.SAXException; /** - * This is a class to test the use of form fields inline with normal + * This is a class to test the use of form fields inline with normal * paragraphs, lists, or tables. Any other location besides forms. - * + * * This class is not internationalized because it is never intended * to be used in production. It is merely a tool to aid developers of * aspects and themes. - * + * * @author Scott Phillips */ public class InlineFormTest extends AbstractDSpaceTransformer { - - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, UIException, SQLException, IOException, - AuthorizeException + + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { pageMeta.addMetadata("title").addContent("Inline Form Test"); - + pageMeta.addTrailLink(contextPath + "/","DSpace Home"); pageMeta.addTrail().addContent("Inline form test"); } - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - Request request = ObjectModelHelper.getRequest(objectModel); - boolean help = false, error = false; - if (request.getParameter("help") != null) + Request request = ObjectModelHelper.getRequest(objectModel); + boolean help = false, error = false; + if (request.getParameter("help") != null) { help = true; } - if (request.getParameter("error") != null) + if (request.getParameter("error") != null) { error = true; } - + Division div = body.addInteractiveDivision("test", "", "post", "primary"); div.setHead("Inline form test"); div.addPara("There are two options you can use to control how this page is generated. First is the help parameter, if this is present then help text will be provided for all fields. Next is the error parameter, if it is provided then all fields will be generated in error conditions."); - - if (help) + + if (help) { div.addPara().addXref(makeURL(false, error), "Turn help OFF"); } - else + else { div.addPara().addXref(makeURL(true, error), "Turn help ON"); } - - if (error) + + if (error) { div.addPara().addXref(makeURL(help, false), "Turn errors OFF"); } - else + else { div.addPara().addXref(makeURL(help, true), "Turn errors ON"); } - - - Division suited = body.addDivision("suited"); - suited.setHead("Fields suited towards being used inline"); - - suited.addPara("Below are a list of embedded fields that are normally considered usefully in an inline context."); - - // Text field - Para p = suited.addPara(); - p.addContent("This is a plain 'Text' field, "); + + + Division suited = body.addDivision("suited"); + suited.setHead("Fields suited towards being used inline"); + + suited.addPara("Below are a list of embedded fields that are normally considered usefully in an inline context."); + + // Text field + Para p = suited.addPara(); + p.addContent("This is a plain 'Text' field, "); Text text = p.addText("text"); text.setLabel("Text"); if (help) @@ -111,10 +112,10 @@ public class InlineFormTest extends AbstractDSpaceTransformer } text.setValue("Current raw value"); p.addContent(", embedded in a paragraph."); - + // Single Checkbox field p = suited.addPara(); - p.addContent("This is a single 'CheckBox' field, "); + p.addContent("This is a single 'CheckBox' field, "); CheckBox checkBox = p.addCheckBox("yes-or-no"); if (help) { @@ -127,10 +128,10 @@ public class InlineFormTest extends AbstractDSpaceTransformer checkBox.setLabel("Yes or no"); checkBox.addOption("yes"); p.addContent(", embedded in a paragraph."); - + // File p = suited.addPara(); - p.addContent("This is a 'File' field, "); + p.addContent("This is a 'File' field, "); File file = p.addFile("file"); file.setLabel("File"); if (help) @@ -142,10 +143,10 @@ public class InlineFormTest extends AbstractDSpaceTransformer file.addError("This field is in error."); } p.addContent(", embedded in a paragraph."); - + // Select (single) p = suited.addPara(); - p.addContent("This is single 'Select' (aka dropdown) field, "); + p.addContent("This is single 'Select' (aka dropdown) field, "); Select select = p.addSelect("select"); select.setLabel("Select (single)"); if (help) @@ -163,10 +164,10 @@ public class InlineFormTest extends AbstractDSpaceTransformer select.addOption("five","cinco"); select.setOptionSelected("one"); p.addContent(", embedded in a paragraph."); - + // Button p = suited.addPara(); - p.addContent("This is a 'Button' field, "); + p.addContent("This is a 'Button' field, "); Button button = p.addButton("button"); button.setLabel("Button"); button.setValue("When you touch me I do things, lots of things"); @@ -179,18 +180,18 @@ public class InlineFormTest extends AbstractDSpaceTransformer button.addError("This button is in error."); } p.addContent(", embedded in a paragraph."); - - - + + + Division unsuited = body.addDivision("unsuited"); unsuited.setHead("Fields typically unsuited towards being used inline"); - - unsuited.addPara("Below are a list of embedded fields that are normally considered useless in an inline context. This is because there widgets normally cross multiple lines making them hard to render inline. However these are all legal, but perhaps not advisable, and in some circumstances may be needed."); - + unsuited.addPara("Below are a list of embedded fields that are normally considered useless in an inline context. This is because there widgets normally cross multiple lines making them hard to render inline. However these are all legal, but perhaps not advisable, and in some circumstances may be needed."); + + // Text Area Field p = unsuited.addPara(); - p.addContent("This is a 'Text Area' field, "); + p.addContent("This is a 'Text Area' field, "); TextArea textArea = p.addTextArea("textarea"); textArea.setLabel("Text Area"); if (help) @@ -203,10 +204,10 @@ public class InlineFormTest extends AbstractDSpaceTransformer } textArea.setValue("This is the raw value"); p.addContent(", embedded in a paragraph."); - + // Multi-option Checkbox field p = unsuited.addPara(); - p.addContent("This is a multi-option 'CheckBox' field, "); + p.addContent("This is a multi-option 'CheckBox' field, "); checkBox = p.addCheckBox("fruit"); if (help) { @@ -223,12 +224,12 @@ public class InlineFormTest extends AbstractDSpaceTransformer checkBox.addOption("tootsie","Tootsie Roll"); checkBox.addOption(true,"cherry","Cherry"); p.addContent(", embedded in a paragraph."); - + // multi-option Radio field p = unsuited.addPara(); - p.addContent("This is a multi-option 'Radio' field, "); + p.addContent("This is a multi-option 'Radio' field, "); Radio radio = p.addRadio("sex"); - radio.setLabel("Football colors"); + radio.setLabel("Football colors"); if (help) { radio.setHelp("Select the colors of the best (college) football team."); @@ -247,7 +248,7 @@ public class InlineFormTest extends AbstractDSpaceTransformer // Select (multiple) p = unsuited.addPara(); - p.addContent("This is multiple 'Select' field, "); + p.addContent("This is multiple 'Select' field, "); select = p.addSelect("multi-select"); select.setLabel("Select (multiple)"); select.setMultiple(); @@ -266,13 +267,13 @@ public class InlineFormTest extends AbstractDSpaceTransformer select.addOption("four","cuatro"); select.addOption("five","cinco"); select.setOptionSelected("one"); - select.setOptionSelected("three"); + select.setOptionSelected("three"); select.setOptionSelected("five"); p.addContent(", embedded in a paragraph."); - + // Composite p = unsuited.addPara(); - p.addContent("This is a 'Composite' field of two text fields, "); + p.addContent("This is a 'Composite' field of two text fields, "); Composite composite = p.addComposite("composite-2text"); composite.setLabel("Composite (two text fields)"); if (help) @@ -298,32 +299,29 @@ public class InlineFormTest extends AbstractDSpaceTransformer text.setHelp("Part B"); } p.addContent(", embedded in a paragraph."); - - - } - + /** - * Helpful method to generate the return url to this page given the - * error & help parameters. + * Helpful method to generate the return url to this page given the + * error and help parameters. */ private String makeURL(boolean help, boolean error) - { - if (help && error) + { + if (help && error) { return "?help&error"; } - - if (help) + + if (help) { return "?help"; } - - if (error) + + if (error) { return "?error"; } - - return "?neither"; - } + + return "?neither"; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Navigation.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Navigation.java index 488c48c8b2..0327fc6cc0 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Navigation.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Navigation.java @@ -46,12 +46,12 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr private static final Message T_xmlworkflow_overview = message("xmlui.XMLWorkflow.Navigation.xmlworkflow_overview"); /** Cached validity object */ - private SourceValidity validity; + private SourceValidity validity; protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); - /** + /** * Generate the unique cache key. * * @return The generated key hashes the src @@ -88,45 +88,47 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr */ public SourceValidity getValidity() { - if (this.validity == null) - { - // Only use the DSpaceValidity object is someone is logged in. - if (context.getCurrentUser() != null) - { - try { - DSpaceValidity validity = new DSpaceValidity(); + if (this.validity == null) + { + // Only use the DSpaceValidity object is someone is logged in. + if (context.getCurrentUser() != null) + { + try + { + DSpaceValidity validity = new DSpaceValidity(); - validity.add(context, eperson); + validity.add(context, eperson); - java.util.List groups = groupService.allMemberGroups(context, eperson); - for (Group group : groups) - { - validity.add(context, group); - } + java.util.List groups = groupService.allMemberGroups(context, eperson); + for (Group group : groups) + { + validity.add(context, group); + } - this.validity = validity.complete(); - } - catch (SQLException sqle) - { - // Just ignore it and return invalid. - } - } - else - { - this.validity = NOPValidity.SHARED_INSTANCE; - } - } - return this.validity; + this.validity = validity.complete(); + } + catch (SQLException sqle) + { + // Just ignore it and return invalid. + } + } + else + { + this.validity = NOPValidity.SHARED_INSTANCE; + } + } + return this.validity; } - public void addOptions(Options options) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addOptions(Options options) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException { - /* Create skeleton menu structure to ensure consistent order between aspects, - * even if they are never used - */ + /* Create skeleton menu structure to ensure consistent order between aspects, + * even if they are never used + */ List admin = options.addList("administrative"); //Check if a system administrator @@ -136,7 +138,7 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr // System Administrator options! if (isSystemAdmin) { - admin.addItemXref(contextPath+ "/admin/xmlworkflowoverview", T_xmlworkflow_overview); + admin.addItemXref(contextPath+ "/admin/xmlworkflowoverview", T_xmlworkflow_overview); } } @@ -148,5 +150,4 @@ public class Navigation extends AbstractDSpaceTransformer implements CacheablePr this.validity = null; super.recycle(); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Submissions.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Submissions.java index 03bd8518fe..2b13057b9b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Submissions.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/xmlworkflow/Submissions.java @@ -43,7 +43,7 @@ import java.util.*; */ public class Submissions extends AbstractDSpaceTransformer { - /** General Language Strings */ + /** General Language Strings */ protected static final Message T_title = message("xmlui.Submission.Submissions.title"); protected static final Message T_dspace_home = @@ -85,7 +85,7 @@ public class Submissions extends AbstractDSpaceTransformer protected static final Message T_w_info3 = message("xmlui.Submission.Submissions.workflow_info3"); - // Used in the in progress section + // Used in the in progress section protected static final Message T_p_head1 = message("xmlui.Submission.Submissions.progress_head1"); protected static final Message T_p_info1 = @@ -105,22 +105,22 @@ public class Submissions extends AbstractDSpaceTransformer protected XmlWorkflowFactory workflowFactory = XmlWorkflowServiceFactory.getInstance().getWorkflowFactory(); - public void addPageMeta(PageMeta pageMeta) throws SAXException, - WingException, SQLException, IOException, - AuthorizeException - { - pageMeta.addMetadata("title").addContent(T_title); - - pageMeta.addTrailLink(contextPath + "/",T_dspace_home); - pageMeta.addTrailLink(contextPath + "/submissions",T_trail); - } - - - public void addBody(Body body) throws SAXException, WingException, - UIException, SQLException, IOException, AuthorizeException + public void addPageMeta(PageMeta pageMeta) + throws SAXException, WingException, SQLException, IOException, + AuthorizeException { + pageMeta.addMetadata("title").addContent(T_title); - Division div = body.addInteractiveDivision("submissions", contextPath+"/submissions", Division.METHOD_POST,"primary"); + pageMeta.addTrailLink(contextPath + "/",T_dspace_home); + pageMeta.addTrailLink(contextPath + "/submissions",T_trail); + } + + + public void addBody(Body body) + throws SAXException, WingException, UIException, SQLException, + IOException, AuthorizeException + { + Division div = body.addInteractiveDivision("submissions", contextPath + "/submissions", Division.METHOD_POST, "primary"); div.setHead(T_head); this.addWorkflowTasks(div); @@ -129,8 +129,10 @@ public class Submissions extends AbstractDSpaceTransformer // this.addPreviousSubmissions(div); } - private void addWorkflowTasksDiv(Division division) throws SQLException, WingException, AuthorizeException, IOException { - division.addDivision("start-submision"); + private void addWorkflowTasksDiv(Division division) + throws SQLException, WingException, AuthorizeException, IOException + { + division.addDivision("start-submision"); } /** @@ -141,23 +143,25 @@ public class Submissions extends AbstractDSpaceTransformer * * @param division The division to add the two queues too. */ - private void addWorkflowTasks(Division division) throws SQLException, WingException, AuthorizeException, IOException { - @SuppressWarnings("unchecked") // This cast is correct - java.util.List ownedItems = claimedTaskService.findByEperson(context, context.getCurrentUser()); - @SuppressWarnings("unchecked") // This cast is correct. - java.util.List pooledItems = poolTaskService.findByEperson(context, context.getCurrentUser()); + private void addWorkflowTasks(Division division) + throws SQLException, WingException, AuthorizeException, IOException { + @SuppressWarnings("unchecked") // This cast is correct + java.util.List ownedItems = claimedTaskService.findByEperson(context, context.getCurrentUser()); + @SuppressWarnings("unchecked") // This cast is correct. + java.util.List pooledItems = poolTaskService.findByEperson(context, context.getCurrentUser()); - if (!(ownedItems.size() > 0 || pooledItems.size() > 0)) - // No tasks, so don't show the table. - return; + if (!(ownedItems.size() > 0 || pooledItems.size() > 0)) + { + // No tasks, so don't show the table. + return; + } + Division workflow = division.addDivision("workflow-tasks"); + workflow.setHead(T_w_head1); + workflow.addPara(T_w_info1); - Division workflow = division.addDivision("workflow-tasks"); - workflow.setHead(T_w_head1); - workflow.addPara(T_w_info1); - - // Tasks you own - Table table = workflow.addTable("workflow-tasks",ownedItems.size() + 2,5); + // Tasks you own + Table table = workflow.addTable("workflow-tasks",ownedItems.size() + 2,5); table.setHead(T_w_head2); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_w_column1); @@ -170,26 +174,31 @@ public class Submissions extends AbstractDSpaceTransformer boolean showReturnToPoolButton = false; if (ownedItems.size() > 0) { - for (ClaimedTask owned : ownedItems) - { + for (ClaimedTask owned : ownedItems) + { String stepID = owned.getStepID(); String actionID = owned.getActionID(); XmlWorkflowItem item = owned.getWorkflowItem(); - try { + try + { Workflow wf = workflowFactory.getWorkflow(item.getCollection()); Step step = wf.getStep(stepID); WorkflowActionConfig action = step.getActionConfig(actionID); - String url = contextPath+"/handle/"+item.getCollection().getHandle()+"/xmlworkflow?workflowID="+item.getID()+"&stepID="+stepID+"&actionID="+actionID; + String url = contextPath + "/handle/" + + item.getCollection().getHandle() + + "/xmlworkflow?workflowID=" + item.getID() + + "&stepID=" + stepID + "&actionID=" + actionID; String title = item.getItem().getName(); String collectionName = item.getCollection().getName(); EPerson submitter = item.getSubmitter(); String submitterName = submitter.getFullName(); String submitterEmail = submitter.getEmail(); - // Message state = getWorkflowStateMessage(owned); + // Message state = getWorkflowStateMessage(owned); boolean taskHasPool = step.getUserSelectionMethod().getProcessingAction().usesTaskPool(); - if(taskHasPool){ + if (taskHasPool) + { //We have a workflow item that uses a pool, ensure we see the return to pool button showReturnToPoolButton = true; } @@ -197,60 +206,70 @@ public class Submissions extends AbstractDSpaceTransformer Row row = table.addRow(); Cell firstCell = row.addCell(); - if(taskHasPool){ + if (taskHasPool){ CheckBox remove = firstCell.addCheckBox("workflowandstepID"); remove.setLabel("selected"); remove.addOption(item.getID() + ":" + step.getId()); } // The task description - row.addCell().addXref(url,message("xmlui.XMLWorkflow." + wf.getID() + "." + stepID + "." + actionID)); + row.addCell().addXref(url, message("xmlui.XMLWorkflow." + + wf.getID() + "." + stepID + "." + actionID)); // The item description if (title != null && title.length() > 0) { String displayTitle = title; if (displayTitle.length() > 50) - displayTitle = displayTitle.substring(0,50)+ " ..."; - row.addCell().addXref(url,displayTitle); + { + displayTitle = displayTitle.substring(0, 50)+ " ..."; + } + row.addCell().addXref(url, displayTitle); } else - row.addCell().addXref(url,T_untitled); + { + row.addCell().addXref(url, T_untitled); + } // Submitted too - row.addCell().addXref(url,collectionName); + row.addCell().addXref(url, collectionName); // Submitted by Cell cell = row.addCell(); cell.addContent(T_email); - cell.addXref("mailto:"+submitterEmail,submitterName); - } catch (WorkflowConfigurationException e) { + cell.addXref("mailto:"+submitterEmail, submitterName); + } + catch (WorkflowConfigurationException e) + { Row row = table.addRow(); row.addCell().addContent("Error: Configuration error in workflow."); log.error(LogManager.getHeader(context, "Error while adding owned tasks on the submissions page", ""), e); - } catch (Exception e) { + } + catch (Exception e) + { log.error(LogManager.getHeader(context, "Error while adding owned tasks on the submissions page", ""), e); } } - if(showReturnToPoolButton){ + if (showReturnToPoolButton) + { Row row = table.addRow(); - row.addCell(0,5).addButton("submit_return_tasks").setValue(T_w_submit_return); + row.addCell(0, 5).addButton("submit_return_tasks").setValue(T_w_submit_return); } } else { - Row row = table.addRow(); - row.addCell(0,5).addHighlight("italic").addContent(T_w_info2); + Row row = table.addRow(); + row.addCell(0, 5).addHighlight("italic").addContent(T_w_info2); } // Tasks in the pool - table = workflow.addTable("workflow-tasks",pooledItems.size()+2,5); + table = workflow.addTable("workflow-tasks", pooledItems.size() + 2, 5); table.setHead(T_w_head3); header = table.addRow(Row.ROLE_HEADER); @@ -262,22 +281,25 @@ public class Submissions extends AbstractDSpaceTransformer if (pooledItems.size() > 0) { - - for (PoolTask pooled : pooledItems) - { + for (PoolTask pooled : pooledItems) + { String stepID = pooled.getStepID(); String actionID = pooled.getActionID(); - try { + try + { XmlWorkflowItem item = pooled.getWorkflowItem(); Workflow wf = workflowFactory.getWorkflow(item.getCollection()); - String url = contextPath+"/handle/"+item.getCollection().getHandle()+"/xmlworkflow?workflowID="+item.getID()+"&stepID="+stepID+"&actionID="+actionID; + String url = contextPath + "/handle/" + + item.getCollection().getHandle() + + "/xmlworkflow?workflowID=" + item.getID() + + "&stepID="+ stepID + "&actionID=" + actionID; String title = item.getItem().getName(); String collectionName = item.getCollection().getName(); EPerson submitter = item.getSubmitter(); String submitterName = submitter.getFullName(); String submitterEmail = submitter.getEmail(); - // Message state = getWorkflowStateMessage(pooled); +// Message state = getWorkflowStateMessage(pooled); Row row = table.addRow(); @@ -287,43 +309,51 @@ public class Submissions extends AbstractDSpaceTransformer claimTask.addOption(item.getID()); // The task description -// row.addCell().addXref(url,message("xmlui.Submission.Submissions.claimAction")); - row.addCell().addXref(url,message("xmlui.XMLWorkflow." + wf.getID() + "." + stepID + "." + actionID)); +// row.addCell().addXref(url, message("xmlui.Submission.Submissions.claimAction")); + row.addCell().addXref(url, message("xmlui.XMLWorkflow." + wf.getID() + "." + stepID + "." + actionID)); // The item description if (title != null && title.length() > 0) { String displayTitle = title; if (displayTitle.length() > 50) - displayTitle = displayTitle.substring(0,50)+ " ..."; + { + displayTitle = displayTitle.substring(0, 50)+ " ..."; + } - row.addCell().addXref(url,displayTitle); + row.addCell().addXref(url, displayTitle); } else - row.addCell().addXref(url,T_untitled); + { + row.addCell().addXref(url, T_untitled); + } // Submitted too - row.addCell().addXref(url,collectionName); + row.addCell().addXref(url, collectionName); // Submitted by Cell cell = row.addCell(); cell.addContent(T_email); - cell.addXref("mailto:"+submitterEmail,submitterName); - } catch (WorkflowConfigurationException e) { + cell.addXref("mailto:"+submitterEmail, submitterName); + } + catch (WorkflowConfigurationException e) + { Row row = table.addRow(); row.addCell().addContent("Error: Configuration error in workflow."); log.error(LogManager.getHeader(context, "Error while adding pooled tasks on the submissions page", ""), e); - } catch (Exception e) { + } + catch (Exception e) + { log.error(LogManager.getHeader(context, "Error while adding pooled tasks on the submissions page", ""), e); } } - Row row = table.addRow(); - row.addCell(0,5).addButton("submit_take_tasks").setValue(T_w_submit_take); + Row row = table.addRow(); + row.addCell(0, 5).addButton("submit_take_tasks").setValue(T_w_submit_take); } else { - Row row = table.addRow(); - row.addCell(0,4).addHighlight("italic").addContent(T_w_info3); + Row row = table.addRow(); + row.addCell(0, 4).addHighlight("italic").addContent(T_w_info3); } } @@ -339,33 +369,37 @@ public class Submissions extends AbstractDSpaceTransformer * presented listing all the unfinished submissions that this user has. * */ - private void addUnfinishedSubmissions(Division division) throws SQLException, WingException + private void addUnfinishedSubmissions(Division division) + throws SQLException, WingException { division.addInteractiveDivision("unfinished-submisions", contextPath+"/submit", Division.METHOD_POST); - } - /** * This section lists all the submissions that this user has submitted which are currently under review. * * If the user has none, this nothing is displayed. */ - private void addSubmissionsInWorkflow(Division division) throws SQLException, WingException, AuthorizeException, IOException { + private void addSubmissionsInWorkflow(Division division) + throws SQLException, WingException, AuthorizeException, IOException + { java.util.List inprogressItems; - try { + try + { inprogressItems = xmlWorkflowItemService.findBySubmitter(context, context.getCurrentUser()); // If there is nothing in progress then don't add anything. if (!(inprogressItems.size() > 0)) - return; + { + return; + } Division inprogress = division.addDivision("submissions-inprogress"); inprogress.setHead(T_p_head1); inprogress.addPara(T_p_info1); - Table table = inprogress.addTable("submissions-inprogress",inprogressItems.size()+1,3); + Table table = inprogress.addTable("submissions-inprogress", inprogressItems.size()+1, 3); Row header = table.addRow(Row.ROLE_HEADER); header.addCellContent(T_p_column1); header.addCellContent(T_p_column2); @@ -376,16 +410,18 @@ public class Submissions extends AbstractDSpaceTransformer { String title = workflowItem.getItem().getName(); String collectionName = workflowItem.getCollection().getName(); - java.util.List pooltasks = poolTaskService.find(context,workflowItem); - java.util.List claimedtasks = claimedTaskService.find(context, workflowItem); + java.util.List pooltasks = poolTaskService.find(context, workflowItem); + java.util.List claimedtasks = claimedTaskService.find(context, workflowItem); Message state = message("xmlui.XMLWorkflow.step.unknown"); - for(PoolTask task: pooltasks){ + for (PoolTask task: pooltasks) + { Workflow wf = workflowFactory.getWorkflow(workflowItem.getCollection()); Step step = wf.getStep(task.getStepID()); state = message("xmlui.XMLWorkflow." + wf.getID() + "." + step.getId() + "." + task.getActionID()); } - for(ClaimedTask task: claimedtasks){ + for (ClaimedTask task: claimedtasks) + { Workflow wf = workflowFactory.getWorkflow(workflowItem.getCollection()); Step step = wf.getStep(task.getStepID()); state = message("xmlui.XMLWorkflow." + wf.getID() + "." + step.getId() + "." + task.getActionID()); @@ -397,11 +433,15 @@ public class Submissions extends AbstractDSpaceTransformer { String displayTitle = title; if (displayTitle.length() > 50) - displayTitle = displayTitle.substring(0,50)+ " ..."; + { + displayTitle = displayTitle.substring(0, 50)+ " ..."; + } row.addCellContent(displayTitle); } else + { row.addCellContent(T_untitled); + } // Collection name column row.addCellContent(collectionName); @@ -412,10 +452,7 @@ public class Submissions extends AbstractDSpaceTransformer } catch (Exception e) { Row row = division.addTable("table0",1,1).addRow(); row.addCell().addContent("Error: Configuration error in workflow."); - } - - } /** @@ -428,9 +465,8 @@ public class Submissions extends AbstractDSpaceTransformer * @param division div to put archived submissions in */ private void addPreviousSubmissions(Division division) - throws SQLException,WingException + throws SQLException, WingException { division.addDivision("completed-submissions"); - } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java index aa108c94d1..bcc951ffaf 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/BitstreamReader.java @@ -110,7 +110,7 @@ import org.dspace.core.LogManager; * Added request-item support.
    * Original Concept, JSPUI version: Universidade do Minho at www.uminho.pt
    * Sponsorship of XMLUI version: Instituto Oceanográfico de España at www.ieo.es - * + * * @author Scott Phillips * @author Adán Román Ruiz at arvo.es (added request item support) */ @@ -118,7 +118,7 @@ import org.dspace.core.LogManager; public class BitstreamReader extends AbstractReader implements Recyclable { private static Logger log = Logger.getLogger(BitstreamReader.class); - + /** * Messages to be sent when the user is not authorized to view * a particular bitstream. They will be redirected to the login @@ -126,7 +126,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable */ private static final String AUTH_REQUIRED_HEADER = "xmlui.BitstreamReader.auth_header"; private static final String AUTH_REQUIRED_MESSAGE = "xmlui.BitstreamReader.auth_message"; - + /** * How big a buffer should we use when reading from the bitstream before * writing to the HTTP response? @@ -151,16 +151,16 @@ public class BitstreamReader extends AbstractReader implements Recyclable /** The bitstream file */ protected InputStream bitstreamInputStream; - + /** The bitstream's reported size */ protected long bitstreamSize; - + /** The bitstream's mime-type */ protected String bitstreamMimeType; - + /** The bitstream's name */ protected String bitstreamName; - + /** True if bitstream is readable by anonymous users */ protected boolean isAnonymouslyReadable; @@ -213,21 +213,21 @@ public class BitstreamReader extends AbstractReader implements Recyclable // normal processes will close it. boolean BitstreamReaderOpenedContext = !ContextUtil.isContextAvailable(objectModel); Context context = ContextUtil.obtainContext(objectModel); - + // Get our parameters that identify the bitstream String itemID = par.getParameter("itemID", null); String bitstreamID = par.getParameter("bitstreamID", null); String handle = par.getParameter("handle", null); - + int sequence = par.getParameterAsInteger("sequence", -1); String name = par.getParameter("name", null); - + this.isSpider = par.getParameter("userAgent", "").equals("spider"); // Resolve the bitstream Bitstream bitstream = null; DSpaceObject dso = null; - + if (bitstreamID != null) { // Direct reference to the individual bitstream ID. @@ -237,7 +237,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable { // Referenced by internal itemID item = itemService.findByIdOrLegacyId(context, itemID); - + if (sequence > -1) { bitstream = findBitstreamBySequence(item, sequence); @@ -273,17 +273,17 @@ public class BitstreamReader extends AbstractReader implements Recyclable // if initial search was by sequence number and found nothing, // then try to find bitstream by name (assuming we have a file name) - if((sequence > -1 && bitstream==null) && name!=null) + if ((sequence > -1 && bitstream==null) && name!=null) { bitstream = findBitstreamByName(item,name); // if we found bitstream by name, send a redirect to its new sequence number location - if(bitstream!=null) + if (bitstream!=null) { String redirectURL = ""; // build redirect URL based on whether item has a handle assigned yet - if(item.getHandle()!=null && item.getHandle().length()>0) + if (item.getHandle()!=null && item.getHandle().length()>0) { redirectURL = request.getContextPath() + "/bitstream/handle/" + item.getHandle(); } @@ -314,11 +314,11 @@ public class BitstreamReader extends AbstractReader implements Recyclable isAuthorized = false; log.info(LogManager.getHeader(context, "view_bitstream", "handle=" + item.getHandle() + ",withdrawn=true")); } - // It item-request is enabled to all request we redirect to restricted-resource immediately without login request + // It item-request is enabled to all request we redirect to restricted-resource immediately without login request String requestItemType = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("request.item.type"); if (!isAuthorized) { - if(context.getCurrentUser() != null || StringUtils.equalsIgnoreCase("all", requestItemType)){ + if (context.getCurrentUser() != null || StringUtils.equalsIgnoreCase("all", requestItemType)){ // A user is logged in, but they are not authorized to read this bitstream, // instead of asking them to login again we'll point them to a friendly error // message that tells them the bitstream is restricted. @@ -326,7 +326,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable if (item!=null){ redictURL += item.getHandle(); } - else if(dso!=null){ + else if (dso!=null){ redictURL += dso.getHandle(); } redictURL += "/restricted-resource?bitstreamId=" + bitstream.getID(); @@ -337,8 +337,8 @@ public class BitstreamReader extends AbstractReader implements Recyclable return; } else{ - if(StringUtils.isBlank(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("request.item.type")) || - DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("request.item.type").equalsIgnoreCase("logged")){ + if (StringUtils.isBlank(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("request.item.type")) || + DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("request.item.type").equalsIgnoreCase("logged")){ // The user does not have read access to this bitstream. Interrupt this current request // and then forward them to the login page so that they can be authenticated. Once that is // successful, their request will be resumed. @@ -351,7 +351,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; - } + } } } @@ -375,7 +375,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable try { //Create the cited document tempFile = citationDocumentService.makeCitedDocument(context, bitstream); - if(tempFile == null) { + if (tempFile == null) { log.error("CitedDocument was null"); } else { log.info("CitedDocument was ok," + tempFile.getAbsolutePath()); @@ -383,7 +383,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable fileInputStream = new FileInputStream(tempFile); - if(fileInputStream == null) { + if (fileInputStream == null) { log.error("Error opening fileInputStream: "); } @@ -430,45 +430,50 @@ public class BitstreamReader extends AbstractReader implements Recyclable else { // In-case there is no bitstream name... - if(name != null && name.length() > 0) { + if (name != null && name.length() > 0) + { bitstreamName = name; - if(name.endsWith(".jpg")) { + if (name.endsWith(".jpg")) + { bitstreamMimeType = "image/jpeg"; - } else if(name.endsWith(".png")) { + } + else if (name.endsWith(".png")) + { bitstreamMimeType = "image/png"; } - } else { + } + else + { bitstreamName = "bitstream"; } } - + // Log that the bitstream has been viewed, this is non-cached and the complexity // of adding it to the sitemap for every possible bitstream uri is not very tractable DSpaceServicesFactory.getInstance().getEventService().fireEvent( - new UsageEvent( - UsageEvent.Action.VIEW, - ObjectModelHelper.getRequest(objectModel), - ContextUtil.obtainContext(ObjectModelHelper.getRequest(objectModel)), - bitstream)); - + new UsageEvent( + UsageEvent.Action.VIEW, + ObjectModelHelper.getRequest(objectModel), + ContextUtil.obtainContext(ObjectModelHelper.getRequest(objectModel)), + bitstream)); + // If we created the database connection close it, otherwise leave it open. if (BitstreamReaderOpenedContext) - context.complete(); + { + context.complete(); + } } catch (SQLException sqle) { - throw new ProcessingException("Unable to read bitstream.",sqle); + throw new ProcessingException("Unable to read bitstream.", sqle); } catch (AuthorizeException ae) { - throw new ProcessingException("Unable to read bitstream.",ae); + throw new ProcessingException("Unable to read bitstream.", ae); } } - - - - + /** * Find the bitstream identified by a sequence number on this item. * @@ -476,13 +481,14 @@ public class BitstreamReader extends AbstractReader implements Recyclable * @param sequence The sequence of the bitstream * @return The bitstream or null if none found. */ - private Bitstream findBitstreamBySequence(Item item, int sequence) throws SQLException + private Bitstream findBitstreamBySequence(Item item, int sequence) + throws SQLException { if (item == null) { return null; } - + List bundles = item.getBundles(); for (Bundle bundle : bundles) { @@ -498,7 +504,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable } return null; } - + /** * Return the bitstream from the given item that is identified by the * given name. If the name has prepended directories they will be removed @@ -509,20 +515,21 @@ public class BitstreamReader extends AbstractReader implements Recyclable * @param name The name of the bitstream * @return The bitstream or null if none found. */ - private Bitstream findBitstreamByName(Item item, String name) throws SQLException + private Bitstream findBitstreamByName(Item item, String name) + throws SQLException { if (name == null || item == null) { return null; } - + // Determine our the maximum number of directories that will be removed for a path. int maxDepthPathSearch = 3; if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.html.max-depth-guess") != null) { maxDepthPathSearch = DSpaceServicesFactory.getInstance().getConfigurationService().getIntProperty("xmlui.html.max-depth-guess"); } - + // Search for the named bitstream on this item. Each time through the loop // a directory is removed from the name until either our maximum depth is // reached or the bitstream is found. Note: an extra pass is added on to the @@ -535,7 +542,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable for (Bundle bundle : bundles) { List bitstreams = bundle.getBitstreams(); - + for (Bitstream bitstream : bitstreams) { if (name.equals(bitstream.getName())) @@ -544,20 +551,20 @@ public class BitstreamReader extends AbstractReader implements Recyclable } } } - + // The bitstream was not found, so try removing a directory // off of the name and see if we lost some path information. int indexOfSlash = name.indexOf('/'); - + if (indexOfSlash < 0) { // No more directories to remove from the path, so return null for no // bitstream found. return null; } - + name = name.substring(indexOfSlash+1); - + // If this is our next to last time through the loop then // trim everything and only use the trailing filename. if (i == maxDepthPathSearch-1) @@ -568,32 +575,32 @@ public class BitstreamReader extends AbstractReader implements Recyclable name = name.substring(indexOfLastSlash + 1); } } - + } - + // The named bitstream was not found and we exhausted the maximum path depth that // we search. return null; } - - + + /** - * Write the actual data out to the response. - * - * Some implementation notes: - * - * 1) We set a short expiration time just in the hopes of preventing someone - * from overloading the server by clicking reload a bunch of times. I - * Realize that this is nowhere near 100% effective but it may help in some - * cases and shouldn't hurt anything. - * - * 2) We accept partial downloads, thus if you lose a connection halfway - * through most web browser will enable you to resume downloading the - * bitstream. + * Write the actual data out to the response. + * + * Some implementation notes: + * + * 1) We set a short expiration time just in the hopes of preventing someone + * from overloading the server by clicking reload a bunch of times. I + * Realize that this is nowhere near 100% effective but it may help in some + * cases and shouldn't hurt anything. + * + * 2) We accept partial downloads, thus if you lose a connection halfway + * through most web browser will enable you to resume downloading the + * bitstream. * @throws java.io.IOException passed through. * @throws org.xml.sax.SAXException passed through. * @throws org.apache.cocoon.ProcessingException passed through. - */ + */ @Override public void generate() throws IOException, SAXException, ProcessingException @@ -602,7 +609,7 @@ public class BitstreamReader extends AbstractReader implements Recyclable { return; } - + // Only allow If-Modified-Since protocol if request is from a spider // since response headers would encourage a browser to cache results // that might change with different authentication. @@ -646,13 +653,13 @@ public class BitstreamReader extends AbstractReader implements Recyclable { response.setDateHeader("Expires", System.currentTimeMillis() + expires); } - + // If this is a large bitstream then tell the browser it should treat it as a download. int threshold = DSpaceServicesFactory.getInstance().getConfigurationService().getIntProperty("xmlui.content_disposition_threshold"); if (bitstreamSize > threshold && threshold != 0) { String name = bitstreamName; - + // Try and make the download file name formatted for each browser. try { String agent = request.getHeader("USER-AGENT"); @@ -755,10 +762,10 @@ public class BitstreamReader extends AbstractReader implements Recyclable { // Close the bitstream input stream so that we don't leak a file descriptor this.bitstreamInputStream.close(); - + // Close the output stream as per Cocoon docs: http://cocoon.apache.org/2.2/core-modules/core/2.2/681_1_1.html out.close(); - } + } catch (IOException ioe) { // Closing the stream threw an IOException but do we want this to propagate up to Cocoon? @@ -778,10 +785,10 @@ public class BitstreamReader extends AbstractReader implements Recyclable { return this.bitstreamMimeType; } - + /** - * Recycle - */ + * Recycle + */ @Override public void recycle() { this.response = null; @@ -794,6 +801,4 @@ public class BitstreamReader extends AbstractReader implements Recyclable this.tempFile = null; super.recycle(); } - - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceCocoonServletFilter.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceCocoonServletFilter.java index 7a53005d6a..1856995c82 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceCocoonServletFilter.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceCocoonServletFilter.java @@ -28,163 +28,160 @@ import org.dspace.harvest.factory.HarvestServiceFactory; import org.dspace.harvest.service.HarvestSchedulingService; /** - * This is a wrapper servlet around the cocoon servlet that performs two functions, 1) it - * initializes DSpace / XML UI configuration parameters, and 2) it will perform interrupted + * This is a wrapper servlet around the cocoon servlet that performs two functions, 1) it + * initializes DSpace / XML UI configuration parameters, and 2) it will perform interrupted * request resumption. * * @author Scott Phillips */ -public class DSpaceCocoonServletFilter implements Filter +public class DSpaceCocoonServletFilter implements Filter { private static final Logger LOG = Logger.getLogger(DSpaceCocoonServletFilter.class); - - private static final long serialVersionUID = 1L; + + private static final long serialVersionUID = 1L; protected HarvestSchedulingService harvestSchedulingService = HarvestServiceFactory.getInstance().getHarvestSchedulingService(); /** - * Before this servlet will become functional replace + * Before this servlet will become functional replace */ public void init(FilterConfig arg0) throws ServletException { - // Paths to the various config files - String webappConfigPath = null; - String installedConfigPath = null; - + // Paths to the various config files + String webappConfigPath = null; + String installedConfigPath = null; + /** * Stage 3 * * Load the XML UI configuration */ - try - { - // There are two places we could find the XMLUI configuration, - // 1) inside the webapp's WEB-INF directory, or 2) inside the - // installed dspace config directory along side the dspace.cfg. - - webappConfigPath = arg0.getServletContext().getRealPath("/") - + File.separator + "WEB-INF" + File.separator + "xmlui.xconf"; - - installedConfigPath = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir") - + File.separator + "config" + File.separator + "xmlui.xconf"; - - XMLUIConfiguration.loadConfig(webappConfigPath,installedConfigPath); - } - catch (RuntimeException e) + try + { + // There are two places we could find the XMLUI configuration, + // 1) inside the webapp's WEB-INF directory, or 2) inside the + // installed dspace config directory along side the dspace.cfg. + + webappConfigPath = arg0.getServletContext().getRealPath("/") + + File.separator + "WEB-INF" + File.separator + "xmlui.xconf"; + + installedConfigPath = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.dir") + + File.separator + "config" + File.separator + "xmlui.xconf"; + + XMLUIConfiguration.loadConfig(webappConfigPath,installedConfigPath); + } + catch (RuntimeException e) { throw e; } catch (Exception e) - { - throw new ServletException( - "\n\nDSpace has failed to initialize, during stage 3. Error while attempting to read \n" + - "the XML UI configuration file (Path: "+webappConfigPath+" or '"+installedConfigPath+"').\n" + - "This has likely occurred because either the file does not exist, or its permissions \n" + - "are set incorrectly, or the path to the configuration file is incorrect. The XML UI \n" + - "configuration file should be named \"xmlui.xconf\" and located inside the standard \n" + - "DSpace configuration directory. \n\n",e); - } - - if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("oai.harvester.autoStart")) - { - try { + { + throw new ServletException( + "\n\nDSpace has failed to initialize, during stage 3. Error while attempting to read \n" + + "the XML UI configuration file (Path: "+webappConfigPath+" or '"+installedConfigPath+"').\n" + + "This has likely occurred because either the file does not exist, or its permissions \n" + + "are set incorrectly, or the path to the configuration file is incorrect. The XML UI \n" + + "configuration file should be named \"xmlui.xconf\" and located inside the standard \n" + + "DSpace configuration directory. \n\n",e); + } + + if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("oai.harvester.autoStart")) + { + try { harvestSchedulingService.startNewScheduler(); - } + } catch (RuntimeException e) { LOG.error(e.getMessage(), e); } - catch (Exception e) - { + catch (Exception e) + { LOG.error(e.getMessage(), e); - } - } - + } + } } - - - /** - * Before passing off a request to the cocoon servlet check to see if there is a request that - * should be resumed? If so replace the real request with a faked request and pass that off to + + + /** + * Before passing off a request to the cocoon servlet check to see if there is a request that + * should be resumed? If so replace the real request with a faked request and pass that off to * cocoon. */ - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain arg2) throws IOException, ServletException { - - HttpServletRequest realRequest = (HttpServletRequest)request; - HttpServletResponse realResponse = (HttpServletResponse) response; + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain arg2) + throws IOException, ServletException + { - try { - // Check if there is a request to be resumed. - realRequest = AuthenticationUtil.resumeRequest(realRequest); - - // Send the real request or the resumed request off to - // cocoon....right after we check our URL... - - // Get the Request URI, this will include the Context Path - String requestUri = realRequest.getRequestURI(); - // Get the Context Path of the XMLUI web application - String contextPath = realRequest.getContextPath(); - // Remove the Context Path from the Request URI -- this is the URI within our webapp - String uri = requestUri.replace(contextPath, ""); - - // If the URI within XMLUI is an empty string, this means user - // accessed XMLUI homepage *without* a trailing slash - if(uri==null || uri.length()==0) - { - // Redirect the user to XMLUI homepage with a trailing slash - // (This is necessary to ensure our Session Cookie, which ends - // in a trailing slash, isn't lost by some browsers, e.g. IE) - String locationWithTrailingSlash = realRequest.getRequestURI() + "/"; - - // Reset any existing response headers -- instead we are going to redirect user to correct path - realResponse.reset(); - - // Redirect user to homepage with trailing slash - realResponse.sendRedirect(locationWithTrailingSlash); - } - // if force ssl is on and the user has authenticated and the request is not secure redirect to https - else if ((DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.force.ssl")) - && (AuthenticationUtil.isLoggedIn(realRequest)) - && (!realRequest.isSecure())) - { - StringBuffer location = new StringBuffer("https://"); - location.append(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.hostname")) - .append(realRequest.getRequestURI()) - .append(realRequest.getQueryString() == null ? "" - : ("?" + realRequest.getQueryString())); - realResponse.sendRedirect(location.toString()); - } - else - { // invoke the next filter - arg2.doFilter(realRequest, realResponse); - } - } catch (IOException e) { - ContextUtil.abortContext(realRequest); - if (LOG.isDebugEnabled()) { - LOG.debug("The connection was reset", e); + HttpServletRequest realRequest = (HttpServletRequest)request; + HttpServletResponse realResponse = (HttpServletResponse) response; + + try { + // Check if there is a request to be resumed. + realRequest = AuthenticationUtil.resumeRequest(realRequest); + + // Send the real request or the resumed request off to + // cocoon....right after we check our URL... + + // Get the Request URI, this will include the Context Path + String requestUri = realRequest.getRequestURI(); + // Get the Context Path of the XMLUI web application + String contextPath = realRequest.getContextPath(); + // Remove the Context Path from the Request URI -- this is the URI within our webapp + String uri = requestUri.replace(contextPath, ""); + + // If the URI within XMLUI is an empty string, this means user + // accessed XMLUI homepage *without* a trailing slash + if (uri==null || uri.length()==0) + { + // Redirect the user to XMLUI homepage with a trailing slash + // (This is necessary to ensure our Session Cookie, which ends + // in a trailing slash, isn't lost by some browsers, e.g. IE) + String locationWithTrailingSlash = realRequest.getRequestURI() + "/"; + + // Reset any existing response headers -- instead we are going to redirect user to correct path + realResponse.reset(); + + // Redirect user to homepage with trailing slash + realResponse.sendRedirect(locationWithTrailingSlash); } - else { - LOG.error("Client closed the connection before file download was complete"); - } - } catch (RuntimeException e) { - ContextUtil.abortContext(realRequest); - LOG.error("Serious Runtime Error Occurred Processing Request!", e); - throw e; - } catch (Exception e) { - ContextUtil.abortContext(realRequest); + // if force ssl is on and the user has authenticated and the request is not secure redirect to https + else if ((DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.force.ssl")) + && (AuthenticationUtil.isLoggedIn(realRequest)) + && (!realRequest.isSecure())) + { + StringBuffer location = new StringBuffer("https://"); + location.append(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.hostname")) + .append(realRequest.getRequestURI()) + .append(realRequest.getQueryString() == null ? "" + : ("?" + realRequest.getQueryString())); + realResponse.sendRedirect(location.toString()); + } + else + { // invoke the next filter + arg2.doFilter(realRequest, realResponse); + } + } catch (IOException e) { + ContextUtil.abortContext(realRequest); + if (LOG.isDebugEnabled()) { + LOG.debug("The connection was reset", e); + } + else { + LOG.error("Client closed the connection before file download was complete"); + } + } catch (RuntimeException e) { + ContextUtil.abortContext(realRequest); + LOG.error("Serious Runtime Error Occurred Processing Request!", e); + throw e; + } catch (Exception e) { + ContextUtil.abortContext(realRequest); LOG.error("Serious Error Occurred Processing Request!", e); - } finally { - // Close out the DSpace context no matter what. - ContextUtil.completeContext(realRequest); - } + } finally { + // Close out the DSpace context no matter what. + ContextUtil.completeContext(realRequest); + } } - public void destroy() { - // TODO Auto-generated method stub - - } - - - + public void destroy() { + // TODO Auto-generated method stub + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceI18NTransformer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceI18NTransformer.java index 38cee16a4c..62d0663ff1 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceI18NTransformer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceI18NTransformer.java @@ -23,7 +23,7 @@ import org.dspace.app.xmlui.configuration.XMLUIConfiguration; * aspects. * *

    - * This transformer modified the base configuration by adding two + * This transformer modified the base configuration by adding two * {@code } parameters for each aspect into the default catalogue. * The first location parameter is contained within the catalogue's * base location + the aspect path. The second location parameter is @@ -31,7 +31,7 @@ import org.dspace.app.xmlui.configuration.XMLUIConfiguration; * *

    * This allows aspect developers to place their default messages files - * inside the aspect, and place translations into various languages inside + * inside the aspect, and place translations into various languages inside * the base i18n/ directory. * *

    @@ -47,7 +47,7 @@ import org.dspace.app.xmlui.configuration.XMLUIConfiguration; * * * }

    - * + * * And there were two aspects installed: *
    {@code } *
    {@code } @@ -70,13 +70,13 @@ import org.dspace.app.xmlui.configuration.XMLUIConfiguration; */ public class DSpaceI18NTransformer extends I18nTransformer { - + /** log4j category */ private static Logger log = Logger.getLogger(DSpaceI18NTransformer.class); - - // If we can't find a base location, use this one by default. - public static final String DEFAULT_BASE_LOCATION ="context://i18n/"; - + + // If we can't find a base location, use this one by default. + public static final String DEFAULT_BASE_LOCATION ="context://i18n/"; + /** * Intercept the configuration parameters coming from the Cocoon sitemap before @@ -88,75 +88,75 @@ public class DSpaceI18NTransformer extends I18nTransformer { * passed through. */ @Override - public void configure(Configuration originalConf) throws ConfigurationException + public void configure(Configuration originalConf) + throws ConfigurationException { - MutableConfiguration modifiedConf = new DefaultConfiguration(originalConf,true); + MutableConfiguration modifiedConf = new DefaultConfiguration(originalConf,true); MutableConfiguration cataloguesConf = modifiedConf.getMutableChild("catalogues", true); - + // Find the default catalogue and add our new locations to it. for (MutableConfiguration catalogueConf : cataloguesConf.getMutableChildren()) { - if (!"false".equals(catalogueConf.getAttribute("aspects","false"))) - { - // Get the first location element to determine what the base path is. - String baseCatalogueLocationPath = DEFAULT_BASE_LOCATION; - Configuration baseCatalogueLocationConf = catalogueConf.getChild("location"); - if (baseCatalogueLocationConf != null) + if (!"false".equals(catalogueConf.getAttribute("aspects","false"))) + { + // Get the first location element to determine what the base path is. + String baseCatalogueLocationPath = DEFAULT_BASE_LOCATION; + Configuration baseCatalogueLocationConf = catalogueConf.getChild("location"); + if (baseCatalogueLocationConf != null) { baseCatalogueLocationPath = baseCatalogueLocationConf.getValue(); } - if (!baseCatalogueLocationPath.endsWith("/")) + if (!baseCatalogueLocationPath.endsWith("/")) { baseCatalogueLocationPath += "/"; } // Add a trailing slash if one doesn't exist - - String catalogueId = catalogueConf.getAttribute("id","unknown"); - - // For each aspect add two new locations one inside the aspect's directory - // and another inside the base location for i18n files. - for (Aspect aspect : XMLUIConfiguration.getAspectChain()) - { - // Add a catalogue location inside the default i18n directory in the webapp - // this will be of the form: "context://i18n//" thus for the artifact - // browser aspect it will be "context://i18n/aspects/BrowseArtifacts/" - String baseLocationPath = aspect.getPath(); - int idx = baseLocationPath.indexOf("://"); - if (idx > 0) + + String catalogueId = catalogueConf.getAttribute("id","unknown"); + + // For each aspect add two new locations one inside the aspect's directory + // and another inside the base location for i18n files. + for (Aspect aspect : XMLUIConfiguration.getAspectChain()) + { + // Add a catalogue location inside the default i18n directory in the webapp + // this will be of the form: "context://i18n//" thus for the artifact + // browser aspect it will be "context://i18n/aspects/BrowseArtifacts/" + String baseLocationPath = aspect.getPath(); + int idx = baseLocationPath.indexOf("://"); + if (idx > 0) { // remove the module directive from the aspect's path so it's just a normal path baseLocationPath = baseLocationPath.substring(idx + 3, baseLocationPath.length()); } - - // Now that the module directive has been removed from the path, add in the base i18npath - baseLocationPath = baseCatalogueLocationPath + baseLocationPath; - - MutableConfiguration baseLocation = new DefaultConfiguration("location"); - baseLocation.setValue(baseLocationPath); - catalogueConf.addChild(baseLocation); - - - // Add a catalogue location inside the aspect's directory - // (most likely in the jar's resources but if it's not that's okay) - // For the artifact browser this would be: - // "resource://aspects/BrowseArtifacts/i18n/" - String aspectLocationPath = aspect.getPath(); - if (!aspectLocationPath.endsWith("/")) + + // Now that the module directive has been removed from the path, add in the base i18npath + baseLocationPath = baseCatalogueLocationPath + baseLocationPath; + + MutableConfiguration baseLocation = new DefaultConfiguration("location"); + baseLocation.setValue(baseLocationPath); + catalogueConf.addChild(baseLocation); + + + // Add a catalogue location inside the aspect's directory + // (most likely in the jar's resources but if it's not that's okay) + // For the artifact browser this would be: + // "resource://aspects/BrowseArtifacts/i18n/" + String aspectLocationPath = aspect.getPath(); + if (!aspectLocationPath.endsWith("/")) { aspectLocationPath += "/"; // Add a trailing slash if one doesn't exist } - aspectLocationPath += "i18n/"; - MutableConfiguration aspectLocation = new DefaultConfiguration("location"); - aspectLocation.setValue(aspectLocationPath); - catalogueConf.addChild(aspectLocation); - - log.debug("Adding i18n location path for '"+catalogueId+"' catalogue: "+baseLocationPath); - log.debug("Adding i18n location path for '"+catalogueId+"' catalogue: "+aspectLocationPath); - } // for each aspect - } // if catalogue has the aspect parameter + aspectLocationPath += "i18n/"; + MutableConfiguration aspectLocation = new DefaultConfiguration("location"); + aspectLocation.setValue(aspectLocationPath); + catalogueConf.addChild(aspectLocation); + + log.debug("Adding i18n location path for '"+catalogueId+"' catalogue: "+baseLocationPath); + log.debug("Adding i18n location path for '"+catalogueId+"' catalogue: "+aspectLocationPath); + } // for each aspect + } // if catalogue has the aspect parameter } // for each catalogue - + // Pass off to cocoon's i18n transformer our modified configuration with new aspect locations. super.configure(modifiedConf); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceLocaleAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceLocaleAction.java index 153ae09db3..656319f8c2 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceLocaleAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceLocaleAction.java @@ -28,11 +28,11 @@ import java.util.Locale; import java.util.Map; /** - * This action looks at several places to determine what locale should be used for - * this request. We use cocoon's i18nUtils find local method which will look in + * This action looks at several places to determine what locale should be used for + * this request. We use cocoon's i18nUtils find local method which will look in * several places continuing to the next step if no local is found.: - * - * 1. HTTP Request parameter 'locale' + * + * 1. HTTP Request parameter 'locale' * 2. Session attribute 'locale' * 3. First matching cookie parameter 'locale' within each cookie sent * 4. Sitemap parameter "locale" @@ -40,39 +40,39 @@ import java.util.Map; * 6. Default * 7. Blank * 8. Fail - * + * * Only those locales which are listed in webui.supported.locales will be identified, * if no acceptable locales are found then the default locale will be used. - * + * * @author Scott Phillips */ public class DSpaceLocaleAction extends ServiceableAction implements Configurable { - - /** A validator class which tests if a local is a supported locale */ - private static DSpaceLocaleValidator localeValidator; - - /** The default locale if no acceptable locales are identified */ - private static Locale defaultLocale; - - - /** - * Configure the action. - */ - public void configure(Configuration config) - { - if (localeValidator == null) - { - localeValidator = new DSpaceLocaleValidator(); - } - - if (defaultLocale == null) - { - defaultLocale = I18nUtil.getDefaultLocale(); - } - } - - + + /** A validator class which tests if a local is a supported locale */ + private static DSpaceLocaleValidator localeValidator; + + /** The default locale if no acceptable locales are identified */ + private static Locale defaultLocale; + + + /** + * Configure the action. + */ + public void configure(Configuration config) + { + if (localeValidator == null) + { + localeValidator = new DSpaceLocaleValidator(); + } + + if (defaultLocale == null) + { + defaultLocale = I18nUtil.getDefaultLocale(); + } + } + + /** * Action which obtains the current environments locale information, and * places it in the objectModel (and optionally in a session/cookie). @@ -82,12 +82,14 @@ public class DSpaceLocaleAction extends ServiceableAction implements Configurabl Map objectModel, String source, Parameters parameters) - throws Exception { - + throws Exception + { Locale locale = I18nUtils.findLocale(objectModel, "locale-attribute", parameters, defaultLocale, false, true, false, localeValidator); - if (locale == null) { - if (getLogger().isDebugEnabled()) { + if (locale == null) + { + if (getLogger().isDebugEnabled()) + { getLogger().debug("No locale found, using default"); } locale = I18nUtil.getDefaultLocale(); @@ -118,68 +120,64 @@ public class DSpaceLocaleAction extends ServiceableAction implements Configurabl return map; } - + /** - * This validator class works with cocoon's i18nutils class to test if locales are valid. - * For dspace we define a locale as valid if it is listed in webui.supported.locales config + * This validator class works with cocoon's i18nutils class to test if locales are valid. + * For dspace we define a locale as valid if it is listed in webui.supported.locales config * parameter. */ public static class DSpaceLocaleValidator implements LocaleValidator { - /** the list of supported locales that may be used. */ - private List supportedLocales; - - /** - * Build a list supported locales to validate against upon object construction. - */ - public DSpaceLocaleValidator() - { + /** the list of supported locales that may be used. */ + private List supportedLocales; + + /** + * Build a list supported locales to validate against upon object construction. + */ + public DSpaceLocaleValidator() + { if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("webui.supported.locales") != null) { - supportedLocales = new ArrayList(); - + supportedLocales = new ArrayList(); + String[] supportedLocalesConfig = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("webui.supported.locales"); for (String part : supportedLocalesConfig) - { - Locale supportedLocale = I18nUtils.parseLocale(part.trim(), null); - if (supportedLocale != null) - { - supportedLocales.add(supportedLocale); - } + { + Locale supportedLocale = I18nUtils.parseLocale(part.trim(), null); + if (supportedLocale != null) + { + supportedLocales.add(supportedLocale); + } } } - } - - - /** + } + + + /** * @param name name of the locale (for debugging) * @param test locale to test * @return true if locale satisfies validator's criteria */ - public boolean test(String name, Locale test) - { - // If there are no configured locales the accept them all. - if (supportedLocales == null) + public boolean test(String name, Locale test) + { + // If there are no configured locales the accept them all. + if (supportedLocales == null) { return true; } - - // Otherwise check if they are listed - for (Locale locale : supportedLocales) + + // Otherwise check if they are listed + for (Locale locale : supportedLocales) { - if (locale.equals(test)) + if (locale.equals(test)) { - return true; + return true; } } - - // Fail if not found - return false; - - } - + + // Fail if not found + return false; + } } - - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceMETSGenerator.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceMETSGenerator.java index 6f0a5ba885..ec017ab08b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceMETSGenerator.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceMETSGenerator.java @@ -41,114 +41,116 @@ import org.xml.sax.SAXException; * identified by passing in one of the two parameters: handle or internal. If an internal ID is given then it must * be of the form "type:id" i.g. item:255 or community:4 or repository:123456789. In the case of a repository the * id must be the handle prefix. - * + * * In addition to rendering a METS document there are several options which can be specified for how the mets * document should be rendered. All parameters are a comma-separated list of values, here is a list: - * - * + * + * * sections: - * - * A comma-separated list of METS sections to included. The possible values are: "metsHdr", "dmdSec", + * + * A comma-separated list of METS sections to included. The possible values are: "metsHdr", "dmdSec", * "amdSec", "fileSec", "structMap", "structLink", "behaviorSec", and "extraSec". If no list is provided then *ALL* * sections are rendered. - * - * + * + * * dmdTypes: - * + * * A comma-separated list of metadata formats to provide as descriptive metadata. The list of available metadata - * types is defined in the dspace.cfg, dissemination crosswalks. If no formats are provided them DIM - DSpace + * types is defined in the dspace.cfg, dissemination crosswalks. If no formats are provided them DIM - DSpace * Intermediate Format - is used. - * - * + * + * * amdTypes: - * + * * A comma-separated list of metadata formats to provide administrative metadata. DSpace does not currently * support this type of metadata. - * - * + * + * * fileGrpTypes: - * + * * A comma-separated list of file groups to render. For DSpace a bundle is translated into a METS fileGrp, so * possible values are "THUMBNAIL","CONTENT", "METADATA", etc... If no list is provided then all groups are * rendered. - * - * + * + * * structTypes: - * + * * A comma-separated list of structure types to render. For DSpace there is only one structType: LOGICAL. If this * is provided then the logical structType will be rendered, otherwise none will. The default operation is to * render all structure types. - * + * * @author Scott Phillips */ public class DSpaceMETSGenerator extends AbstractGenerator { protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - /** - * Generate the METS Document. + /** + * Generate the METS Document. * @throws java.io.IOException passed through. * @throws org.xml.sax.SAXException passed through. * @throws org.apache.cocoon.ProcessingException on error. - */ + */ @Override - public void generate() throws IOException, SAXException, ProcessingException { - try { - // Open a new context. - Context context = ContextUtil.obtainContext(objectModel); - - // Determine which adapter to use - AbstractAdapter adapter = resolveAdapter(context); + public void generate() + throws IOException, SAXException, ProcessingException + { + try { + // Open a new context. + Context context = ContextUtil.obtainContext(objectModel); + + // Determine which adapter to use + AbstractAdapter adapter = resolveAdapter(context); if (adapter == null) { throw new ResourceNotFoundException("Unable to locate object."); } - + // Configure the adapter for this request. configureAdapter(adapter); - - // Generate the METS document - contentHandler.startDocument(); - adapter.renderMETS(context, contentHandler,lexicalHandler); - contentHandler.endDocument(); - - } catch (WingException we) { - throw new ProcessingException(we); - } catch (CrosswalkException ce) { - throw new ProcessingException(ce); - } catch (SQLException sqle) { - throw new ProcessingException(sqle); - } - } - - - - /** - * Determine which type of adapter to use for this object, either a community, collection, item, or - * repository adapter. The decision is based upon the two supplied identifiers: a handle or an - * internal id. If the handle is supplied then this is resolved and the appropriate adapter is - * picked. Otherwise the internal identifier is used to resolve the correct type of adapter. - * - * The internal identifier must be of the form "type:id" i.g. item:255 or collection:99. In the - * case of a repository the handle prefix must be used. - * - * @return Return the correct adaptor or null if none found. - */ - private AbstractAdapter resolveAdapter(Context context) throws SQLException - { - Request request = ObjectModelHelper.getRequest(objectModel); + + // Generate the METS document + contentHandler.startDocument(); + adapter.renderMETS(context, contentHandler,lexicalHandler); + contentHandler.endDocument(); + + } catch (WingException we) { + throw new ProcessingException(we); + } catch (CrosswalkException ce) { + throw new ProcessingException(ce); + } catch (SQLException sqle) { + throw new ProcessingException(sqle); + } + } + + + /** + * Determine which type of adapter to use for this object, either a community, collection, item, or + * repository adapter. The decision is based upon the two supplied identifiers: a handle or an + * internal id. If the handle is supplied then this is resolved and the appropriate adapter is + * picked. Otherwise the internal identifier is used to resolve the correct type of adapter. + * + * The internal identifier must be of the form "type:id" i.g. item:255 or collection:99. In the + * case of a repository the handle prefix must be used. + * + * @return Return the correct adaptor or null if none found. + */ + private AbstractAdapter resolveAdapter(Context context) + throws SQLException + { + Request request = ObjectModelHelper.getRequest(objectModel); String contextPath = request.getContextPath(); // Determine the correct adapter to use for this item String handle = parameters.getParameter("handle",null); String internal = parameters.getParameter("internal",null); - + AbstractAdapter adapter = null; - if (handle != null) - { + if (handle != null) + { // Specified using a regular handle. DSpaceObject dso = handleService.resolveToObject(context, handle); @@ -157,70 +159,71 @@ public class DSpaceMETSGenerator extends AbstractGenerator { adapter = new ItemAdapter(context, (Item) dso, contextPath); } - else if (dso instanceof Collection || dso instanceof Community) + else if (dso instanceof Collection || dso instanceof Community) { adapter = new ContainerAdapter(context, dso, contextPath); } - } - else if (internal != null) - { - // Internal identifier, format: "type:id". - String[] parts = internal.split(":"); - - if (parts.length == 2) - { - String type = parts[0]; - String strid = parts[1]; - UUID id = null; + } + else if (internal != null) + { + // Internal identifier, format: "type:id". + String[] parts = internal.split(":"); - // Handle prefixes must be treated as strings - // all non-repository types need integer IDs - if ("repository".equals(type)) + if (parts.length == 2) + { + String type = parts[0]; + String strid = parts[1]; + UUID id = null; + + // Handle prefixes must be treated as strings + // all non-repository types need integer IDs + if ("repository".equals(type)) + { + if (handleService.getPrefix().equals(strid)) + { + adapter = new RepositoryAdapter(context, contextPath); + } + } + else + { + id = UUID.fromString(parts[1]); + if ("item".equals(type)) + { + Item item = itemService.find(context,id); + if (item != null) { - if (handleService.getPrefix().equals(strid)) - { - adapter = new RepositoryAdapter(context, contextPath); - } + adapter = new ItemAdapter(context, item, contextPath); } - else + } + else if ("collection".equals(type)) + { + Collection collection = collectionService.find(context,id); + if (collection != null) { - id = UUID.fromString(parts[1]); - if ("item".equals(type)) - { - Item item = itemService.find(context,id); - if (item != null) - { - adapter = new ItemAdapter(context, item, contextPath); - } - } - else if ("collection".equals(type)) - { - Collection collection = collectionService.find(context,id); - if (collection != null) - { - adapter = new ContainerAdapter(context, collection, contextPath); - } - } - else if ("community".equals(type)) - { - Community community = communityService.find(context,id); - if (community != null) - { - adapter = new ContainerAdapter(context, community, contextPath); - } - } - } - } + adapter = new ContainerAdapter(context, collection, contextPath); + } + } + else if ("community".equals(type)) + { + Community community = communityService.find(context,id); + if (community != null) + { + adapter = new ContainerAdapter(context, community, contextPath); + } + } + } + } } - return adapter; - } - - /** - * Configure the adapter according to the supplied parameters. + return adapter; + } + + + /** + * Configure the adapter according to the supplied parameters. * @param adapter the adapter. - */ - public void configureAdapter(AbstractAdapter adapter) - { + */ + public void configureAdapter(AbstractAdapter adapter) + { // Configure the adapter based upon the passed parameters Request request = ObjectModelHelper.getRequest(objectModel); String sections = request.getParameter("sections"); @@ -231,7 +234,7 @@ public class DSpaceMETSGenerator extends AbstractGenerator String digiprovMDTypes = request.getParameter("digiprovMDTypes"); String fileGrpTypes = request.getParameter("fileGrpTypes"); String structTypes = request.getParameter("structTypes"); - + adapter.setSections(sections); adapter.setDmdTypes(dmdTypes); adapter.setTechMDTypes(techMDTypes); @@ -240,6 +243,5 @@ public class DSpaceMETSGenerator extends AbstractGenerator adapter.setDigiProvMDTypes(digiprovMDTypes); adapter.setFileGrpTypes(fileGrpTypes); adapter.setStructTypes(structTypes); - } - + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceOREGenerator.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceOREGenerator.java index 6b5f168ee8..6497773b1d 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceOREGenerator.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpaceOREGenerator.java @@ -32,7 +32,7 @@ import org.jdom.output.SAXOutputter; import org.xml.sax.SAXException; /** - * Generate an ORE aggregation of a DSpace Item. The object to be rendered should be an item identified by pasing + * Generate an ORE aggregation of a DSpace Item. The object to be rendered should be an item identified by pasing * in one of the two parameters: handle or internal. The fragment parameter determines the encoding format for * the aggregation; only Atom is supported at this time. @@ -41,92 +41,96 @@ import org.xml.sax.SAXException; public class DSpaceOREGenerator extends AbstractGenerator { - protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); + protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); - /** - * Generate the ORE Aggregation. - */ - public void generate() throws IOException, SAXException, - ProcessingException { - try { - // Grab the context. - Context context = ContextUtil.obtainContext(objectModel); - - Item item = getItem(context); + /** + * Generate the ORE Aggregation. + */ + public void generate() + throws IOException, SAXException, ProcessingException + { + try + { + // Grab the context. + Context context = ContextUtil.obtainContext(objectModel); + + Item item = getItem(context); if (item == null) { throw new ResourceNotFoundException("Unable to locate object."); } - - + + // Instantiate and execute the ORE plugin SAXOutputter out = new SAXOutputter(contentHandler); - DisseminationCrosswalk xwalk = (DisseminationCrosswalk)CoreServiceFactory.getInstance().getPluginService().getNamedPlugin(DisseminationCrosswalk.class,"ore"); - + DisseminationCrosswalk xwalk = + (DisseminationCrosswalk)CoreServiceFactory.getInstance() + .getPluginService().getNamedPlugin( + DisseminationCrosswalk.class, "ore"); + Element ore = xwalk.disseminateElement(context, item); out.output(ore); - - /* Generate the METS document - contentHandler.startDocument(); - adapter.renderMETS(contentHandler,lexicalHandler); - contentHandler.endDocument();*/ - - } catch (JDOMException je) { - throw new ProcessingException(je); - } catch (AuthorizeException ae) { - throw new ProcessingException(ae); - } catch (CrosswalkException ce) { - throw new ProcessingException(ce); - } catch (SQLException sqle) { - throw new ProcessingException(sqle); - } - } - - - private Item getItem(Context context) throws SQLException, CrosswalkException - { + + /* Generate the METS document + contentHandler.startDocument(); + adapter.renderMETS(contentHandler,lexicalHandler); + contentHandler.endDocument();*/ + + } catch (JDOMException je) { + throw new ProcessingException(je); + } catch (AuthorizeException ae) { + throw new ProcessingException(ae); + } catch (CrosswalkException ce) { + throw new ProcessingException(ce); + } catch (SQLException sqle) { + throw new ProcessingException(sqle); + } + } + + + private Item getItem(Context context) + throws SQLException, CrosswalkException + { // Determine the correct adatper to use for this item String handle = parameters.getParameter("handle",null); String internal = parameters.getParameter("internal",null); - - if (handle != null) + + if (handle != null) { - // Specified using a regular handle. - DSpaceObject dso = handleService.resolveToObject(context, handle); - - // Handles can be either items or containers. - if (dso instanceof Item) + // Specified using a regular handle. + DSpaceObject dso = handleService.resolveToObject(context, handle); + + // Handles can be either items or containers. + if (dso instanceof Item) { return (Item) dso; } - else + else { throw new CrosswalkException("ORE dissemination only available for DSpace Items."); } } else if (internal != null) { - // Internal identifier, format: "type:id". - String[] parts = internal.split(":"); - - if (parts.length == 2) - { - String type = parts[0]; - UUID id = UUID.fromString(parts[1]); - - if ("item".equals(type)) - { + // Internal identifier, format: "type:id". + String[] parts = internal.split(":"); + + if (parts.length == 2) + { + String type = parts[0]; + UUID id = UUID.fromString(parts[1]); + + if ("item".equals(type)) + { return itemService.find(context,id); - } - else + } + else { throw new CrosswalkException("ORE dissemination only available for DSpace Items."); } - - } + } } - return null; - } - + return null; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpacePropertyFileReader.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpacePropertyFileReader.java index 4d015fafc7..4a4d3b018a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpacePropertyFileReader.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/DSpacePropertyFileReader.java @@ -25,10 +25,10 @@ import org.dspace.services.factory.DSpaceServicesFactory; *

    * For example: *

    {@code
    - * 		
    - *			
    - *			 
    - *		
    + *         
    + *            
    + *             
    + *        
      * }
    * Will place the value of the {@code dspace.dir} property in the * {@code dspace_dir} variable to be used in the sitemap. @@ -50,20 +50,21 @@ public class DSpacePropertyFileReader extends AbstractAction { * @throws Exception passed through. */ @Override - public Map act(Redirector redirector, SourceResolver resolver, - Map objectModel, String source, Parameters parameters) - throws Exception { + public Map act(Redirector redirector, SourceResolver resolver, + Map objectModel, String source, Parameters parameters) + throws Exception + { - Map map = new HashMap(); + Map map = new HashMap(); - final String[] parameterNames = parameters.getNames(); - - for (int i = 0; i < parameterNames.length; i++) { - final String paramName = parameterNames[i]; - map.put(parameters.getParameter(paramName), - DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(paramName)); - } - - return map; - } + final String[] parameterNames = parameters.getNames(); + + for (int i = 0; i < parameterNames.length; i++) { + final String paramName = parameterNames[i]; + map.put(parameters.getParameter(paramName), + DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(paramName)); + } + + return map; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/HttpServletRequestCocoonWrapper.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/HttpServletRequestCocoonWrapper.java index a1e66b279d..b292ef5a0f 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/HttpServletRequestCocoonWrapper.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/HttpServletRequestCocoonWrapper.java @@ -25,269 +25,265 @@ import org.apache.cocoon.environment.ObjectModelHelper; import org.apache.cocoon.environment.Request; /** - * This is a wrapper class that translates a Cocoon request object back - * into an HttpServletRequest object. The main purpose of this class is to - * support form encoding in libraries that require a real HttpServletRequest - * object. If they are given the real request object then any parameters they - * obtain from it will not take into account the form encoding. Thus this - * method, by proxing everything back through the cocoon object will not - * be hindered by this problem. - * - * + * This is a wrapper class that translates a Cocoon request object back + * into an HttpServletRequest object. The main purpose of this class is to + * support form encoding in libraries that require a real HttpServletRequest + * object. If they are given the real request object then any parameters they + * obtain from it will not take into account the form encoding. Thus this + * method, by proxing everything back through the cocoon object will not + * be hindered by this problem. + * + * * Some methods are unsupported, see below for a list. * getCookies(),getInputStream(),getParameterMap(),getReader(), * getRealPath(String arg0),getRequestDispatcher(String arg0) - * + * * @author Scott Phillips */ public class HttpServletRequestCocoonWrapper implements HttpServletRequest{ - private Request cocoonRequest; - // private HttpServletRequest realRequest; - - public HttpServletRequestCocoonWrapper(Map objectModel) { - - // Get the two requests objects the cocoon one, and the real request object as a fall back. - this.cocoonRequest = ObjectModelHelper.getRequest(objectModel); - - // If the real request is needed in the future to fall back to when the - // cocoon request object doesn't support those methods use the following line. - // this.realRequest = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); - } - - public String getAuthType() { - return this.cocoonRequest.getAuthType(); - } + private Request cocoonRequest; + // private HttpServletRequest realRequest; - public String getContextPath() { - return this.cocoonRequest.getContextPath(); - } + public HttpServletRequestCocoonWrapper(Map objectModel) { - public Cookie[] getCookies() { - throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support cookies."); - } + // Get the two requests objects the cocoon one, and the real request object as a fall back. + this.cocoonRequest = ObjectModelHelper.getRequest(objectModel); - public long getDateHeader(String arg0) { - return this.cocoonRequest.getDateHeader(arg0); - } + // If the real request is needed in the future to fall back to when the + // cocoon request object doesn't support those methods use the following line. + // this.realRequest = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + } - public String getHeader(String arg0) { - return this.cocoonRequest.getHeader(arg0); - } + public String getAuthType() { + return this.cocoonRequest.getAuthType(); + } - public Enumeration getHeaderNames() { - return this.cocoonRequest.getHeaderNames(); - } + public String getContextPath() { + return this.cocoonRequest.getContextPath(); + } - public Enumeration getHeaders(String arg0) { - return this.cocoonRequest.getHeaders(arg0); - } + public Cookie[] getCookies() { + throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support cookies."); + } - public int getIntHeader(String arg0) { - Enumeration e = getHeaders(arg0); - if (e.hasMoreElements()) - { - Object v = e.nextElement(); - if (v instanceof String) - { - try { - return Integer.valueOf((String)v); - } catch (NumberFormatException nfe) - { - // do nothing - } - } - } - return -1; - } + public long getDateHeader(String arg0) { + return this.cocoonRequest.getDateHeader(arg0); + } - public String getMethod() { - return this.cocoonRequest.getMethod(); - } + public String getHeader(String arg0) { + return this.cocoonRequest.getHeader(arg0); + } - public String getPathInfo() { - return this.cocoonRequest.getPathInfo(); - } + public Enumeration getHeaderNames() { + return this.cocoonRequest.getHeaderNames(); + } - public String getPathTranslated() { - return this.cocoonRequest.getPathTranslated(); - } + public Enumeration getHeaders(String arg0) { + return this.cocoonRequest.getHeaders(arg0); + } - public String getQueryString() { - return this.cocoonRequest.getQueryString(); - } + public int getIntHeader(String arg0) { + Enumeration e = getHeaders(arg0); + if (e.hasMoreElements()) + { + Object v = e.nextElement(); + if (v instanceof String) + { + try { + return Integer.valueOf((String)v); + } catch (NumberFormatException nfe) + { + // do nothing + } + } + } + return -1; + } - public String getRemoteUser() { - return this.cocoonRequest.getRemoteUser(); - } + public String getMethod() { + return this.cocoonRequest.getMethod(); + } - public String getRequestURI() { - return this.cocoonRequest.getRequestURI(); - } + public String getPathInfo() { + return this.cocoonRequest.getPathInfo(); + } - public StringBuffer getRequestURL() { - return new StringBuffer(this.cocoonRequest.getRequestURI()); - } + public String getPathTranslated() { + return this.cocoonRequest.getPathTranslated(); + } - public String getRequestedSessionId() { - return this.cocoonRequest.getRequestedSessionId(); - } + public String getQueryString() { + return this.cocoonRequest.getQueryString(); + } - public String getServletPath() { - return this.cocoonRequest.getServletPath(); - } + public String getRemoteUser() { + return this.cocoonRequest.getRemoteUser(); + } - public HttpSession getSession() { - return (HttpSession) this.cocoonRequest.getSession(); - } + public String getRequestURI() { + return this.cocoonRequest.getRequestURI(); + } - public HttpSession getSession(boolean arg0) { - return (HttpSession) this.cocoonRequest.getSession(arg0); - } + public StringBuffer getRequestURL() { + return new StringBuffer(this.cocoonRequest.getRequestURI()); + } - public Principal getUserPrincipal() { - return this.cocoonRequest.getUserPrincipal(); - } + public String getRequestedSessionId() { + return this.cocoonRequest.getRequestedSessionId(); + } - public boolean isRequestedSessionIdFromCookie() { - return this.cocoonRequest.isRequestedSessionIdFromCookie(); - } + public String getServletPath() { + return this.cocoonRequest.getServletPath(); + } - public boolean isRequestedSessionIdFromURL() { - return this.cocoonRequest.isRequestedSessionIdFromURL(); - } + public HttpSession getSession() { + return (HttpSession) this.cocoonRequest.getSession(); + } - public boolean isRequestedSessionIdFromUrl() { - return this.cocoonRequest.isRequestedSessionIdFromURL(); - } + public HttpSession getSession(boolean arg0) { + return (HttpSession) this.cocoonRequest.getSession(arg0); + } - public boolean isRequestedSessionIdValid() { - return this.cocoonRequest.isRequestedSessionIdValid(); - } + public Principal getUserPrincipal() { + return this.cocoonRequest.getUserPrincipal(); + } - public boolean isUserInRole(String arg0) { - return this.cocoonRequest.isUserInRole(arg0); - } + public boolean isRequestedSessionIdFromCookie() { + return this.cocoonRequest.isRequestedSessionIdFromCookie(); + } - public Object getAttribute(String arg0) { - return this.cocoonRequest.getAttribute(arg0); - } + public boolean isRequestedSessionIdFromURL() { + return this.cocoonRequest.isRequestedSessionIdFromURL(); + } - public Enumeration getAttributeNames() { - return this.cocoonRequest.getAttributeNames(); - } + public boolean isRequestedSessionIdFromUrl() { + return this.cocoonRequest.isRequestedSessionIdFromURL(); + } - public String getCharacterEncoding() { - return this.cocoonRequest.getCharacterEncoding(); - } + public boolean isRequestedSessionIdValid() { + return this.cocoonRequest.isRequestedSessionIdValid(); + } - public int getContentLength() { - return this.cocoonRequest.getContentLength(); - } + public boolean isUserInRole(String arg0) { + return this.cocoonRequest.isUserInRole(arg0); + } - public String getContentType() { - return this.cocoonRequest.getContentType(); - } + public Object getAttribute(String arg0) { + return this.cocoonRequest.getAttribute(arg0); + } - public ServletInputStream getInputStream() throws IOException { - throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getInputStream()."); - } + public Enumeration getAttributeNames() { + return this.cocoonRequest.getAttributeNames(); + } - public Locale getLocale() { - return this.cocoonRequest.getLocale(); - } + public String getCharacterEncoding() { + return this.cocoonRequest.getCharacterEncoding(); + } - public Enumeration getLocales() { - return this.cocoonRequest.getLocales(); - } + public int getContentLength() { + return this.cocoonRequest.getContentLength(); + } - public String getParameter(String arg0) { - return this.cocoonRequest.getParameter(arg0); - } + public String getContentType() { + return this.cocoonRequest.getContentType(); + } - public Map getParameterMap() { - throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getParameterMap()."); - } + public ServletInputStream getInputStream() throws IOException { + throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getInputStream()."); + } - public Enumeration getParameterNames() { - return this.cocoonRequest.getParameterNames(); - } + public Locale getLocale() { + return this.cocoonRequest.getLocale(); + } - public String[] getParameterValues(String arg0) { - return this.cocoonRequest.getParameterValues(arg0); - } + public Enumeration getLocales() { + return this.cocoonRequest.getLocales(); + } - public String getProtocol() { - return this.cocoonRequest.getProtocol(); - } + public String getParameter(String arg0) { + return this.cocoonRequest.getParameter(arg0); + } - public BufferedReader getReader() throws IOException { - throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getReader()."); - } + public Map getParameterMap() { + throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getParameterMap()."); + } - public String getRealPath(String arg0) { - throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getRealPath()."); - } + public Enumeration getParameterNames() { + return this.cocoonRequest.getParameterNames(); + } - public String getRemoteAddr() { - return this.cocoonRequest.getRemoteAddr(); - } + public String[] getParameterValues(String arg0) { + return this.cocoonRequest.getParameterValues(arg0); + } - public String getRemoteHost() { - return this.cocoonRequest.getRemoteHost(); - } + public String getProtocol() { + return this.cocoonRequest.getProtocol(); + } - public RequestDispatcher getRequestDispatcher(String arg0) { - throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getRequestDispatcher(arg0)."); - } + public BufferedReader getReader() throws IOException { + throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getReader()."); + } - public String getScheme() { - return this.cocoonRequest.getScheme(); - } + public String getRealPath(String arg0) { + throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getRealPath()."); + } - public String getServerName() { - return this.cocoonRequest.getServerName(); - } + public String getRemoteAddr() { + return this.cocoonRequest.getRemoteAddr(); + } - public int getServerPort() { - return this.cocoonRequest.getServerPort(); - } + public String getRemoteHost() { + return this.cocoonRequest.getRemoteHost(); + } - public boolean isSecure() { - return this.cocoonRequest.isSecure(); - } + public RequestDispatcher getRequestDispatcher(String arg0) { + throw new UnsupportedOperationException("HttpRequestCocoonWrapper does not support getRequestDispatcher(arg0)."); + } - public void removeAttribute(String arg0) { - this.cocoonRequest.removeAttribute(arg0); - } + public String getScheme() { + return this.cocoonRequest.getScheme(); + } - public void setAttribute(String arg0, Object arg1) { - this.cocoonRequest.setAttribute(arg0, arg1); - } + public String getServerName() { + return this.cocoonRequest.getServerName(); + } - public void setCharacterEncoding(String arg0) - throws UnsupportedEncodingException { - this.cocoonRequest.setCharacterEncoding(arg0); - } + public int getServerPort() { + return this.cocoonRequest.getServerPort(); + } - public int getRemotePort() { - return this.cocoonRequest.getRemotePort(); - } + public boolean isSecure() { + return this.cocoonRequest.isSecure(); + } - public String getLocalName() { - return this.cocoonRequest.getLocalName(); - } + public void removeAttribute(String arg0) { + this.cocoonRequest.removeAttribute(arg0); + } - public String getLocalAddr() { - return this.cocoonRequest.getLocalAddr(); - } + public void setAttribute(String arg0, Object arg1) { + this.cocoonRequest.setAttribute(arg0, arg1); + } - public int getLocalPort() { - return this.cocoonRequest.getLocalPort(); - } - - - + public void setCharacterEncoding(String arg0) + throws UnsupportedEncodingException { + this.cocoonRequest.setCharacterEncoding(arg0); + } + public int getRemotePort() { + return this.cocoonRequest.getRemotePort(); + } + + public String getLocalName() { + return this.cocoonRequest.getLocalName(); + } + + public String getLocalAddr() { + return this.cocoonRequest.getLocalAddr(); + } + + public int getLocalPort() { + return this.cocoonRequest.getLocalPort(); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ItemExportDownloadReader.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ItemExportDownloadReader.java index 0a76d63490..d72e34a924 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ItemExportDownloadReader.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ItemExportDownloadReader.java @@ -39,13 +39,13 @@ public class ItemExportDownloadReader extends AbstractReader implements Recyclab { /** - * Messages to be sent when the user is not authorized to view + * Messages to be sent when the user is not authorized to view * a particular bitstream. They will be redirected to the login * where this message will be displayed. */ - private static final String AUTH_REQUIRED_HEADER = "xmlui.ItemExportDownloadReader.auth_header"; - private static final String AUTH_REQUIRED_MESSAGE = "xmlui.ItemExportDownloadReader.auth_message"; - + private static final String AUTH_REQUIRED_HEADER = "xmlui.ItemExportDownloadReader.auth_header"; + private static final String AUTH_REQUIRED_MESSAGE = "xmlui.ItemExportDownloadReader.auth_message"; + /** * How big a buffer should we use when reading from the bitstream before * writing to the HTTP response? @@ -69,12 +69,12 @@ public class ItemExportDownloadReader extends AbstractReader implements Recyclab /** The bitstream file */ protected InputStream compressedExportInputStream; - + /** The compressed export's reported size */ protected long compressedExportSize; - + protected String compressedExportName; - + protected ItemExportService itemExportService = ItemExportServiceFactory.getInstance().getItemExportService(); /** * Set up the export reader. @@ -95,40 +95,42 @@ public class ItemExportDownloadReader extends AbstractReader implements Recyclab // Get our parameters that identify the bitstream String fileName = par.getParameter("fileName", null); - - + + // Is there a User logged in and does the user have access to read it? if (!itemExportService.canDownload(context, fileName)) { - if(context.getCurrentUser()!=null){ - // A user is logged in, but they are not authorized to read this bitstream, - // instead of asking them to login again we'll point them to a friendly error - // message that tells them the bitstream is restricted. - String redictURL = request.getContextPath() + "/restricted-resource?name=" + fileName; + if (context.getCurrentUser()!=null) + { + // A user is logged in, but they are not authorized to read this bitstream, + // instead of asking them to login again we'll point them to a friendly error + // message that tells them the bitstream is restricted. + String redictURL = request.getContextPath() + "/restricted-resource?name=" + fileName; - HttpServletResponse httpResponse = (HttpServletResponse) - objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - httpResponse.sendRedirect(redictURL); - return; - } - else{ + HttpServletResponse httpResponse = (HttpServletResponse) + objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + httpResponse.sendRedirect(redictURL); + return; + } + else + { - // The user does not have read access to this bitstream. Interrupt this current request - // and then forward them to the login page so that they can be authenticated. Once that is - // successful they will request will be resumed. - AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null); + // The user does not have read access to this bitstream. Interrupt this current request + // and then forward them to the login page so that they can be authenticated. Once that is + // successful they will request will be resumed. + AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null); - // Redirect - String redictURL = request.getContextPath() + "/login"; + // Redirect + String redictURL = request.getContextPath() + "/login"; - HttpServletResponse httpResponse = (HttpServletResponse) - objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - httpResponse.sendRedirect(redictURL); - return; - } + HttpServletResponse httpResponse = (HttpServletResponse) + objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + httpResponse.sendRedirect(redictURL); + return; + } } - - + + // Success, bitstream found and the user has access to read it. // Store these for later retrieval: this.compressedExportInputStream = itemExportService.getExportDownloadInputStream(fileName, context.getCurrentUser()); @@ -138,29 +140,29 @@ public class ItemExportDownloadReader extends AbstractReader implements Recyclab catch (Exception e) { throw new ProcessingException("Unable to read bitstream.",e); - } + } } - + /** - * Write the actual data out to the response. - * - * Some implementation notes: - * - * 1) We set a short expiration time just in the hopes of preventing someone - * from overloading the server by clicking reload a bunch of times. I - * Realize that this is nowhere near 100% effective but it may help in some - * cases and shouldn't hurt anything. - * - */ + * Write the actual data out to the response. + * + * Some implementation notes: + * + * 1) We set a short expiration time just in the hopes of preventing someone + * from overloading the server by clicking reload a bunch of times. I + * Realize that this is nowhere near 100% effective but it may help in some + * cases and shouldn't hurt anything. + * + */ public void generate() throws IOException, SAXException, ProcessingException { - if (this.compressedExportInputStream == null) + if (this.compressedExportInputStream == null) { return; } - + byte[] buffer = new byte[BUFFER_SIZE]; int length = -1; @@ -254,21 +256,18 @@ public class ItemExportDownloadReader extends AbstractReader implements Recyclab */ public String getMimeType() { - return itemExportService.COMPRESSED_EXPORT_MIME_TYPE; + return itemExportService.COMPRESSED_EXPORT_MIME_TYPE; } - + /** - * Recycle - */ - public void recycle() { + * Recycle + */ + public void recycle() { this.response = null; this.request = null; this.compressedExportInputStream = null; this.compressedExportSize = 0; this.compressedExportName = null; super.recycle(); - } - - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/NamespaceFilterTransformer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/NamespaceFilterTransformer.java index 58d8d27cb8..b4621469d1 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/NamespaceFilterTransformer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/NamespaceFilterTransformer.java @@ -38,47 +38,47 @@ import org.xml.sax.ext.Attributes2Impl; public class NamespaceFilterTransformer extends AbstractTransformer implements CacheableProcessingComponent { - /** The namespace to be filtered out of the document */ - private String filterNamespace; + /** The namespace to be filtered out of the document */ + private String filterNamespace; - /** The prefixes used to identified the namespace */ - private Stack filterPrefixes = new Stack(); + /** The prefixes used to identified the namespace */ + private Stack filterPrefixes = new Stack(); /** - * Return the cache key. + * Return the cache key. * @return the key. - */ + */ @Override - public Serializable getKey() { - if (filterNamespace != null) + public Serializable getKey() { + if (filterNamespace != null) { return filterNamespace; } - else + else { return "1"; } - } + } - /** - * This cache never invalidates, always return a validating cache. + /** + * This cache never invalidates, always return a validating cache. * @return the validity. - */ + */ @Override - public SourceValidity getValidity() { - // Always returned cached; - return NOPValidity.SHARED_INSTANCE; - } - - - /** - * Setup the processing instruction transformer. The only parameter that - * matters in the {@code src} parameter which should be the path to an XSL - * style sheet to be applied by the client's browser. - * + public SourceValidity getValidity() { + // Always returned cached; + return NOPValidity.SHARED_INSTANCE; + } + + + /** + * Setup the processing instruction transformer. The only parameter that + * matters in the {@code src} parameter which should be the path to an XSL + * style sheet to be applied by the client's browser. + * *

    - * Set up the namespace filter by getting a list of namespaces to be filtered - * from the pipeline. + * Set up the namespace filter by getting a list of namespaces to be filtered + * from the pipeline. * * @param resolver unused. * @param objectModel unused. @@ -87,35 +87,35 @@ public class NamespaceFilterTransformer extends AbstractTransformer implements C * @throws org.apache.cocoon.ProcessingException never. * @throws org.xml.sax.SAXException never. * @throws java.io.IOException never. - */ + */ @Override - public void setup(SourceResolver resolver, Map objectModel, String src, - Parameters parameters) - throws ProcessingException, SAXException, IOException - { - filterNamespace = src; - filterPrefixes.clear(); - } - - - /** Should this namespace be filtered out of the document? */ - private boolean filter(String test) - { - return (filterNamespace != null && filterNamespace.equals(test)); - } - - /** Should this prefix be filtered out of the document? */ - private boolean filterPrefix(String test) - { - if (filterPrefixes.isEmpty()) + public void setup(SourceResolver resolver, Map objectModel, String src, + Parameters parameters) + throws ProcessingException, SAXException, IOException + { + filterNamespace = src; + filterPrefixes.clear(); + } + + + /** Should this namespace be filtered out of the document? */ + private boolean filter(String test) + { + return (filterNamespace != null && filterNamespace.equals(test)); + } + + /** Should this prefix be filtered out of the document? */ + private boolean filterPrefix(String test) + { + if (filterPrefixes.isEmpty()) { return false; } - String peek = filterPrefixes.peek(); - return (peek != null && peek.equals(test)); - } - - /** + String peek = filterPrefixes.peek(); + return (peek != null && peek.equals(test)); + } + + /** * Begin the scope of a prefix-URI Namespace mapping. * * @param prefix The Namespace prefix being declared. @@ -123,16 +123,16 @@ public class NamespaceFilterTransformer extends AbstractTransformer implements C * @throws org.xml.sax.SAXException passed through. */ @Override - public void startPrefixMapping(String prefix, String uri) throws SAXException + public void startPrefixMapping(String prefix, String uri) throws SAXException { - if (filter(uri)) - { - filterPrefixes.push(prefix); - } - else - { - contentHandler.startPrefixMapping(prefix, uri); - } + if (filter(uri)) + { + filterPrefixes.push(prefix); + } + else + { + contentHandler.startPrefixMapping(prefix, uri); + } } /** @@ -142,19 +142,19 @@ public class NamespaceFilterTransformer extends AbstractTransformer implements C * @throws org.xml.sax.SAXException passed through. */ @Override - public void endPrefixMapping(String prefix) throws SAXException + public void endPrefixMapping(String prefix) throws SAXException { - if (filterPrefix(prefix)) - { - filterPrefixes.pop(); - } - else - { - contentHandler.endPrefixMapping(prefix); - } + if (filterPrefix(prefix)) + { + filterPrefixes.pop(); + } + else + { + contentHandler.endPrefixMapping(prefix); + } } - - + + /** * Receive notification of the beginning of an element. * @param uri element namespace. @@ -164,52 +164,52 @@ public class NamespaceFilterTransformer extends AbstractTransformer implements C * @throws org.xml.sax.SAXException passed through. */ @Override - public void startElement(String uri, String loc, String raw, Attributes a) throws SAXException + public void startElement(String uri, String loc, String raw, Attributes a) throws SAXException { - // Reset the namespace context flag. - if (!filter(uri)) - { - List filterAttributeIndexes = new ArrayList(); - - for (int i = 0; i < a.getLength(); i++) - { - if (filter(a.getURI(i))) + // Reset the namespace context flag. + if (!filter(uri)) + { + List filterAttributeIndexes = new ArrayList(); + + for (int i = 0; i < a.getLength(); i++) + { + if (filter(a.getURI(i))) { // Add it to the list of filtered indexes. filterAttributeIndexes.add(i); } - } - - // Check if any of the attributes are to be filtered if so, filter them out. - if (!filterAttributeIndexes.isEmpty()) - { - // New set of attributes. - Attributes2Impl a2 = new Attributes2Impl(); - - for (int i = 0; i < a.getLength(); i++) - { - if (filterAttributeIndexes.contains(i)) + } + + // Check if any of the attributes are to be filtered if so, filter them out. + if (!filterAttributeIndexes.isEmpty()) + { + // New set of attributes. + Attributes2Impl a2 = new Attributes2Impl(); + + for (int i = 0; i < a.getLength(); i++) + { + if (filterAttributeIndexes.contains(i)) { // This index is to be filtered. continue; } - - String a_uri = a.getURI(i); - String a_localName = a.getLocalName(i); - String a_qName = a.getQName(i); - String a_type = a.getType(i); - String a_value = a.getValue(i); - - // Add the new attribute - a2.addAttribute(a_uri, a_localName, a_qName, a_type, a_value); - } - - // Use our new filtered attributes. - a = a2; - } - - contentHandler.startElement(uri, loc, raw, a); - } + + String a_uri = a.getURI(i); + String a_localName = a.getLocalName(i); + String a_qName = a.getQName(i); + String a_type = a.getType(i); + String a_value = a.getValue(i); + + // Add the new attribute + a2.addAttribute(a_uri, a_localName, a_qName, a_type, a_value); + } + + // Use our new filtered attributes. + a = a2; + } + + contentHandler.startElement(uri, loc, raw, a); + } } /** @@ -220,12 +220,11 @@ public class NamespaceFilterTransformer extends AbstractTransformer implements C * @throws org.xml.sax.SAXException passed through. */ @Override - public void endElement(String uri, String loc, String raw) throws SAXException + public void endElement(String uri, String loc, String raw) throws SAXException { - if (!filter(uri)) - { - contentHandler.endElement(uri, loc, raw); - } + if (!filter(uri)) + { + contentHandler.endElement(uri, loc, raw); + } } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/OpenURLReader.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/OpenURLReader.java index 042e161e46..6f34cfe2cf 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/OpenURLReader.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/OpenURLReader.java @@ -41,276 +41,288 @@ import org.xml.sax.SAXException; /** * Simple servlet for open URL support. Presently, simply extracts terms from * open URL and redirects to search. - * + * * @author Robert Tansley * @author Mark Diggory (mdiggory at mire.be) * @version $Revision$ */ public class OpenURLReader extends AbstractReader implements Recyclable { - private static final String Z39882004 = "Z39.88-2004"; + private static final String Z39882004 = "Z39.88-2004"; - private static final String Z39882004DC = "info:ofi/fmt:kev:mtx:dc"; + private static final String Z39882004DC = "info:ofi/fmt:kev:mtx:dc"; - private static final String Z39882004CTX = "info:ofi/fmt:kev:mtx:ctx"; + private static final String Z39882004CTX = "info:ofi/fmt:kev:mtx:ctx"; - /** The Cocoon response */ - protected Response response; + /** The Cocoon response */ + protected Response response; - /** The Cocoon request */ - protected Request request; + /** The Cocoon request */ + protected Request request; - /** The Servlet Response */ - protected HttpServletResponse httpResponse; + /** The Servlet Response */ + protected HttpServletResponse httpResponse; - protected Context context; + protected Context context; - /** Logger */ - private static Logger log = Logger.getLogger(OpenURLReader.class); + /** Logger */ + private static Logger log = Logger.getLogger(OpenURLReader.class); - protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); + protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); @Override - public void generate() throws IOException, SAXException, - ProcessingException { - } + public void generate() + throws IOException, SAXException, ProcessingException + { + } - @Override - public void setup(SourceResolver resolver, Map objectModel, String src, - Parameters par) throws ProcessingException, SAXException, - IOException { + @Override + public void setup(SourceResolver resolver, Map objectModel, String src, + Parameters par) throws ProcessingException, SAXException, + IOException + { + super.setup(resolver, objectModel, src, par); - super.setup(resolver, objectModel, src, par); + try { + this.httpResponse = (HttpServletResponse) objectModel + .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); + this.request = ObjectModelHelper.getRequest(objectModel); + this.response = ObjectModelHelper.getResponse(objectModel); + this.context = ContextUtil.obtainContext(objectModel); - try { - this.httpResponse = (HttpServletResponse) objectModel - .get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - this.request = ObjectModelHelper.getRequest(objectModel); - this.response = ObjectModelHelper.getResponse(objectModel); - this.context = ContextUtil.obtainContext(objectModel); - - if (Z39882004.equals(request.getParameter("url_ver"))) { - handleZ39882004(); - } else { - handleLegacy(); - } - } catch (SQLException sqle) { - throw new ProcessingException("Unable to resolve OpenURL.", sqle); - } - - } - - @Override - public void recycle() { - super.recycle(); - this.response = null; - this.request = null; - this.httpResponse = null; - this.context = null; - } - - public void handleLegacy() throws IOException { - String query = ""; - - String title = request.getParameter("title"); - String authorFirst = request.getParameter("aufirst"); - String authorLast = request.getParameter("aulast"); - - String logInfo = ""; - - if (title != null) { - query = query + " " + title; - logInfo = logInfo + "title=\"" + title + "\","; - } - - if (authorFirst != null) { - query = query + " " + authorFirst; - logInfo = logInfo + "aufirst=\"" + authorFirst + "\","; - } - - if (authorLast != null) { - query = query + " " + authorLast; - logInfo = logInfo + "aulast=\"" + authorLast + "\","; - } - - log.info(LogManager.getHeader(context, "openURL", logInfo - + "dspacequery=" + query)); - - httpResponse.sendRedirect(httpResponse.encodeRedirectURL(request - .getContextPath() - + "/simple-search?query=" + query)); - - } - - private String getFirstHandle(String query) throws IOException { - - // Construct a Discovery query - DiscoverQuery queryArgs = new DiscoverQuery(); - queryArgs.setQuery(query); - // we want Items only - queryArgs.setDSpaceObjectFilter(Constants.ITEM); - - try - { - DiscoverResult queryResults = SearchUtils.getSearchService().search(context, queryArgs); - List objResults = queryResults.getDspaceObjects(); - - if(objResults!=null && !objResults.isEmpty()) - return objResults.get(0).getHandle(); - else - return null; + if (Z39882004.equals(request.getParameter("url_ver"))) { + handleZ39882004(); + } else { + handleLegacy(); } - catch(SearchServiceException e) - { - throw new IOException(e); - } - } + } catch (SQLException sqle) { + throw new ProcessingException("Unable to resolve OpenURL.", sqle); + } - /** - * Validate supported formats. - * + } + + @Override + public void recycle() { + super.recycle(); + this.response = null; + this.request = null; + this.httpResponse = null; + this.context = null; + } + + public void handleLegacy() + throws IOException + { + String query = ""; + + String title = request.getParameter("title"); + String authorFirst = request.getParameter("aufirst"); + String authorLast = request.getParameter("aulast"); + + String logInfo = ""; + + if (title != null) { + query = query + " " + title; + logInfo = logInfo + "title=\"" + title + "\","; + } + + if (authorFirst != null) { + query = query + " " + authorFirst; + logInfo = logInfo + "aufirst=\"" + authorFirst + "\","; + } + + if (authorLast != null) { + query = query + " " + authorLast; + logInfo = logInfo + "aulast=\"" + authorLast + "\","; + } + + log.info(LogManager.getHeader(context, "openURL", logInfo + + "dspacequery=" + query)); + + httpResponse.sendRedirect(httpResponse.encodeRedirectURL(request + .getContextPath() + + "/simple-search?query=" + query)); + } + + private String getFirstHandle(String query) + throws IOException + { + + // Construct a Discovery query + DiscoverQuery queryArgs = new DiscoverQuery(); + queryArgs.setQuery(query); + // we want Items only + queryArgs.setDSpaceObjectFilter(Constants.ITEM); + + try + { + DiscoverResult queryResults = SearchUtils.getSearchService().search(context, queryArgs); + List objResults = queryResults.getDspaceObjects(); + + if (objResults!=null && !objResults.isEmpty()) + return objResults.get(0).getHandle(); + else + return null; + } + catch (SearchServiceException e) + { + throw new IOException(e); + } + } + + /** + * Validate supported formats. + * *

    - * We can deal with various formats if they exist such as journals and - * books, but we currently do not have specific needs to represent - * different formats, thus it may be more appropriate to use Dublin Core - * here directly. - * + * We can deal with various formats if they exist such as journals and + * books, but we currently do not have specific needs to represent + * different formats, thus it may be more appropriate to use Dublin Core + * here directly. + * *

    - * {@code rft_val_fmt=info:ofi/fmt:kev:mtx:dc} - * + * {@code rft_val_fmt=info:ofi/fmt:kev:mtx:dc} + * *

    - * See Dublin Core OpenURL Profile Citation Guidelines: + * See Dublin Core OpenURL Profile Citation Guidelines: *

    - * + * *

    - * What happens when we use Context Objects of different versions? Do - * they exist? {@code ctx_ver=Z39.88-2004} - * + * What happens when we use Context Objects of different versions? Do + * they exist? {@code ctx_ver=Z39.88-2004} + * *

    - * COinS will be implemented as: - * + * COinS will be implemented as: + * *

    {@code
    -	 * 
    -	 *  
    -	 *   Find at Example Library
    +     * 
    +     *  
    +     *   Find at Example Library
          *  
          * 
          * }
    - * - * If a {@code ctx_id} is present, use it to resolve the item directly. - * Otherwise, use the search mechanism. Our {@code ctx_id}s are going to be + * + * If a {@code ctx_id} is present, use it to resolve the item directly. + * Otherwise, use the search mechanism. Our {@code ctx_id}s are going to be * local handle identifiers like the following: - * + * *

    - * {@code ctx_id=10255/dryad.111} - * + * {@code ctx_id=10255/dryad.111} + * *

    - * Global identifiers will be any other valid {@code dc.identifier} present - * within that field. Thus: - * + * Global identifiers will be any other valid {@code dc.identifier} present + * within that field. Thus: + * *

    {@code
    -	 * dc.identifier.uri http://dx.doi.org/10.1080/106351598260806
    -	 * dc.identifier.uri http://hdl.handle.net/10255/dryad.111
    +     * dc.identifier.uri http://dx.doi.org/10.1080/106351598260806
    +     * dc.identifier.uri http://hdl.handle.net/10255/dryad.111
          * }
    - * - * will lead to - * + * + * will lead to + * *
    {@code
    -	 * rft.identifier=http%3A%2F%2Fdx.doi.org%2F10.1080%2F106351598260806
    -	 * rft.identifier=http%3A%2F%2Fhdl.handle.net%2F10255%2Fdryad.111
    +     * rft.identifier=http%3A%2F%2Fdx.doi.org%2F10.1080%2F106351598260806
    +     * rft.identifier=http%3A%2F%2Fhdl.handle.net%2F10255%2Fdryad.111
          * }
    - * - * and thus be resolvable as well + * + * and thus be resolvable as well * * @throws java.io.IOException passed through. * @throws org.apache.cocoon.ProcessingException on unknown formats. - * @throws SQLException passed through. - */ - public void handleZ39882004() throws IOException, ProcessingException, SQLException { - - String rft_val_fmt = request.getParameter("rft_val_fmt"); - if (rft_val_fmt != null && !rft_val_fmt.equals(Z39882004DC)) - { - throw new ProcessingException( - "DSpace 1.0 OpenURL Service only supports rft_val_fmt=" - + Z39882004DC); - } + * @throws SQLException passed through. + */ + public void handleZ39882004() + throws IOException, ProcessingException, SQLException + { - String url_ctx_fmt = request.getParameter("url_ctx_fmt"); - if (url_ctx_fmt != null && !url_ctx_fmt.equals(Z39882004CTX)) - { - throw new ProcessingException( - "DSpace 1.0 OpenURL Service only supports url_ctx_fmt=" - + Z39882004CTX); - } + String rft_val_fmt = request.getParameter("rft_val_fmt"); + if (rft_val_fmt != null && !rft_val_fmt.equals(Z39882004DC)) + { + throw new ProcessingException( + "DSpace 1.0 OpenURL Service only supports rft_val_fmt=" + + Z39882004DC); + } - /** - * First attempt to resolve an rft_id identifier as a handle - */ - String[] rft_ids = request.getParameterValues("rft_id"); + String url_ctx_fmt = request.getParameter("url_ctx_fmt"); + if (url_ctx_fmt != null && !url_ctx_fmt.equals(Z39882004CTX)) + { + throw new ProcessingException( + "DSpace 1.0 OpenURL Service only supports url_ctx_fmt=" + + Z39882004CTX); + } - if(rft_ids != null) - { - for (String rft_id : rft_ids) { - DSpaceObject obj = handleService.resolveToObject(context, rft_id); - if (obj != null) { - httpResponse.sendRedirect(httpResponse - .encodeRedirectURL(request.getContextPath() - + "/handle/" + obj.getHandle())); - return; - } - } - } - + /** + * First attempt to resolve an rft_id identifier as a handle + */ + String[] rft_ids = request.getParameterValues("rft_id"); - String[] identifiers = request.getParameterValues("rtf.identifier"); + if (rft_ids != null) + { + for (String rft_id : rft_ids) { + DSpaceObject obj = handleService.resolveToObject(context, rft_id); + if (obj != null) { + httpResponse.sendRedirect(httpResponse + .encodeRedirectURL(request.getContextPath() + + "/handle/" + obj.getHandle())); + return; + } + } + } - /** - * Next attempt to resolve an identifier in search - */ - if(identifiers != null) - { - for (String identifier : identifiers) { - String handle = getFirstHandle("identifier: " + identifier); - if (handle != null) { - httpResponse.sendRedirect(httpResponse - .encodeRedirectURL(request.getContextPath() - + "/handle/" + handle)); - return; - } - } - } - - /** - * Otherwise, attempt to full text search for the item - */ - StringBuilder queryBuilder = new StringBuilder(); + String[] identifiers = request.getParameterValues("rtf.identifier"); - Enumeration e = request.getParameterNames(); + /** + * Next attempt to resolve an identifier in search + */ + if (identifiers != null) + { + for (String identifier : identifiers) + { + String handle = getFirstHandle("identifier: " + identifier); + if (handle != null) + { + httpResponse.sendRedirect(httpResponse + .encodeRedirectURL(request.getContextPath() + + "/handle/" + handle)); + return; + } + } + } - while (e.hasMoreElements()) { - String name = e.nextElement(); - if (name.startsWith("rft.")) { - for (String value : request.getParameterValues(name)) { - queryBuilder.append(value).append(" "); - } - } - } + + /** + * Otherwise, attempt to full text search for the item + */ + StringBuilder queryBuilder = new StringBuilder(); + + Enumeration e = request.getParameterNames(); + + while (e.hasMoreElements()) + { + String name = e.nextElement(); + if (name.startsWith("rft.")) + { + for (String value : request.getParameterValues(name)) + { + queryBuilder.append(value).append(" "); + } + } + } String query = queryBuilder.toString().trim(); - if(query.length() == 0) - { - httpResponse.sendError(httpResponse.SC_BAD_REQUEST, "OpenURL Request requires a valid rtf_id, rtf.identifier or other rtf. search fields" ); - } - - httpResponse.sendRedirect(httpResponse.encodeRedirectURL(request - .getContextPath() - + "/simple-search?query=" + java.net.URLEncoder.encode(query, request.getCharacterEncoding()))); + if (query.length() == 0) + { + httpResponse.sendError(httpResponse.SC_BAD_REQUEST, "OpenURL Request requires a valid rtf_id, rtf.identifier or other rtf. search fields" ); + } - } + httpResponse.sendRedirect(httpResponse.encodeRedirectURL( + request.getContextPath() + + "/simple-search?query=" + + java.net.URLEncoder.encode( + query, request.getCharacterEncoding()))); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/PropertyFileReader.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/PropertyFileReader.java index 7e8d4150dd..39be8016b4 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/PropertyFileReader.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/PropertyFileReader.java @@ -23,11 +23,11 @@ import org.apache.cocoon.environment.SourceResolver; * It accepts the name of the property file to read and the properties to set to * the sitemap scope. For example: *
    {@code
    - * 		
    - *  		
    - *			...
    - *		
    + *         
    + *          
    + *            ...
    + *        
      * }
    * Will place the value of the "some.property" property in the "some_property" variable to be * used in the sitemap using the {some_property} syntax. @@ -37,32 +37,34 @@ import org.apache.cocoon.environment.SourceResolver; */ public class PropertyFileReader { - public Map act(Redirector redirector, SourceResolver resolver, - Map objectModel, String source, Parameters parameters) - throws Exception { - Map map = new HashMap(); + public Map act(Redirector redirector, SourceResolver resolver, + Map objectModel, String source, Parameters parameters) + throws Exception + { + Map map = new HashMap(); - String propertyFile = parameters.getParameter("property-file"); - - Properties props = new Properties(); - InputStream in = new FileInputStream(propertyFile); + String propertyFile = parameters.getParameter("property-file"); + + Properties props = new Properties(); + InputStream in = new FileInputStream(propertyFile); try { - props.load(in); + props.load(in); } finally { - in.close(); + in.close(); } - - final String[] parameterNames = parameters.getNames(); - - for (int i = 0; i < parameterNames.length; i++) { - final String paramName = parameterNames[i]; - if ("property-file".equals(paramName)) { - continue; - } - map.put(parameters.getParameter(paramName), props - .getProperty(paramName)); - } - return map; - } + final String[] parameterNames = parameters.getNames(); + + for (int i = 0; i < parameterNames.length; i++) + { + final String paramName = parameterNames[i]; + if ("property-file".equals(paramName)) { + continue; + } + map.put(parameters.getParameter(paramName), props + .getProperty(paramName)); + } + + return map; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SearchMetadataExportReader.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SearchMetadataExportReader.java index 43c1fa02e5..dd7738a0dd 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SearchMetadataExportReader.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SearchMetadataExportReader.java @@ -50,15 +50,15 @@ import org.dspace.discovery.*; * result metadata using MetadataExport. */ public class SearchMetadataExportReader extends AbstractReader implements Recyclable -{ - /** - * Messages to be sent when the user is not authorized to view +{ + /** + * Messages to be sent when the user is not authorized to view * a particular bitstream. They will be redirected to the login * where this message will be displayed. */ - private static final String AUTH_REQUIRED_HEADER = "xmlui.ItemExportDownloadReader.auth_header"; - private static final String AUTH_REQUIRED_MESSAGE = "xmlui.ItemExportDownloadReader.auth_message"; - + private static final String AUTH_REQUIRED_HEADER = "xmlui.ItemExportDownloadReader.auth_header"; + private static final String AUTH_REQUIRED_MESSAGE = "xmlui.ItemExportDownloadReader.auth_message"; + /** * How big a buffer should we use when reading from the bitstream before * writing to the HTTP response? @@ -69,7 +69,7 @@ public class SearchMetadataExportReader extends AbstractReader implements Recycl * When should a download expire in milliseconds. This should be set to * some low value just to prevent someone hitting DSpace repeatedly from * killing the server. Note: there are 60000 milliseconds in a minute. - * + * * Format: minutes * seconds * milliseconds */ protected static final int expires = 60 * 60 * 60000; @@ -79,18 +79,18 @@ public class SearchMetadataExportReader extends AbstractReader implements Recycl /** The Cocoon request */ protected Request request; - - + + private static Logger log = Logger.getLogger(SearchMetadataExportReader.class); - - private AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); + + private AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService(); private HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); private DSpaceCSV csv = null; private String filename = null; - + private SimpleSearch simpleSearch = null; - + /** * Set up the export reader. * See the class description for information on configuration options. @@ -111,32 +111,35 @@ public class SearchMetadataExportReader extends AbstractReader implements Recycl try { - this.request = ObjectModelHelper.getRequest(objectModel); - this.response = ObjectModelHelper.getResponse(objectModel); - - String query = request.getParameter("query"); - String scope = request.getParameter("scope"); - String filters = request.getParameter("filters"); - + this.request = ObjectModelHelper.getRequest(objectModel); + this.response = ObjectModelHelper.getResponse(objectModel); + + String query = request.getParameter("query"); + String scope = request.getParameter("scope"); + String filters = request.getParameter("filters"); + Context context = ContextUtil.obtainContext(objectModel); - + String search_export_config = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.search.metadata_export"); - - - if(search_export_config.equals("admin")) { - if(!authorizeService.isAdmin(context)) { + + if (search_export_config.equals("admin")) + { + if (!authorizeService.isAdmin(context)) + { /* * Auth should be done by MetadataExport -- pass context through * we should just be catching exceptions and displaying errors here */ - if(AuthenticationUtil.isLoggedIn(request)) { - String redictURL = request.getContextPath() + "/restricted-resource"; + if (AuthenticationUtil.isLoggedIn(request)) + { + String redictURL = request.getContextPath() + "/restricted-resource"; HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); - httpResponse.sendRedirect(redictURL); - return; + httpResponse.sendRedirect(redictURL); + return; } - else { - String redictURL = request.getContextPath() + "/login"; + else + { + String redictURL = request.getContextPath() + "/login"; AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null); HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); @@ -144,39 +147,41 @@ public class SearchMetadataExportReader extends AbstractReader implements Recycl } } } - else if(search_export_config.equals("user")) { - if(!AuthenticationUtil.isLoggedIn(request)) { - String redictURL = request.getContextPath() + "/login"; + else if (search_export_config.equals("user")) + { + if (!AuthenticationUtil.isLoggedIn(request)) + { + String redictURL = request.getContextPath() + "/login"; AuthenticationUtil.interruptRequest(objectModel, AUTH_REQUIRED_HEADER, AUTH_REQUIRED_MESSAGE, null); HttpServletResponse httpResponse = (HttpServletResponse) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT); httpResponse.sendRedirect(redictURL); return; } } - + simpleSearch = new SimpleSearch(); - + csv = exportMetadata(context, objectModel, query, scope, filters); filename = "search-results.csv"; - + } catch (RuntimeException e) { - throw e; + throw e; } catch (IOException e) { - throw new ProcessingException("Unable to export metadata.",e); + throw new ProcessingException("Unable to export metadata.",e); } catch (Exception e) { throw new ProcessingException("Unable to read bitstream.",e); - } + } } - + /** - * Write the CSV. + * Write the CSV. * @throws java.io.IOException passed through. * @throws org.xml.sax.SAXException passed through. * @throws org.apache.cocoon.ProcessingException passed through. - */ + */ @Override public void generate() throws IOException, SAXException, ProcessingException { @@ -186,16 +191,16 @@ public class SearchMetadataExportReader extends AbstractReader implements Recycl out.flush(); out.close(); } - + /** - * Recycle - */ + * Recycle + */ @Override - public void recycle() { + public void recycle() { this.response = null; this.request = null; } - + /** * Save and return the search results as a CSV file. * @@ -213,73 +218,77 @@ public class SearchMetadataExportReader extends AbstractReader implements Recycl public DSpaceCSV exportMetadata(Context context, Map objectModel, String query, String scopeString, String filters) throws IOException, UIException, SearchServiceException, SQLException { - DiscoverResult qResults = new DiscoverResult(); - - DiscoverQuery qArgs = new DiscoverQuery(); - - // Are we in a community or collection? + DiscoverResult qResults = new DiscoverResult(); + + DiscoverQuery qArgs = new DiscoverQuery(); + + // Are we in a community or collection? DSpaceObject scope; - - if(scopeString != null && scopeString.length() > 0) { - scopeString = scopeString.replace("~", "/"); - // Get the search scope from the location parameter - scope = handleService.resolveToObject(context, scopeString); - } - else { - // get the search scope from the url handle - scope = HandleUtil.obtainHandle(objectModel); - } - - + + if (scopeString != null && scopeString.length() > 0) + { + scopeString = scopeString.replace("~", "/"); + // Get the search scope from the location parameter + scope = handleService.resolveToObject(context, scopeString); + } + else + { + // get the search scope from the url handle + scope = HandleUtil.obtainHandle(objectModel); + } + + // set the object model on the simple search object simpleSearch.objectModel = objectModel; - + String[] fqs = filters != null ? filters.split(",") : new String[0]; - + // prepare query from SimpleSearch object qArgs = simpleSearch.prepareQuery(scope, query, fqs); - + // no paging required qArgs.setStart(0); - + // some arbitrary value for first search qArgs.setMaxResults(10); - + // search once to get total search results qResults = SearchUtils.getSearchService().search(context, scope, qArgs); - + // set max results to total search results - qArgs.setMaxResults(safeLongToInt(qResults.getTotalSearchResults())); - + qArgs.setMaxResults(safeLongToInt(qResults.getTotalSearchResults())); + // search again to return all search results qResults = SearchUtils.getSearchService().search(context, scope, qArgs); - - // Get a list of found items - ArrayList items = new ArrayList(); - for (DSpaceObject resultDSO : qResults.getDspaceObjects()) { - if (resultDSO instanceof Item) { + + // Get a list of found items + ArrayList items = new ArrayList(); + for (DSpaceObject resultDSO : qResults.getDspaceObjects()) + { + if (resultDSO instanceof Item) + { items.add((Item) resultDSO); } - } - + } + // Log the attempt log.info(LogManager.getHeader(context, "metadataexport", "exporting_search")); MetadataExport exporter = new MetadataExport(context, items.iterator(), false); - + // Perform the export DSpaceCSV csv = exporter.export(); log.info(LogManager.getHeader(context, "metadataexport", "exported_file:search-results.csv")); - + return csv; } - + public static int safeLongToInt(long l) { - if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { + if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) + { throw new IllegalArgumentException(l + " cannot be cast to int."); } return (int) l; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SetCharacterEncodingFilter.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SetCharacterEncodingFilter.java index 00594a3a5a..5b19efaa8e 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SetCharacterEncodingFilter.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/SetCharacterEncodingFilter.java @@ -90,8 +90,8 @@ public class SetCharacterEncodingFilter implements Filter * @param response The servlet response we are creating * @param chain The filter chain we are processing * - * @exception IOException if an input/output error occurs - * @exception ServletException if a servlet error occurs + * @throws IOException if an input/output error occurs + * @throws ServletException if a servlet error occurs */ @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java index 262586b95b..4397b72eb0 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/ThemeMatcher.java @@ -30,123 +30,125 @@ import org.dspace.services.factory.DSpaceServicesFactory; * determined by the Theme rules defined in the xmlui.xml configuration file. * Each rule is evaluated in order and the first rule to match is the selected * Theme. - * + * * Once the Theme has been selected the following sitemap parameters are * provided: {themeName} is a unique name for the Theme, and {theme} is the * theme's path. - * + * * @author Scott Phillips */ public class ThemeMatcher extends AbstractLogEnabled implements Matcher { - /** - * @param src - * name of sitemap parameter to find (ignored) - * @param objectModel - * environment passed through via cocoon - * @param parameters - * parameters passed to this matcher in the sitemap - * @return null or map containing value of sitemap parameter 'src' - */ - public Map match(String src, Map objectModel, Parameters parameters) - throws PatternException { - try { - Request request = ObjectModelHelper.getRequest(objectModel); - String uri = request.getSitemapURI(); - DSpaceObject dso = HandleUtil.obtainHandle(objectModel); + /** + * @param src + * name of sitemap parameter to find (ignored) + * @param objectModel + * environment passed through via cocoon + * @param parameters + * parameters passed to this matcher in the sitemap + * @return null or map containing value of sitemap parameter 'src' + */ + public Map match(String src, Map objectModel, Parameters parameters) + throws PatternException { + try { + Request request = ObjectModelHelper.getRequest(objectModel); + String uri = request.getSitemapURI(); + DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - - // Allow the user to override the theme configuration - if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.theme.allowoverrides",false)) - { - String themePathOverride = request.getParameter("themepath"); - if (themePathOverride != null && themePathOverride.length() > 0) - { - // Allowing the user to specify the theme path is a security risk because it - // allows the user to direct which sitemap is executed next. An attacker could - // use this in combination with another attack execute code on the server. - // Ultimately this option should not be turned on in a production system and - // only used in development. However lets do some simple sanity checks to - // protect us a little even when under development. - - // Allow: allow all letters and numbers plus periods (but not consecutive), - // dashes, underscores, and forward slashes - if (!themePathOverride.matches("^[a-zA-Z0-9][a-zA-Z0-9/_\\-]*/?$")) { - - throw new IllegalArgumentException("The user specified theme path, \""+themePathOverride+"\", may be " + - "an exploit attempt. To use this feature please limit your theme paths to only letters " + - "(a-Z), numbers(0-9), dashes(-), underscores (_), and trailing forward slashes (/)."); - } - - // The user is selecting to override a theme, ignore any set - // rules to apply and use the one specified. - String themeNameOverride = request.getParameter("themename"); - String themeIdOverride = request.getParameter("themeid"); - - if (themeNameOverride == null || themeNameOverride.length() == 0) + + // Allow the user to override the theme configuration + if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.theme.allowoverrides",false)) + { + String themePathOverride = request.getParameter("themepath"); + if (themePathOverride != null && themePathOverride.length() > 0) + { + // Allowing the user to specify the theme path is a security risk because it + // allows the user to direct which sitemap is executed next. An attacker could + // use this in combination with another attack execute code on the server. + // Ultimately this option should not be turned on in a production system and + // only used in development. However lets do some simple sanity checks to + // protect us a little even when under development. + + // Allow: allow all letters and numbers plus periods (but not consecutive), + // dashes, underscores, and forward slashes + if (!themePathOverride.matches("^[a-zA-Z0-9][a-zA-Z0-9/_\\-]*/?$")) { + + throw new IllegalArgumentException("The user specified theme path, \""+themePathOverride+"\", may be " + + "an exploit attempt. To use this feature please limit your theme paths to only letters " + + "(a-Z), numbers(0-9), dashes(-), underscores (_), and trailing forward slashes (/)."); + } + + // The user is selecting to override a theme, ignore any set + // rules to apply and use the one specified. + String themeNameOverride = request.getParameter("themename"); + String themeIdOverride = request.getParameter("themeid"); + + if (themeNameOverride == null || themeNameOverride.length() == 0) { themeNameOverride = "User specified theme"; } - - getLogger().debug("User as specified to override theme selection with theme "+ - "(name=\""+themeNameOverride+"\", path=\""+themePathOverride+"\", id=\""+themeIdOverride+"\")"); - - Map result = new HashMap(); - result.put("themeName", themeNameOverride); - result.put("theme", themePathOverride); - result.put("themeID", themeIdOverride); - - return result; - } - } - - - List rules = XMLUIConfiguration.getThemeRules(); - getLogger().debug("Checking if URL=" + uri + " matches any theme rules."); - for (Theme rule : rules) { - getLogger().debug("rule=" + rule.getName()); - if (!(rule.hasRegex() || rule.hasHandle())) + + getLogger().debug("User as specified to override theme selection with theme "+ + "(name=\""+themeNameOverride+"\", path=\""+themePathOverride+"\", id=\""+themeIdOverride+"\")"); + + Map result = new HashMap(); + result.put("themeName", themeNameOverride); + result.put("theme", themePathOverride); + result.put("themeID", themeIdOverride); + + return result; + } + } + + + List rules = XMLUIConfiguration.getThemeRules(); + getLogger().debug("Checking if URL=" + uri + " matches any theme rules."); + for (Theme rule : rules) { + getLogger().debug("rule=" + rule.getName()); + if (!(rule.hasRegex() || rule.hasHandle())) { // Skip any rule without a pattern or handle continue; } - getLogger().debug("checking for patterns"); - if (rule.hasRegex()) { - // If the rule has a pattern ensure that the URL matches it. - Pattern pattern = rule.getPattern(); - if (!pattern.matcher(uri).find()) + getLogger().debug("checking for patterns"); + if (rule.hasRegex()) + { + // If the rule has a pattern ensure that the URL matches it. + Pattern pattern = rule.getPattern(); + if (!pattern.matcher(uri).find()) { continue; } - } + } - getLogger().debug("checking for handles"); - if (rule.hasHandle() && !HandleUtil.inheritsFrom(dso, rule.getHandle())) + getLogger().debug("checking for handles"); + if (rule.hasHandle() && !HandleUtil.inheritsFrom(dso, rule.getHandle())) { continue; } - getLogger().debug("rule selected!!"); - Map result = new HashMap(); - result.put("themeName", rule.getName()); - result.put("theme", rule.getPath()); - result.put("themeID", rule.getId()); - - request.getSession().setAttribute("themeName", rule.getName()); - request.getSession().setAttribute("theme", rule.getPath()); - request.getSession().setAttribute("themeID", rule.getId()); - - return result; - } + getLogger().debug("rule selected!!"); + Map result = new HashMap(); + result.put("themeName", rule.getName()); + result.put("theme", rule.getPath()); + result.put("themeID", rule.getId()); - } catch (SQLException sqle) { - throw new PatternException(sqle); - } + request.getSession().setAttribute("themeName", rule.getName()); + request.getSession().setAttribute("theme", rule.getPath()); + request.getSession().setAttribute("themeID", rule.getId()); - // No themes matched. - return null; - } + return result; + } + } + catch (SQLException sqle) + { + throw new PatternException(sqle); + } + + // No themes matched. + return null; + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/UsageLoggerAction.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/UsageLoggerAction.java index 81607a928c..1ef29bfe09 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/UsageLoggerAction.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/cocoon/UsageLoggerAction.java @@ -41,17 +41,23 @@ public class UsageLoggerAction extends AbstractAction { protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService(); - public Map act(Redirector redirector, SourceResolver sourceResolver, Map objectModel, String string, Parameters parameters) throws Exception { - try{ + public Map act(Redirector redirector, SourceResolver sourceResolver, Map objectModel, String string, Parameters parameters) + throws Exception + { + try + { Request request = ObjectModelHelper.getRequest(objectModel); Context context = ContextUtil.obtainContext(objectModel); DSpaceObject dso = HandleUtil.obtainHandle(objectModel); - if(dso == null){ + if (dso == null) + { //We might have a bitstream dso = findBitstream(context, parameters); } logDspaceObject(request, dso, context); - }catch(Exception e){ + } + catch(Exception e) + { // Ignore, we cannot let this crash // TODO: log this e.printStackTrace(); @@ -62,25 +68,27 @@ public class UsageLoggerAction extends AbstractAction { } public static void logDspaceObject(Request request, DSpaceObject dso, Context context){ - if(dso == null) + if (dso == null) { return; } - try { - + try + { DSpaceServicesFactory.getInstance().getEventService().fireEvent( - new UsageEvent( - UsageEvent.Action.VIEW, - (HttpServletRequest)request, - ContextUtil.obtainContext((HttpServletRequest)request), - dso)); - - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + new UsageEvent( + UsageEvent.Action.VIEW, + (HttpServletRequest) request, + ContextUtil.obtainContext((HttpServletRequest) request), + dso)); + + } + catch (SQLException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } private Bitstream findBitstream(Context context, Parameters par) throws SQLException { @@ -148,21 +156,21 @@ public class UsageLoggerAction extends AbstractAction { */ private Bitstream findBitstreamBySequence(Item item, int sequence) throws SQLException { - if (item == null) + if (item == null) { return null; } - List bundles = item.getBundles(); + List bundles = item.getBundles(); for (Bundle bundle : bundles) { List bitstreams = bundle.getBitstreams(); for (Bitstream bitstream : bitstreams) { - if (bitstream.getSequenceID() == sequence) - { - return bitstream; + if (bitstream.getSequenceID() == sequence) + { + return bitstream; } } } @@ -181,68 +189,68 @@ public class UsageLoggerAction extends AbstractAction { */ private Bitstream findBitstreamByName(Item item, String name) throws SQLException { - if (name == null || item == null) + if (name == null || item == null) { return null; } - // Determine our the maximum number of directories that will be removed for a path. - int maxDepthPathSearch = 3; - if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.html.max-depth-guess") != null) + // Determine our the maximum number of directories that will be removed for a path. + int maxDepthPathSearch = 3; + if (DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("xmlui.html.max-depth-guess") != null) { maxDepthPathSearch = DSpaceServicesFactory.getInstance().getConfigurationService().getIntProperty("xmlui.html.max-depth-guess"); } - // Search for the named bitstream on this item. Each time through the loop - // a directory is removed from the name until either our maximum depth is - // reached or the bitstream is found. Note: an extra pass is added on to the - // loop for a last ditch effort where all directory paths will be removed. - for (int i = 0; i < maxDepthPathSearch+1; i++) - { - // Search through all the bitstreams and see - // if the name can be found - List bundles = item.getBundles(); - for (Bundle bundle : bundles) - { - List bitstreams = bundle.getBitstreams(); + // Search for the named bitstream on this item. Each time through the loop + // a directory is removed from the name until either our maximum depth is + // reached or the bitstream is found. Note: an extra pass is added on to the + // loop for a last ditch effort where all directory paths will be removed. + for (int i = 0; i < maxDepthPathSearch+1; i++) + { + // Search through all the bitstreams and see + // if the name can be found + List bundles = item.getBundles(); + for (Bundle bundle : bundles) + { + List bitstreams = bundle.getBitstreams(); - for (Bitstream bitstream : bitstreams) - { - if (name.equals(bitstream.getName())) - { - return bitstream; - } - } - } + for (Bitstream bitstream : bitstreams) + { + if (name.equals(bitstream.getName())) + { + return bitstream; + } + } + } - // The bitstream was not found, so try removing a directory - // off of the name and see if we lost some path information. - int indexOfSlash = name.indexOf('/'); + // The bitstream was not found, so try removing a directory + // off of the name and see if we lost some path information. + int indexOfSlash = name.indexOf('/'); - if (indexOfSlash < 0) + if (indexOfSlash < 0) { // No more directories to remove from the path, so return null for no // bitstream found. return null; } - name = name.substring(indexOfSlash+1); + name = name.substring(indexOfSlash+1); - // If this is our next to last time through the loop then - // trim everything and only use the trailing filename. - if (i == maxDepthPathSearch-1) - { - int indexOfLastSlash = name.lastIndexOf('/'); - if (indexOfLastSlash > -1) + // If this is our next to last time through the loop then + // trim everything and only use the trailing filename. + if (i == maxDepthPathSearch-1) + { + int indexOfLastSlash = name.lastIndexOf('/'); + if (indexOfLastSlash > -1) { name = name.substring(indexOfLastSlash + 1); } - } + } - } + } - // The named bitstream was not found and we exausted the maximum path depth that - // we search. - return null; + // The named bitstream was not found and we exausted the maximum path depth that + // we search. + return null; } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/configuration/XMLUIConfiguration.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/configuration/XMLUIConfiguration.java index b52d421670..ee79c9fdfb 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/configuration/XMLUIConfiguration.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/configuration/XMLUIConfiguration.java @@ -22,7 +22,7 @@ import org.jdom.xpath.XPath; /** * This class reads the XMLUI configuration file. - * + * * @author Scott Phillips */ @@ -31,7 +31,7 @@ public class XMLUIConfiguration /** log4j category */ private static final Logger log = Logger.getLogger(XMLUIConfiguration.class); - + /** The configured Aspects */ private static final List aspects = new ArrayList<>(); @@ -40,12 +40,12 @@ public class XMLUIConfiguration /** * Initialize the XMLUI Configuration. - * - * Load and parse the xmlui.xconf configuration file for a list of - * installed aspects and themes. Multiple configuration paths may be + * + * Load and parse the xmlui.xconf configuration file for a list of + * installed aspects and themes. Multiple configuration paths may be * supplied but only the first valid file (exists and readable) will * be used. - * + * * @param configPaths Multiple configuration paths may be specified. * @throws java.io.IOException if file access fails. * @throws org.jdom.JDOMException if file cannot be parsed. @@ -59,42 +59,42 @@ public class XMLUIConfiguration } File configFile = null; - + for (String configPath : configPaths ) { - if (configPath != null) + if (configPath != null) { configFile = new File(configPath); } - - if (configFile != null && configFile.exists() && configFile.canRead()) - { - log.info("Loading XMLUI configuration from: "+configPath); - break; - } - else - { - log.debug("Failed to load XMLUI configuration from: "+configPath); - } + + if (configFile != null && configFile.exists() && configFile.canRead()) + { + log.info("Loading XMLUI configuration from: "+configPath); + break; + } + else + { + log.debug("Failed to load XMLUI configuration from: "+configPath); + } } - + if (configFile == null) { - StringBuilder allPaths = new StringBuilder(); - for (String configPath : configPaths) - { - if (allPaths.length() > 0) + StringBuilder allPaths = new StringBuilder(); + for (String configPath : configPaths) + { + if (allPaths.length() > 0) { - allPaths.append(", "); + allPaths.append(", "); } - - allPaths.append(configPath); - } - - throw new IllegalStateException("None of the xmlui configuration paths were valid: "+ allPaths); + + allPaths.append(configPath); + } + + throw new IllegalStateException("None of the xmlui configuration paths were valid: "+ allPaths); } - - // FIXME: Sometime in the future require that the xmlui.xconf be valid. + + // FIXME: Sometime in the future require that the xmlui.xconf be valid. // SAXBuilder builder = new SAXBuilder(true); SAXBuilder builder = new SAXBuilder(); Document config = builder.build(configFile); @@ -121,7 +121,7 @@ public class XMLUIConfiguration } // Put them in the order that people expect. Collections.reverse(aspects); - + for (Element themeElement : themeElements) { @@ -141,20 +141,18 @@ public class XMLUIConfiguration } /** - * + * * @return The configured Aspect chain. */ public static List getAspectChain() { return aspects; } - + /** - * + * * @return The configured Theme rules. */ public static List getThemeRules() { return themes; } - - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/AbstractAdapter.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/AbstractAdapter.java index 5e4a7b7a17..1d61c977c3 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/AbstractAdapter.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/AbstractAdapter.java @@ -65,31 +65,31 @@ public abstract class AbstractAdapter public static final String XSI_URI = "http://www.w3.org/2001/XMLSchema-instance"; public static final Namespace XSI = new Namespace(XSI_URI); public static final String DIM_URI = "http://www.dspace.org/xmlns/dspace/dim"; - public static final Namespace DIM = new Namespace(DIM_URI); - + public static final Namespace DIM = new Namespace(DIM_URI); + /** * A sequence used to generate unique mets ids. */ private int idSequence = 0; - + /** * The contextPath of this web application, used for generating URLs. */ protected String contextPath; - + /** - * The SAX handlers for content and lexical events. Also the support - * element for namespaces which knows the prefixes for each declared + * The SAX handlers for content and lexical events. Also the support + * element for namespaces which knows the prefixes for each declared * namespace. */ protected ContentHandler contentHandler; protected LexicalHandler lexicalHandler; protected NamespaceSupport namespaces; - + /** * Construct a new adapter, implementers must call this method so * the appropriate internal values are ensured to be set correctly. - * + * * @param contextPath * The contextPath of this web application. */ @@ -104,45 +104,45 @@ public abstract class AbstractAdapter Map amdTypes = new HashMap<>(); List fileGrpTypes = new ArrayList<>(); List structTypes = new ArrayList<>(); - + /** - * A comma-separated list of METS sections to render. If no value + * A comma-separated list of METS sections to render. If no value * is provided then all METS sections are rendered. - * + * * @param sections Comma separated list of METS sections. */ public final void setSections(String sections) { - if (sections == null) + if (sections == null) { return; } - for (String section : sections.split(",")) - { - this.sections.add(section); - } + for (String section : sections.split(",")) + { + this.sections.add(section); + } } - + /** - * A comma-separated list of METS descriptive metadata formats to + * A comma-separated list of METS descriptive metadata formats to * render. If no value is provided then only the DIM format is used. - * + * * @param dmdTypes Comma separated list of METS metadata types. */ public final void setDmdTypes(String dmdTypes) { - if (dmdTypes == null) + if (dmdTypes == null) { return; } - for (String dmdType : dmdTypes.split(",")) - { - this.dmdTypes.add(dmdType); - } + for (String dmdType : dmdTypes.split(",")) + { + this.dmdTypes.add(dmdType); + } } - + /** * Store information about what will be rendered in the METS administrative * metadata section. HashMap format: keys = amdSec, value = List of mdTypes @@ -153,17 +153,17 @@ public abstract class AbstractAdapter */ public final void setAmdTypes(String amdSec, String mdTypes) { - if (mdTypes == null) + if (mdTypes == null) { return; } List mdTypeList = new ArrayList<>(); - for (String mdType : mdTypes.split(",")) - { - mdTypeList.add(mdType); - } - + for (String mdType : mdTypes.split(",")) + { + mdTypeList.add(mdType); + } + this.amdTypes.put(amdSec, mdTypeList); } @@ -175,7 +175,7 @@ public abstract class AbstractAdapter */ public final void setTechMDTypes(String techMDTypes) { - setAmdTypes("techMD", techMDTypes); + setAmdTypes("techMD", techMDTypes); } /** @@ -186,7 +186,7 @@ public abstract class AbstractAdapter */ public final void setRightsMDTypes(String rightsMDTypes) { - setAmdTypes("rightsMD", rightsMDTypes); + setAmdTypes("rightsMD", rightsMDTypes); } /** @@ -197,7 +197,7 @@ public abstract class AbstractAdapter */ public final void setSourceMDTypes(String sourceMDTypes) { - setAmdTypes("sourceMD", sourceMDTypes); + setAmdTypes("sourceMD", sourceMDTypes); } /** @@ -208,48 +208,48 @@ public abstract class AbstractAdapter */ public final void setDigiProvMDTypes(String digiprovMDTypes) { - setAmdTypes("digiprovMD", digiprovMDTypes); + setAmdTypes("digiprovMD", digiprovMDTypes); } - + /** * A comma-separated list of METS fileGrps to render. If no value * is provided then all groups are rendered. - * + * * @param fileGrpTypes Comma-separated list of METS file groups. */ public final void setFileGrpTypes(String fileGrpTypes) { - if (fileGrpTypes == null) + if (fileGrpTypes == null) { return; } - for (String fileGrpType : fileGrpTypes.split(",")) - { - this.fileGrpTypes.add(fileGrpType); - } + for (String fileGrpType : fileGrpTypes.split(",")) + { + this.fileGrpTypes.add(fileGrpType); + } } - + /** - * A comma-separated list of METS structural types to render. If no + * A comma-separated list of METS structural types to render. If no * value is provided then only the DIM format is used. - * + * * @param structTypes Comma-separated list of METS structure types. */ public final void setStructTypes(String structTypes) { - if (structTypes == null) + if (structTypes == null) { return; } - for (String structType : structTypes.split(",")) - { - this.structTypes.add(structType); - } + for (String structType : structTypes.split(",")) + { + this.structTypes.add(structType); + } } - - + + /** * * @@ -264,8 +264,8 @@ public abstract class AbstractAdapter * * */ - - + + /** * @return the URL for this item in the interface. * @throws org.dspace.app.xmlui.wing.WingException on error. @@ -295,9 +295,9 @@ public abstract class AbstractAdapter */ protected abstract String getMETSLabel() throws WingException; - - /** - * Render the complete METS document. + + /** + * Render the complete METS document. * @param context session context. * @param contentHandler XML content handler. * @param lexicalHandler XML lexical handler. @@ -306,104 +306,102 @@ public abstract class AbstractAdapter * @throws org.dspace.content.crosswalk.CrosswalkException passed through. * @throws java.io.IOException passed through. * @throws java.sql.SQLException passed through. - */ + */ public final void renderMETS(Context context, ContentHandler contentHandler, LexicalHandler lexicalHandler) - throws WingException, SAXException, CrosswalkException, IOException, SQLException + throws WingException, SAXException, CrosswalkException, IOException, SQLException { - this.contentHandler = contentHandler; - this.lexicalHandler = lexicalHandler; - this.namespaces = new NamespaceSupport(); - - - // Declare our namespaces - namespaces.pushContext(); - namespaces.declarePrefix("mets", METS.URI); - namespaces.declarePrefix("xlink", XLINK.URI); - namespaces.declarePrefix("xsi", XSI.URI); - namespaces.declarePrefix("dim", DIM.URI); - contentHandler.startPrefixMapping("mets", METS.URI); - contentHandler.startPrefixMapping("xlink", XLINK.URI); - contentHandler.startPrefixMapping("xsi", XSI.URI); - contentHandler.startPrefixMapping("dim", DIM.URI); - - // Send the METS element - AttributeMap attributes = new AttributeMap(); - attributes.put("ID", getMETSID()); - attributes.put("PROFILE", getMETSProfile()); - attributes.put("LABEL", getMETSLabel()); - String objid = getMETSOBJID(); - if (objid != null) - { - attributes.put("OBJID", objid); - } + this.contentHandler = contentHandler; + this.lexicalHandler = lexicalHandler; + this.namespaces = new NamespaceSupport(); - // Include the link for editing the item - objid = getMETSOBJEDIT(); - if (objid != null) - { - attributes.put("OBJEDIT", objid); - } - startElement(METS,"METS",attributes); + // Declare our namespaces + namespaces.pushContext(); + namespaces.declarePrefix("mets", METS.URI); + namespaces.declarePrefix("xlink", XLINK.URI); + namespaces.declarePrefix("xsi", XSI.URI); + namespaces.declarePrefix("dim", DIM.URI); + contentHandler.startPrefixMapping("mets", METS.URI); + contentHandler.startPrefixMapping("xlink", XLINK.URI); + contentHandler.startPrefixMapping("xsi", XSI.URI); + contentHandler.startPrefixMapping("dim", DIM.URI); - // If the user requested no specific sections then render them all. - boolean all = (sections.isEmpty()); - - if (all || sections.contains("metsHdr")) - { - renderHeader(); - } - if (all || sections.contains("dmdSec")) - { - renderDescriptiveSection(); - } - if (all || sections.contains("amdSec")) - { - renderAdministrativeSection(); - } - if (all || sections.contains("fileSec")) - { - renderFileSection(context); - } - if (all || sections.contains("structMap")) - { - renderStructureMap(); - } - if (all || sections.contains("structLink")) - { - renderStructuralLink(); - } - if (all || sections.contains("behaviorSec")) - { - renderBehavioralSection(); - } - - // FIXME: this is not a met's section, it should be removed - if (all || sections.contains("extraSec")) - { - renderExtraSections(); - } - - endElement(METS,"METS"); - contentHandler.endPrefixMapping("mets"); - contentHandler.endPrefixMapping("xlink"); - contentHandler.endPrefixMapping("dim"); - namespaces.popContext(); + // Send the METS element + AttributeMap attributes = new AttributeMap(); + attributes.put("ID", getMETSID()); + attributes.put("PROFILE", getMETSProfile()); + attributes.put("LABEL", getMETSLabel()); + String objid = getMETSOBJID(); + if (objid != null) + { + attributes.put("OBJID", objid); + } + // Include the link for editing the item + objid = getMETSOBJEDIT(); + if (objid != null) + { + attributes.put("OBJEDIT", objid); + } + + startElement(METS, "METS", attributes); + + // If the user requested no specific sections then render them all. + boolean all = (sections.isEmpty()); + + if (all || sections.contains("metsHdr")) + { + renderHeader(); + } + if (all || sections.contains("dmdSec")) + { + renderDescriptiveSection(); + } + if (all || sections.contains("amdSec")) + { + renderAdministrativeSection(); + } + if (all || sections.contains("fileSec")) + { + renderFileSection(context); + } + if (all || sections.contains("structMap")) + { + renderStructureMap(); + } + if (all || sections.contains("structLink")) + { + renderStructuralLink(); + } + if (all || sections.contains("behaviorSec")) + { + renderBehavioralSection(); + } + + // FIXME: this is not a met's section, it should be removed + if (all || sections.contains("extraSec")) + { + renderExtraSections(); + } + + endElement(METS, "METS"); + contentHandler.endPrefixMapping("mets"); + contentHandler.endPrefixMapping("xlink"); + contentHandler.endPrefixMapping("dim"); + namespaces.popContext(); } - + /* * Each of the METS sections */ - protected void renderHeader() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} - protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} - protected void renderAdministrativeSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} - protected void renderFileSection(Context context) throws WingException, SAXException, CrosswalkException, IOException, SQLException {} - protected void renderStructureMap() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} - protected void renderStructuralLink() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} - protected void renderBehavioralSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} - protected void renderExtraSections() throws WingException, SAXException, CrosswalkException, SQLException, IOException {} - + protected void renderHeader() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} + protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} + protected void renderAdministrativeSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} + protected void renderFileSection(Context context) throws WingException, SAXException, CrosswalkException, IOException, SQLException {} + protected void renderStructureMap() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} + protected void renderStructuralLink() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} + protected void renderBehavioralSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException {} + protected void renderExtraSections() throws WingException, SAXException, CrosswalkException, SQLException, IOException {} /** @@ -424,13 +422,13 @@ public abstract class AbstractAdapter * @throws org.xml.sax.SAXException passed through. * @throws java.sql.SQLException passed through. */ - protected final void renderFile(Context context, Item item, Bitstream bitstream, String fileID, String groupID) + protected final void renderFile(Context context, Item item, Bitstream bitstream, String fileID, String groupID) throws SAXException, SQLException { renderFile(context, item, bitstream, fileID, groupID, null); } - /** + /** * Generate a METS file element for a given bitstream. * * @param context @@ -451,14 +449,14 @@ public abstract class AbstractAdapter * @throws org.xml.sax.SAXException passed through. * @throws java.sql.SQLException passed through. */ - protected final void renderFile(Context context, Item item, + protected final void renderFile(Context context, Item item, Bitstream bitstream, String fileID, String groupID, String admID) throws SAXException, SQLException { - AttributeMap attributes; - - // ////////////////////////////// - // Determine the file attributes + AttributeMap attributes; + + // ////////////////////////////// + // Determine the file attributes BitstreamFormat format = bitstream.getFormat(context); String mimeType = null; if (format != null) @@ -468,12 +466,12 @@ public abstract class AbstractAdapter String checksumType = bitstream.getChecksumAlgorithm(); String checksum = bitstream.getChecksum(); long size = bitstream.getSize(); - + // //////////////////////////////// // Start the actual file attributes = new AttributeMap(); attributes.put("ID", fileID); - attributes.put("GROUPID",groupID); + attributes.put("GROUPID", groupID); if (admID != null && admID.length()>0) { attributes.put("ADMID", admID); @@ -484,19 +482,19 @@ public abstract class AbstractAdapter } if (checksumType != null && checksum != null) { - attributes.put("CHECKSUM", checksum); - attributes.put("CHECKSUMTYPE", checksumType); + attributes.put("CHECKSUM", checksum); + attributes.put("CHECKSUMTYPE", checksumType); } attributes.put("SIZE", String.valueOf(size)); - startElement(METS,"file",attributes); - - + startElement(METS, "file", attributes); + + // //////////////////////////////////// // Determine the file location attributes String name = bitstream.getName(); String description = bitstream.getDescription(); - + // If possible, reference this bitstream via a handle, however this may // be null if a handle has not yet been assigned. In this case reference the // item its internal id. In the last case where the bitstream is not associated @@ -514,14 +512,14 @@ public abstract class AbstractAdapter { identifier = "id/" + bitstream.getID(); } - - + + String url = contextPath + "/bitstream/"+identifier+"/"; - + // If we can, append the pretty name of the bitstream to the URL try { - if (bitstream.getName() != null) + if (bitstream.getName() != null) { url += Util.encodeBitstreamName(bitstream.getName(), "UTF-8"); } @@ -529,90 +527,90 @@ public abstract class AbstractAdapter catch (UnsupportedEncodingException uee) { // just ignore it, we don't have to have a pretty - // name at the end of the URL because the sequence id will - // locate it. However it means that links in this file might - // not work.... + // name at the end of the URL because the sequence id will + // locate it. However it means that links in this file might + // not work.... } - + url += "?sequence="+bitstream.getSequenceID(); - - + + // ////////////////////// // Start the file location attributes = new AttributeMap(); AttributeMap attributesXLINK = new AttributeMap(); attributesXLINK.setNamespace(XLINK); attributes.put("LOCTYPE", "URL"); - attributesXLINK.put("type","locator"); + attributesXLINK.put("type", "locator"); attributesXLINK.put("title", name); if (description != null) { attributesXLINK.put("label", description); } attributesXLINK.put("href", url); - startElement(METS,"FLocat",attributes,attributesXLINK); - + startElement(METS, "FLocat", attributes, attributesXLINK); + // /////////////////////// // End file location - endElement(METS,"FLocate"); - + endElement(METS, "FLocate"); + // //////////////////////////////// // End the file - endElement(METS,"file"); - } - - - /** - * + endElement(METS, "file"); + } + + + /** + * * Generate a unique METS id. For consistency, all prefixes should probably * end in an underscore, "_". - * + * * @param prefix * Prefix to prepend to the id for readability. - * + * * @return A unique METS id. */ protected final String getGenericID(String prefix) { return prefix + (idSequence++); } - + /** * Return a dissemination crosswalk for the given name. - * + * * @param crosswalkName name of crosswalk plugin to be looked up. * @return The crosswalk. * @throws org.dspace.app.xmlui.wing.WingException if crosswalk not found. */ - public final DisseminationCrosswalk getDisseminationCrosswalk(String crosswalkName) throws WingException + public final DisseminationCrosswalk getDisseminationCrosswalk(String crosswalkName) throws WingException { - // FIXME add some caching here - DisseminationCrosswalk crosswalk - = (DisseminationCrosswalk) CoreServiceFactory.getInstance() - .getPluginService() - .getNamedPlugin(DisseminationCrosswalk.class, crosswalkName); + // FIXME add some caching here + DisseminationCrosswalk crosswalk + = (DisseminationCrosswalk) CoreServiceFactory.getInstance() + .getPluginService() + .getNamedPlugin(DisseminationCrosswalk.class, crosswalkName); - if (crosswalk == null) + if (crosswalk == null) { throw new WingException("Unable to find named DisseminationCrosswalk: " + crosswalkName); } - - return crosswalk; + + return crosswalk; } - - /** - * The METS defined types of Metadata, if a format is not listed here - * then it should use the string "OTHER" and provide additional - * attributes describing the metadata type + + /** + * The METS defined types of Metadata, if a format is not listed here + * then it should use the string "OTHER" and provide additional + * attributes describing the metadata type */ - public static final String[] METS_DEFINED_TYPES = - {"MARC","MODS","EAD","DC","NISOIMG","LC-AV","VRA","TEIHDR","DDI","FGDC","PREMIS"/*,"OTHER"*/}; - + public static final String[] METS_DEFINED_TYPES = + {"MARC", "MODS", "EAD", "DC", "NISOIMG", "LC-AV", "VRA", "TEIHDR", "DDI", "FGDC", "PREMIS"/*, "OTHER"*/}; + /** * Determine if the provided metadata type is a standard METS * defined type. If it is not, use the other string. - * + * * @param metadataType type name * @return True if METS defined */ @@ -627,23 +625,23 @@ public abstract class AbstractAdapter } return false; } - - - - - + + + + + /** - * - * - * SAX Helper methods - * - * - * - */ - - /** - * Send the SAX events to start this element. * + * + * SAX Helper methods + * + * + * + */ + + /** + * Send the SAX events to start this element. + * * @param namespace * (Required) The namespace of this element. * @param name @@ -656,13 +654,13 @@ public abstract class AbstractAdapter AttributeMap... attributes) throws SAXException { contentHandler.startElement(namespace.URI, name, qName(namespace, name), - map2sax(namespace,attributes)); + map2sax(namespace, attributes)); } /** * Send the SAX event for these plain characters, not wrapped in any * elements. - * + * * @param characters * (May be null) Characters to send. * @throws org.xml.sax.SAXException passed through. @@ -675,10 +673,10 @@ public abstract class AbstractAdapter contentHandler.characters(contentArray, 0, contentArray.length); } } - + /** * Send the SAX events to end this element. - * + * * @param namespace * (Required) The namespace of this element. * @param name @@ -695,7 +693,7 @@ public abstract class AbstractAdapter * Build the SAX attributes object based upon Java's String map. This * convenience method will build, or add to an existing attributes object, * the attributes detailed in the AttributeMap. - * + * * @param elementNamespace * SAX Helper class to keep track of namespaces able to determine * the correct prefix for a given namespace URI. @@ -732,7 +730,6 @@ public abstract class AbstractAdapter { attributes.addAttribute(attributeNamespace.URI, attr.getKey(), qName(attributeNamespace, attr.getKey()), "CDATA", attr.getValue()); - } else { @@ -742,11 +739,11 @@ public abstract class AbstractAdapter } return attributes; } - + /** * Create the qName for the element with the given localName and namespace * prefix. - * + * * @param namespace * (May be null) The namespace prefix. * @param localName @@ -755,7 +752,7 @@ public abstract class AbstractAdapter */ private String qName(Namespace namespace, String localName) { - String prefix = namespaces.getPrefix(namespace.URI); + String prefix = namespaces.getPrefix(namespace.URI); if (prefix == null || prefix.equals("")) { return localName; @@ -765,5 +762,4 @@ public abstract class AbstractAdapter return prefix + ":" + localName; } } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java index 8e84ccf59b..808549f6e3 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ContainerAdapter.java @@ -37,21 +37,21 @@ import org.jdom.output.SAXOutputter; import org.xml.sax.SAXException; /** - * This is an adapter which translates DSpace containers + * This is an adapter which translates DSpace containers * (communities and collections) into METS documents. This adapter follows * the DSpace METS profile, however that profile does not define how a - * community or collection should be described, but we make the obvious + * community or collection should be described, but we make the obvious * decisions to deviate when necessary from the profile. - * + * * The METS document consists of three parts: descriptive metadata section, * file section, and a structural map. The descriptive metadata sections holds - * metadata about the item being adapted using DSpace crosswalks. This is the + * metadata about the item being adapted using DSpace crosswalks. This is the * same way the item adapter works. - * + * * However, the file section and structural map are a bit different. In these - * cases the the only files listed is the one logo that may be attached to + * cases the the only files listed is the one logo that may be attached to * a community or collection. - * + * * @author Scott Phillips */ public class ContainerAdapter extends AbstractAdapter @@ -63,24 +63,24 @@ public class ContainerAdapter extends AbstractAdapter /** A space-separated list of descriptive metadata sections */ private StringBuffer dmdSecIDS; - + /** Current DSpace context **/ private final Context dspaceContext; protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); - protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); - - + protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + + /** * Construct a new CommunityCollectionMETSAdapter. - * + * * @param context session context. * @param dso * A DSpace Community or Collection to adapt. * @param contextPath * The contextPath of this webapplication. */ - public ContainerAdapter(Context context, DSpaceObject dso,String contextPath) + public ContainerAdapter(Context context, DSpaceObject dso, String contextPath) { super(contextPath); this.dso = dso; @@ -92,9 +92,9 @@ public class ContainerAdapter extends AbstractAdapter */ public DSpaceObject getContainer() { - return this.dso; + return this.dso; } - + /** * * @@ -104,18 +104,18 @@ public class ContainerAdapter extends AbstractAdapter * * */ - + /** * @return the URL of this community/collection in the interface. */ @Override protected String getMETSOBJID() { - if (dso.getHandle() != null) + if (dso.getHandle() != null) { return contextPath + "/handle/" + dso.getHandle(); } - return null; + return null; } /** @@ -126,7 +126,7 @@ public class ContainerAdapter extends AbstractAdapter { return null; } - + /** * Use the handle as the id for this METS document. * @return the id. @@ -134,17 +134,17 @@ public class ContainerAdapter extends AbstractAdapter @Override protected String getMETSID() { - if (dso.getHandle() == null) - { - if (dso instanceof Collection) + if (dso.getHandle() == null) + { + if (dso instanceof Collection) { return "collection:" + dso.getID(); } - else + else { return "community:" + dso.getID(); } - } + } else { return "hdl:" + dso.getHandle(); @@ -153,14 +153,14 @@ public class ContainerAdapter extends AbstractAdapter /** * Return the profile to use for communities and collections. - * + * * @return the constant profile name. * @throws org.dspace.app.xmlui.wing.WingException never. */ @Override protected String getMETSProfile() throws WingException { - return "DSPACE METS SIP Profile 1.0"; + return "DSPACE METS SIP Profile 1.0"; } /** @@ -199,8 +199,8 @@ public class ContainerAdapter extends AbstractAdapter } - - + + /** * * @@ -211,12 +211,12 @@ public class ContainerAdapter extends AbstractAdapter * */ - - + + /** * Render the METS descriptive section. This will create a new metadata * section for each crosswalk configured. - * + * *

    Example: * *

    {@code
    @@ -235,55 +235,56 @@ public class ContainerAdapter extends AbstractAdapter
          * @throws java.sql.SQLException passed through.
          */
         @Override
    -    protected void renderDescriptiveSection() throws WingException, SAXException, CrosswalkException, IOException, SQLException 
    +    protected void renderDescriptiveSection()
    +        throws WingException, SAXException, CrosswalkException, IOException, SQLException
         {
             AttributeMap attributes;
    -        
    +
             String groupID = getGenericID("group_dmd_");
             dmdSecIDS = new StringBuffer();
     
    -        // Add DIM descriptive metadata if it was requested or if no metadata types 
    -        // were specified. Furthermore, since this is the default type we also use a 
    +        // Add DIM descriptive metadata if it was requested or if no metadata types
    +        // were specified. Furthermore, since this is the default type we also use a
             // faster rendering method that the crosswalk API.
    -        if(dmdTypes.isEmpty() || dmdTypes.contains("DIM"))
    +        if (dmdTypes.isEmpty() || dmdTypes.contains("DIM"))
             {
                 // Metadata element's ID
                 String dmdID = getGenericID("dmd_");
    -            
    +
                 // Keep track of all descriptive sections
                 dmdSecIDS.append(dmdID);
    -            
    -            
    +
    +
                 // ////////////////////////////////
                 // Start a new dmdSec for each crosswalk.
                 attributes = new AttributeMap();
                 attributes.put("ID", dmdID);
                 attributes.put("GROUPID", groupID);
    -            startElement(METS,"dmdSec",attributes);
    -            
    +            startElement(METS, "dmdSec", attributes);
    +
                 // ////////////////////////////////
                 // Start metadata wrapper
                 attributes = new AttributeMap();
                 attributes.put("MDTYPE", "OTHER");
                 attributes.put("OTHERMDTYPE", "DIM");
    -            startElement(METS,"mdWrap",attributes);
    +            startElement(METS, "mdWrap", attributes);
     
                 // ////////////////////////////////
                 // Start the xml data
    -            startElement(METS,"xmlData");
    -            
    -            
    +            startElement(METS, "xmlData");
    +
    +
                 // ///////////////////////////////
                 // Start the DIM element
                 attributes = new AttributeMap();
                 attributes.put("dspaceType", Constants.typeText[dso.getType()]);
    -            startElement(DIM,"dim",attributes);
    +            startElement(DIM, "dim", attributes);
     
                 // Add each field for this collection
    -            if (dso.getType() == Constants.COLLECTION) 
    +            if (dso.getType() == Constants.COLLECTION)
                 {
                     Collection collection = (Collection) dso;
    -                
    +
                     String description = collectionService.getMetadata(collection, "introductory_text");
                     String description_abstract = collectionService.getMetadata(collection, "short_description");
                     String description_table = collectionService.getMetadata(collection, "side_bar_text");
    @@ -292,57 +293,57 @@ public class ContainerAdapter extends AbstractAdapter
                     String rights = collectionService.getMetadata(collection, "copyright_text");
                     String rights_license = collectionService.getMetadata(collection, "license");
                     String title = collectionService.getMetadata(collection, "name");
    -                
    -                createField("dc","description",null,null,description);
    -                createField("dc","description","abstract",null,description_abstract);
    -                createField("dc","description","tableofcontents",null,description_table);
    -                createField("dc","identifier","uri",null,identifier_uri);
    -                createField("dc","provenance",null,null,provenance);
    -                createField("dc","rights",null,null,rights);
    -                createField("dc","rights","license",null,rights_license);
    -                createField("dc","title",null,null,title);
    -                
    +
    +                createField("dc", "description", null, null, description);
    +                createField("dc", "description", "abstract", null, description_abstract);
    +                createField("dc", "description", "tableofcontents", null, description_table);
    +                createField("dc", "identifier", "uri", null, identifier_uri);
    +                createField("dc", "provenance", null, null, provenance);
    +                createField("dc", "rights", null, null, rights);
    +                createField("dc", "rights", "license", null, rights_license);
    +                createField("dc", "title", null, null, title);
    +
                     boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    -                 
    +
                     if (showCount)
                     {
                         try
    -                    {	// try to determine Collection size (i.e. # of items)
    +                    {    // try to determine Collection size (i.e. # of items)
                             int size = new ItemCounter(this.dspaceContext).getCount(collection);
    -                        createField("dc","format","extent",null, String.valueOf(size)); 
    +                        createField("dc", "format", "extent", null, String.valueOf(size));
                         }
                         catch (ItemCountException e)
                         {
                             throw new IOException("Could not obtain Collection item count", e);
                         }
                     }
    -            } 
    -            else if (dso.getType() == Constants.COMMUNITY) 
    +            }
    +            else if (dso.getType() == Constants.COMMUNITY)
                 {
                     Community community = (Community) dso;
    -                
    +
                     String description = communityService.getMetadata(community, "introductory_text");
                     String description_abstract = communityService.getMetadata(community, "short_description");
                     String description_table = communityService.getMetadata(community, "side_bar_text");
                     String identifier_uri = "http://hdl.handle.net/" + community.getHandle();
                     String rights = communityService.getMetadata(community, "copyright_text");
                     String title = communityService.getMetadata(community, "name");
    -                
    -                createField("dc","description",null,null,description);
    -                createField("dc","description","abstract",null,description_abstract);
    -                createField("dc","description","tableofcontents",null,description_table);
    -                createField("dc","identifier","uri",null,identifier_uri);
    -                createField("dc","rights",null,null,rights);
    -                createField("dc","title",null,null,title);
    -                
    +
    +                createField("dc", "description", null, null, description);
    +                createField("dc", "description", "abstract", null, description_abstract);
    +                createField("dc", "description", "tableofcontents", null, description_table);
    +                createField("dc", "identifier", "uri", null, identifier_uri);
    +                createField("dc", "rights", null, null, rights);
    +                createField("dc", "title", null, null, title);
    +
                     boolean showCount = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.strengths.show");
    -        		
    +
                     if (showCount)
                     {
                         try
    -                    {	// try to determine Community size (i.e. # of items)
    +                    {   // try to determine Community size (i.e. # of items)
                             int size = new ItemCounter(this.dspaceContext).getCount(community);
    -                        createField("dc","format","extent",null, String.valueOf(size)); 
    +                        createField("dc", "format", "extent", null, String.valueOf(size));
                         }
                         catch (ItemCountException e)
                         {
    @@ -350,37 +351,37 @@ public class ContainerAdapter extends AbstractAdapter
                         }
                     }
                 }
    -            
    +
                 // ///////////////////////////////
                 // End the DIM element
    -            endElement(DIM,"dim");
    -            
    +            endElement(DIM, "dim");
    +
                 // ////////////////////////////////
                 // End elements
    -            endElement(METS,"xmlData");
    -            endElement(METS,"mdWrap");
    +            endElement(METS, "xmlData");
    +            endElement(METS, "mdWrap");
                 endElement(METS, "dmdSec");
    -          
    +
             }
    -        
    -    	for (String dmdType : dmdTypes)
    -    	{
    -    		// If DIM was requested then it was generated above without using
    -    		// the crosswalk API. So we can skip this one.
    -    		if ("DIM".equals(dmdType))
    +
    +        for (String dmdType : dmdTypes)
    +        {
    +            // If DIM was requested then it was generated above without using
    +            // the crosswalk API. So we can skip this one.
    +            if ("DIM".equals(dmdType))
                 {
                     continue;
                 }
    -    		
    -    		DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType);
    -    		
    -    		if (crosswalk == null)
    +
    +            DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType);
    +
    +            if (crosswalk == null)
                 {
                     continue;
                 }
    -    		
    -        	String dmdID = getGenericID("dmd_");
    -	   		// Add our id to the list.
    +
    +            String dmdID = getGenericID("dmd_");
    +            // Add our id to the list.
                 dmdSecIDS.append(" ").append(dmdID);
     
                 // ////////////////////////////////
    @@ -388,58 +389,58 @@ public class ContainerAdapter extends AbstractAdapter
                 attributes = new AttributeMap();
                 attributes.put("ID", dmdID);
                 attributes.put("GROUPID", groupID);
    -            startElement(METS,"dmdSec",attributes);
    -            
    +            startElement(METS, "dmdSec", attributes);
    +
                 // ////////////////////////////////
                 // Start metadata wrapper
                 attributes = new AttributeMap();
                 if (isDefinedMETStype(dmdType))
                 {
    -            	attributes.put("MDTYPE", dmdType);
    +                attributes.put("MDTYPE", dmdType);
                 }
                 else
                 {
    -            	attributes.put("MDTYPE", "OTHER");
    -            	attributes.put("OTHERMDTYPE", dmdType);
    +                attributes.put("MDTYPE", "OTHER");
    +                attributes.put("OTHERMDTYPE", dmdType);
                 }
    -            startElement(METS,"mdWrap",attributes);
    +            startElement(METS, "mdWrap", attributes);
     
                 // ////////////////////////////////
                 // Start the xml data
    -            startElement(METS,"xmlData");
    -            
    +            startElement(METS, "xmlData");
    +
                 // ///////////////////////////////
                 // Send the actual XML content
                 try {
    -	    		Element dissemination = crosswalk.disseminateElement(dspaceContext, dso);
    -	
    -	    		SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
    -	    		// Allow the basics for XML
    -	    		filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
    -	    		
    -	            SAXOutputter outputter = new SAXOutputter();
    -	            outputter.setContentHandler(filter);
    -	            outputter.setLexicalHandler(filter);
    -				outputter.output(dissemination);
    -			} 
    -            catch (JDOMException jdome) 
    -			{
    -				throw new WingException(jdome);
    -			}
    -			catch (AuthorizeException ae)
    -			{
    -				// just ignore the authorize exception and continue on
    -				// without parsing the xml document.
    -			}
    -    		
    -            
    +                Element dissemination = crosswalk.disseminateElement(dspaceContext, dso);
    +
    +                SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
    +                // Allow the basics for XML
    +                filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
    +
    +                SAXOutputter outputter = new SAXOutputter();
    +                outputter.setContentHandler(filter);
    +                outputter.setLexicalHandler(filter);
    +                outputter.output(dissemination);
    +            }
    +            catch (JDOMException jdome)
    +            {
    +                throw new WingException(jdome);
    +            }
    +            catch (AuthorizeException ae)
    +            {
    +                // just ignore the authorize exception and continue on
    +                // without parsing the xml document.
    +            }
    +
    +
                 // ////////////////////////////////
                 // End elements
    -            endElement(METS,"xmlData");
    -            endElement(METS,"mdWrap");
    +            endElement(METS, "xmlData");
    +            endElement(METS, "mdWrap");
                 endElement(METS, "dmdSec");
    -            
    -            
    +
    +
                 // Record keeping
                 if (dmdSecIDS == null)
                 {
    @@ -448,14 +449,13 @@ public class ContainerAdapter extends AbstractAdapter
                 else
                 {
                     dmdSecIDS.append(" ").append(dmdID);
    -
                 }
             }
         }
     
         /**
          * Render the METS file section. If a logo is present for this
    -     * container then that single bitstream is listed in the 
    +     * container then that single bitstream is listed in the
          * file section.
          *
          * 

    Example: @@ -474,10 +474,11 @@ public class ContainerAdapter extends AbstractAdapter * @throws java.sql.SQLException passed through. */ @Override - protected void renderFileSection(Context context) throws SAXException, SQLException + protected void renderFileSection(Context context) + throws SAXException, SQLException { - AttributeMap attributes; - + AttributeMap attributes; + // Get the Community or Collection logo. Bitstream logo = getLogo(); @@ -485,32 +486,32 @@ public class ContainerAdapter extends AbstractAdapter { // //////////////////////////////// // Start the file section - startElement(METS,"fileSec"); + startElement(METS, "fileSec"); // //////////////////////////////// // Start a new fileGrp for the logo. attributes = new AttributeMap(); attributes.put("USE", "LOGO"); - startElement(METS,"fileGrp",attributes); - + startElement(METS, "fileGrp", attributes); + // //////////////////////////////// // Add the actual file element String fileID = getFileID(logo); String groupID = getGroupFileID(logo); renderFile(context, null, logo, fileID, groupID); - + // //////////////////////////////// // End th file group and file section - endElement(METS,"fileGrp"); - endElement(METS,"fileSec"); + endElement(METS, "fileGrp"); + endElement(METS, "fileSec"); } } /** * Render the container's structural map. This includes a reference - * to the container's logo, if available, otherwise it is an empty + * to the container's logo, if available, otherwise it is an empty * division that just states it is a DSpace community or Collection. - * + * *

    Example: * *

    {@code
    @@ -524,69 +525,70 @@ public class ContainerAdapter extends AbstractAdapter
          * @throws org.xml.sax.SAXException passed through.
          */
         @Override
    -    protected void renderStructureMap() throws SQLException, SAXException
    +    protected void renderStructureMap()
    +        throws SQLException, SAXException
         {
    -    	AttributeMap attributes;
    -    	
    -    	// ///////////////////////
    -    	// Start a new structure map
    -    	attributes = new AttributeMap();
    -    	attributes.put("TYPE", "LOGICAL");
    -    	attributes.put("LABEL", "DSpace");
    -    	startElement(METS,"structMap",attributes);
    +        AttributeMap attributes;
     
    -    	// ////////////////////////////////
    -    	// Start the special first division
    -    	attributes = new AttributeMap();
    -    	attributes.put("TYPE", getMETSLabel());
    -    	// add references to the Descriptive metadata
    -    	if (dmdSecIDS != null)
    +        // ///////////////////////
    +        // Start a new structure map
    +        attributes = new AttributeMap();
    +        attributes.put("TYPE", "LOGICAL");
    +        attributes.put("LABEL", "DSpace");
    +        startElement(METS, "structMap", attributes);
    +
    +        // ////////////////////////////////
    +        // Start the special first division
    +        attributes = new AttributeMap();
    +        attributes.put("TYPE", getMETSLabel());
    +        // add references to the Descriptive metadata
    +        if (dmdSecIDS != null)
             {
                 attributes.put("DMDID", dmdSecIDS.toString());
             }
    -    	startElement(METS,"div",attributes);
    -    	
    -    	
    -    	// add a fptr pointer to the logo.
    +        startElement(METS, "div", attributes);
    +
    +
    +        // add a fptr pointer to the logo.
             Bitstream logo = getLogo();
             if (logo != null)
             {
                 // ////////////////////////////////
                 // Add a reference to the logo as the primary bitstream.
                 attributes = new AttributeMap();
    -            attributes.put("FILEID",getFileID(logo));
    -            startElement(METS,"fptr",attributes);
    -            endElement(METS,"fptr");
    -        
    -            
    +            attributes.put("FILEID", getFileID(logo));
    +            startElement(METS, "fptr", attributes);
    +            endElement(METS, "fptr");
    +
    +
                 // ///////////////////////////////////////////////
                 // Add a div for the publicly viewable bitstreams (i.e. the logo)
                 attributes = new AttributeMap();
                 attributes.put("ID", getGenericID("div_"));
                 attributes.put("TYPE", "DSpace Content Bitstream");
    -            startElement(METS,"div",attributes);
    -        	
    +            startElement(METS, "div", attributes);
    +
                 // ////////////////////////////////
                 // Add a reference to the logo as the primary bitstream.
                 attributes = new AttributeMap();
    -            attributes.put("FILEID",getFileID(logo));
    -            startElement(METS,"fptr",attributes);
    -            endElement(METS,"fptr");
    -        	
    +            attributes.put("FILEID", getFileID(logo));
    +            startElement(METS, "fptr", attributes);
    +            endElement(METS, "fptr");
    +
                 // //////////////////////////
                 // End the logo division
    -            endElement(METS,"div");
    +            endElement(METS, "div");
             }
     
    -    	// ////////////////////////////////
    -    	// End the special first division
    -    	endElement(METS,"div");
    -    	
    -    	// ///////////////////////
    -    	// End the structure map
    -    	endElement(METS,"structMap");
    +        // ////////////////////////////////
    +        // End the special first division
    +        endElement(METS, "div");
    +
    +        // ///////////////////////
    +        // End the structure map
    +        endElement(METS, "structMap");
         }
    -    
    +
     
         /**
          * 
    @@ -617,43 +619,43 @@ public class ContainerAdapter extends AbstractAdapter
             }
             return null;
         }
    -    
    +
         /**
          * Count how many occurrence there is of the given
          * character in the given string.
    -     * 
    +     *
          * @param string The string value to be counted.
          * @param character the character to count in the string.
          */
         private int countOccurences(String string, char character)
         {
    -    	if (string == null || string.length() == 0)
    +        if (string == null || string.length() == 0)
             {
                 return 0;
             }
    -    	
    -    	int fromIndex = -1;
    +
    +        int fromIndex = -1;
             int count = 0;
    -        
    +
             while (true)
             {
    -        	fromIndex = string.indexOf('>', fromIndex+1);
    -        	
    -        	if (fromIndex == -1)
    +            fromIndex = string.indexOf('>', fromIndex+1);
    +
    +            if (fromIndex == -1)
                 {
                     break;
                 }
    -        	
    -        	count++;
    +
    +            count++;
             }
    -        
    +
             return count;
         }
    -    
    +
         /**
          * Check if the given character sequence is located in the given
          * string at the specified index. If it is then return true, otherwise false.
    -     * 
    +     *
          * @param string The string to test against
          * @param index The location within the string
          * @param characters The character sequence to look for.
    @@ -661,160 +663,160 @@ public class ContainerAdapter extends AbstractAdapter
          */
         private boolean substringCompare(String string, int index, char ... characters)
         {
    -    	// Is the string long enough?
    -    	if (string.length() <= index + characters.length)
    +        // Is the string long enough?
    +        if (string.length() <= index + characters.length)
             {
                 return false;
             }
    -    	
    -    	// Do all the characters match?
    -    	for (char character : characters)
    -    	{
    -    		if (string.charAt(index) != character)
    +
    +        // Do all the characters match?
    +        for (char character : characters)
    +        {
    +            if (string.charAt(index) != character)
                 {
                     return false;
                 }
    -    		index++;
    -    	}
    -    	
    -    	return false;
    +            index++;
    +        }
    +
    +        return false;
         }
    -    
    +
         /**
          * Create a new DIM field element with the given attributes.
    -     * 
    +     *
          * @param schema The schema the DIM field belongs too.
          * @param element The element the DIM field belongs too.
          * @param qualifier The qualifier the DIM field belongs too.
          * @param language The language the DIM field belongs too.
          * @param value The value of the DIM field.
          * @return A new DIM field element
    -     * @throws SAXException 
    +     * @throws SAXException
          */
         private void createField(String schema, String element, String qualifier, String language, String value) throws SAXException
         {
    -    	// ///////////////////////////////
    -    	// Field element for each metadata field.
    -    	AttributeMap attributes = new AttributeMap();
    -		attributes.put("mdschema",schema);
    -		attributes.put("element", element);
    -		if (qualifier != null)
    +        // ///////////////////////////////
    +        // Field element for each metadata field.
    +        AttributeMap attributes = new AttributeMap();
    +        attributes.put("mdschema", schema);
    +        attributes.put("element", element);
    +        if (qualifier != null)
             {
                 attributes.put("qualifier", qualifier);
             }
    -		if (language != null)
    +        if (language != null)
             {
                 attributes.put("language", language);
             }
    -		startElement(DIM,"field",attributes);
    -		
    -		// Only try and add the metadata value, but only if it is non-null.
    -    	if (value != null)
    -    	{
    -    		// First, perform a quick check to see if the value may be XML.
    -	        int countOpen = countOccurences(value,'<');
    -	        int countClose = countOccurences(value, '>');
    -	        
    -	        // If it passed the quick test, then try and parse the value.
    -	        Element xmlDocument = null;
    -	        if (countOpen > 0 && countOpen == countClose)
    -	        {
    -	        	// This may be XML, First try and remove any bad entity references.
    -	        	int amp = -1;
    -	        	while ((amp = value.indexOf('&', amp+1)) > -1)
    -	        	{
    -	        		// Is it an xml entity named by number?
    -	        		if (substringCompare(value,amp+1,'#'))
    -                    {
    -                        continue;
    -                    }
    -	        		
    -	        		// &
    -	        		if (substringCompare(value,amp+1,'a','m','p',';'))
    -                    {
    -                        continue;
    -                    }
    -	        		
    -	        		// '
    -	        		if (substringCompare(value,amp+1,'a','p','o','s',';'))
    -                    {
    -                        continue;
    -                    }
    -	        		
    -	        		// "
    -	        		if (substringCompare(value,amp+1,'q','u','o','t',';'))
    -                    {
    -                        continue;
    -                    }
    -	        			
    -	        		// <
    -	        		if (substringCompare(value,amp+1,'l','t',';'))
    -                    {
    -                        continue;
    -                    }
    -	        		
    -	        		// >
    -	        		if (substringCompare(value,amp+1,'g','t',';'))
    -                    {
    -                        continue;
    -                    }
    -	        		
    -	        		// Replace the ampersand with an XML entity.
    -	        		value = value.substring(0,amp) + "&" + value.substring(amp+1);
    -	        	}
    -	        	
    -	        	
    -	        	// Second try and parse the XML into a mini-dom
    -	        	try {
    -	        		// Wrap the value inside a root element (which will be trimed out 
    -	        		// by the SAX filter and set the default namespace to XHTML. 
    -		        	String xml = ""+value+"";
    +        startElement(DIM, "field", attributes);
     
    -		            ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    -		     	   
    -			 	    SAXBuilder builder = new SAXBuilder();
    -					Document document = builder.build(inputStream);
    -					
    -					xmlDocument = document.getRootElement();
    -	        	} 
    -	        	catch (JDOMException | IOException e)
    -				{
    +        // Only try and add the metadata value, but only if it is non-null.
    +        if (value != null)
    +        {
    +            // First, perform a quick check to see if the value may be XML.
    +            int countOpen = countOccurences(value, '<');
    +            int countClose = countOccurences(value, '>');
    +
    +            // If it passed the quick test, then try and parse the value.
    +            Element xmlDocument = null;
    +            if (countOpen > 0 && countOpen == countClose)
    +            {
    +                // This may be XML, First try and remove any bad entity references.
    +                int amp = -1;
    +                while ((amp = value.indexOf('&', amp+1)) > -1)
    +                {
    +                    // Is it an xml entity named by number?
    +                    if (substringCompare(value, amp+1, '#'))
    +                    {
    +                        continue;
    +                    }
    +
    +                    // &
    +                    if (substringCompare(value, amp+1, 'a', 'm', 'p', ';'))
    +                    {
    +                        continue;
    +                    }
    +
    +                    // '
    +                    if (substringCompare(value, amp+1, 'a', 'p', 'o', 's', ';'))
    +                    {
    +                        continue;
    +                    }
    +
    +                    // "
    +                    if (substringCompare(value, amp+1, 'q', 'u', 'o', 't', ';'))
    +                    {
    +                        continue;
    +                    }
    +
    +                    // <
    +                    if (substringCompare(value, amp+1, 'l', 't', ';'))
    +                    {
    +                        continue;
    +                    }
    +
    +                    // >
    +                    if (substringCompare(value, amp+1, 'g', 't', ';'))
    +                    {
    +                        continue;
    +                    }
    +
    +                    // Replace the ampersand with an XML entity.
    +                    value = value.substring(0, amp) + "&" + value.substring(amp+1);
    +                }
    +
    +
    +                // Second try and parse the XML into a mini-dom
    +                try {
    +                    // Wrap the value inside a root element (which will be trimed out
    +                    // by the SAX filter and set the default namespace to XHTML.
    +                    String xml = ""+value+"";
    +
    +                    ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    +
    +                     SAXBuilder builder = new SAXBuilder();
    +                    Document document = builder.build(inputStream);
    +
    +                    xmlDocument = document.getRootElement();
    +                }
    +                catch (JDOMException | IOException e)
    +                {
                         log.trace("Caught exception", e);
    -				}
    -	        }		
    -					
    -	        // Third, If we have xml, attempt to serialize the dom.
    -	        if (xmlDocument != null)
    -	        {	
    -	        	SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
    -	    		// Allow the basics for XML
    -	    		filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
    -	    		// Special option, only allow elements below the second level to pass through. This
    -	    		// will trim out the METS declaration and only leave the actual METS parts to be
    -	    		// included.
    -	    		filter.allowElements(1);
    -	    		
    -	            SAXOutputter outputter = new SAXOutputter();
    -	            outputter.setContentHandler(filter);
    -	            outputter.setLexicalHandler(filter);
    -	            try {
    -	            	outputter.output(xmlDocument);
    -	            } 
    -	            catch (JDOMException jdome)
    -	            {
    -	            	// serialization failed so let's just fallback sending the plain characters.
    -	            	sendCharacters(value);
    -	            }
    -	        }
    -	        else
    -	        {
    -	        	// We don't have XML, so just send the plain old characters.
    -	        	sendCharacters(value);
    -	        }
    -    	}
    -        
    +                }
    +            }
    +
    +            // Third, If we have xml, attempt to serialize the dom.
    +            if (xmlDocument != null)
    +            {
    +                SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces);
    +                // Allow the basics for XML
    +                filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings();
    +                // Special option, only allow elements below the second level to pass through. This
    +                // will trim out the METS declaration and only leave the actual METS parts to be
    +                // included.
    +                filter.allowElements(1);
    +
    +                SAXOutputter outputter = new SAXOutputter();
    +                outputter.setContentHandler(filter);
    +                outputter.setLexicalHandler(filter);
    +                try {
    +                    outputter.output(xmlDocument);
    +                }
    +                catch (JDOMException jdome)
    +                {
    +                    // serialization failed so let's just fallback sending the plain characters.
    +                    sendCharacters(value);
    +                }
    +            }
    +            else
    +            {
    +                // We don't have XML, so just send the plain old characters.
    +                sendCharacters(value);
    +            }
    +        }
    +
             // //////////////////////////////
             // Close out field
    -        endElement(DIM,"field");
    -    }  
    +        endElement(DIM, "field");
    +    }
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/DSpaceObjectManager.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/DSpaceObjectManager.java
    index ae7e69a1d5..25066f70b0 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/DSpaceObjectManager.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/DSpaceObjectManager.java
    @@ -31,7 +31,7 @@ import org.dspace.handle.service.HandleService;
     public class DSpaceObjectManager implements ObjectManager
     {
     
    -	protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
    +    protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
     
         /**
          * Manage the given object, if this manager is unable to manage the object then false must be returned.
    @@ -43,107 +43,107 @@ public class DSpaceObjectManager implements ObjectManager
         @Override
         public boolean manageObject(Object object)
         {
    -    	// Check that the object is of a type we can manage.
    -    	return (object instanceof Item) || (object instanceof Collection)
    -			    || (object instanceof Community);
    +        // Check that the object is of a type we can manage.
    +        return (object instanceof Item) || (object instanceof Collection)
    +                || (object instanceof Community);
         }
    -	
    -	
    +    
    +    
         /**
          * Return the metadata URL of the supplied object, assuming 
          * it's a DSpace item, community or collection.
          */
         @Override
    -	public String getObjectURL(Object object) throws WingException 
    -	{
    -		if (object instanceof DSpaceObject)
    -		{
    -			DSpaceObject dso = (DSpaceObject) object;
    -			String handle = dso.getHandle();
    -			
    -			// If the object has a handle then reference it by its handle.
    -			if (handle != null)
    -			{
    -				return "/metadata/handle/" + handle + "/mets.xml";
    -			}
    -			else
    -			{
    -				// No handle then reference it by an internal ID.
    -				if (dso instanceof Item)
    -		    	{
    -		    		return "/metadata/internal/item/" + dso.getID() + "/mets.xml";
    -		    	}
    -		    	else if (object instanceof Collection)
    -		    	{
    -		    		return "/metadata/internal/collection/" + dso.getID() + "/mets.xml";
    -		    	}
    -		    	else if (object instanceof Community)
    -		    	{
    -		    		return "/metadata/internal/community/" + dso.getID() + "/mets.xml";
    -		    	}
    -			}
    -		}
    -		
    -		return null;
    -	}
    -	
    -	/**
    -	 * Return a pretty specific string giving a hint to the theme as to what
    -	 * type of DSpace object is being referenced.
    -	 */
    +    public String getObjectURL(Object object) throws WingException 
    +    {
    +        if (object instanceof DSpaceObject)
    +        {
    +            DSpaceObject dso = (DSpaceObject) object;
    +            String handle = dso.getHandle();
    +            
    +            // If the object has a handle then reference it by its handle.
    +            if (handle != null)
    +            {
    +                return "/metadata/handle/" + handle + "/mets.xml";
    +            }
    +            else
    +            {
    +                // No handle then reference it by an internal ID.
    +                if (dso instanceof Item)
    +                {
    +                    return "/metadata/internal/item/" + dso.getID() + "/mets.xml";
    +                }
    +                else if (object instanceof Collection)
    +                {
    +                    return "/metadata/internal/collection/" + dso.getID() + "/mets.xml";
    +                }
    +                else if (object instanceof Community)
    +                {
    +                    return "/metadata/internal/community/" + dso.getID() + "/mets.xml";
    +                }
    +            }
    +        }
    +        
    +        return null;
    +    }
    +    
    +    /**
    +     * Return a pretty specific string giving a hint to the theme as to what
    +     * type of DSpace object is being referenced.
    +     */
         @Override
    -	public String getObjectType(Object object)
    -	{
    -		if (object instanceof Item)
    -    	{
    -    		return "DSpace Item";
    -    	}
    -    	else if (object instanceof Collection)
    -    	{
    -    		return "DSpace Collection";
    -    	}
    -    	else if (object instanceof Community)
    -    	{
    -    		return "DSpace Community";
    -    	}
    -			
    -		return null;
    -	}
    +    public String getObjectType(Object object)
    +    {
    +        if (object instanceof Item)
    +        {
    +            return "DSpace Item";
    +        }
    +        else if (object instanceof Collection)
    +        {
    +            return "DSpace Collection";
    +        }
    +        else if (object instanceof Community)
    +        {
    +            return "DSpace Community";
    +        }
    +            
    +        return null;
    +    }
     
         /**
          * Return a globally unique identifier for the repository. For dspace, we
          * use the handle prefix.
          */
         @Override
    -	public String getRepositoryIdentifier(Object object) throws WingException
    -	{
    -		return handleService.getPrefix();
    -	}
    -	
    -	/**
    -	 * Return the metadata URL for this repository.
    +    public String getRepositoryIdentifier(Object object) throws WingException
    +    {
    +        return handleService.getPrefix();
    +    }
    +    
    +    /**
    +     * Return the metadata URL for this repository.
          * @param object unused.
          * @return path to the metadata document.
          * @throws org.dspace.app.xmlui.wing.WingException never.
    -	 */
    -	public String getRepositoryURL(Object object) throws WingException
    -	{
    -		String handlePrefix = handleService.getPrefix();
    -		return "/metadata/internal/repository/"+handlePrefix +"/mets.xml";
    -	}
    -	
    -	/**
    -	 * For the DSpace implementation we just return a hash of one entry which contains
    -	 * a reference to this repository's metadata.
    -	 */
    +     */
    +    public String getRepositoryURL(Object object) throws WingException
    +    {
    +        String handlePrefix = handleService.getPrefix();
    +        return "/metadata/internal/repository/"+handlePrefix +"/mets.xml";
    +    }
    +    
    +    /**
    +     * For the DSpace implementation we just return a hash of one entry which contains
    +     * a reference to this repository's metadata.
    +     */
         @Override
    -	public Map getAllManagedRepositories() throws WingException
    -	{
    -		String handlePrefix = handleService.getPrefix();
    -		
    -		Map allRepositories = new HashMap();
    -		allRepositories.put(handlePrefix, "/metadata/internal/repository/"+handlePrefix +"/mets.xml");
    -		
    -		return allRepositories;
    -	}
    +    public Map getAllManagedRepositories() throws WingException
    +    {
    +        String handlePrefix = handleService.getPrefix();
    +        
    +        Map allRepositories = new HashMap();
    +        allRepositories.put(handlePrefix, "/metadata/internal/repository/"+handlePrefix +"/mets.xml");
    +        
    +        return allRepositories;
    +    }
     }
    diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ItemAdapter.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ItemAdapter.java
    index 0602b434d1..1a3aa5b5d2 100644
    --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ItemAdapter.java
    +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/ItemAdapter.java
    @@ -55,13 +55,13 @@ import java.util.*;
      *
      * 

    There are four parts to an item's METS document: descriptive metadata, * file section, structural map, and extra sections. - * + * *

    Request item-support *

    Original Concept, JSPUI version: Universidade do Minho at www.uminho.pt *

    Sponsorship of XMLUI version: Instituto Oceanográfico de España at www.ieo.es * * @author Scott Phillips - * @author Adán Román Ruiz at arvo.es (for request item support) + * @author Adán Román Ruiz at arvo.es (for request item support) */ public class ItemAdapter extends AbstractAdapter @@ -80,7 +80,7 @@ public class ItemAdapter extends AbstractAdapter /** A space-separated list of administrative metadata sections (for item)*/ private StringBuffer amdSecIDS; - + /** A hashmap of all Files and their corresponding space separated list of administrative metadata sections */ private final Map fileAmdSecIDs = new HashMap<>(); @@ -105,7 +105,7 @@ public class ItemAdapter extends AbstractAdapter * @param contextPath * The context path for this web application. */ - public ItemAdapter(Context context, Item item,String contextPath) + public ItemAdapter(Context context, Item item, String contextPath) { super(contextPath); this.item = item; @@ -117,9 +117,9 @@ public class ItemAdapter extends AbstractAdapter { return this.item; } - - - + + + /** * * @@ -186,7 +186,7 @@ public class ItemAdapter extends AbstractAdapter { return "DSpace Item"; } - + /** * @param bitstream a Bitstream. * @return a unique id for a bitstream. @@ -256,158 +256,162 @@ public class ItemAdapter extends AbstractAdapter // Add DIM descriptive metadata if it was requested or if no metadata types // were specified. Furthermore, since this is the default type we also use a // faster rendering method that the crosswalk API. - if(dmdTypes.isEmpty() || dmdTypes.contains("DIM")) + if (dmdTypes.isEmpty() || dmdTypes.contains("DIM")) { - // Metadata element's ID - String dmdID = getGenericID("dmd_"); - // Keep track of all descriptive sections - dmdSecIDS.append(dmdID); - - //////////////////////////////// - // Start a metadata wrapper - attributes = new AttributeMap(); - attributes.put("ID", dmdID); - attributes.put("GROUPID", groupID); - startElement(METS, "dmdSec", attributes); - - //////////////////////////////// - // Start a metadata wrapper - attributes = new AttributeMap(); - attributes.put("MDTYPE","OTHER"); - attributes.put("OTHERMDTYPE", "DIM"); - startElement(METS,"mdWrap",attributes); - - // //////////////////////////////// - // Start the xml data - startElement(METS,"xmlData"); - - - // /////////////////////////////// - // Start the DIM element - attributes = new AttributeMap(); - attributes.put("dspaceType", Constants.typeText[item.getType()]); + // Metadata element's ID + String dmdID = getGenericID("dmd_"); + // Keep track of all descriptive sections + dmdSecIDS.append(dmdID); + + //////////////////////////////// + // Start a metadata wrapper + attributes = new AttributeMap(); + attributes.put("ID", dmdID); + attributes.put("GROUPID", groupID); + startElement(METS, "dmdSec", attributes); + + //////////////////////////////// + // Start a metadata wrapper + attributes = new AttributeMap(); + attributes.put("MDTYPE", "OTHER"); + attributes.put("OTHERMDTYPE", "DIM"); + startElement(METS, "mdWrap", attributes); + + // //////////////////////////////// + // Start the xml data + startElement(METS, "xmlData"); + + + // /////////////////////////////// + // Start the DIM element + attributes = new AttributeMap(); + attributes.put("dspaceType", Constants.typeText[item.getType()]); + if (item.isWithdrawn()) { attributes.put("withdrawn", "y"); } - startElement(DIM,"dim",attributes); - - List dcvs = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); - for (MetadataValue dcv : dcvs) + startElement(DIM, "dim", attributes); + + List dcvs = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); + for (MetadataValue dcv : dcvs) + { + MetadataField metadataField = dcv.getMetadataField(); + if (!metadataExposureService.isHidden(context, dcv.getMetadataField().getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) { - MetadataField metadataField = dcv.getMetadataField(); - if (!metadataExposureService.isHidden(context, dcv.getMetadataField().getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) { - // /////////////////////////////// - // Field element for each metadata field. - attributes = new AttributeMap(); - attributes.put("mdschema", metadataField.getMetadataSchema().getName()); - attributes.put("element", metadataField.getElement()); - if (metadataField.getQualifier() != null) { - attributes.put("qualifier", metadataField.getQualifier()); - } - if (dcv.getLanguage() != null) { - attributes.put("language", dcv.getLanguage()); - } - if (dcv.getAuthority() != null || dcv.getConfidence() != Choices.CF_UNSET) { - attributes.put("authority", dcv.getAuthority()); - attributes.put("confidence", Choices.getConfidenceText(dcv.getConfidence())); - } - startElement(DIM, "field", attributes); - sendCharacters(dcv.getValue()); - endElement(DIM,"field"); + // /////////////////////////////// + // Field element for each metadata field. + attributes = new AttributeMap(); + attributes.put("mdschema", metadataField.getMetadataSchema().getName()); + attributes.put("element", metadataField.getElement()); + if (metadataField.getQualifier() != null) + { + attributes.put("qualifier", metadataField.getQualifier()); + } + if (dcv.getLanguage() != null) + { + attributes.put("language", dcv.getLanguage()); + } + if (dcv.getAuthority() != null || dcv.getConfidence() != Choices.CF_UNSET) + { + attributes.put("authority", dcv.getAuthority()); + attributes.put("confidence", Choices.getConfidenceText(dcv.getConfidence())); + } + startElement(DIM, "field", attributes); + sendCharacters(dcv.getValue()); + endElement(DIM, "field"); } - } - - // /////////////////////////////// - // End the DIM element - endElement(DIM,"dim"); - - // //////////////////////////////// - // End elements - endElement(METS,"xmlData"); - endElement(METS,"mdWrap"); - endElement(METS,"dmdSec"); + } + + // /////////////////////////////// + // End the DIM element + endElement(DIM, "dim"); + + // //////////////////////////////// + // End elements + endElement(METS, "xmlData"); + endElement(METS, "mdWrap"); + endElement(METS, "dmdSec"); } - - + + // Add any extra crosswalks that may configured. for (String dmdType : dmdTypes) { - // If DIM was requested then it was generated above without using - // the crosswalk API. So we can skip this one. - if ("DIM".equals(dmdType)) - { - continue; - } - - DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType); - - if (crosswalk == null) - { - continue; - } - - String dmdID = getGenericID("dmd_"); - // Add our id to the list. - dmdSecIDS.append(" ").append(dmdID); - - //////////////////////////////// - // Start a metadata wrapper - attributes = new AttributeMap(); - attributes.put("ID", dmdID); - attributes.put("GROUPID", groupID); - startElement(METS, "dmdSec", attributes); + // If DIM was requested then it was generated above without using + // the crosswalk API. So we can skip this one. + if ("DIM".equals(dmdType)) + { + continue; + } - //////////////////////////////// - // Start a metadata wrapper - attributes = new AttributeMap(); - if (isDefinedMETStype(dmdType)) - { - attributes.put("MDTYPE", dmdType); - } - else - { - attributes.put("MDTYPE","OTHER"); - attributes.put("OTHERMDTYPE", dmdType); - } - startElement(METS,"mdWrap",attributes); - - // //////////////////////////////// - // Start the xml data - startElement(METS,"xmlData"); + DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(dmdType); - - // /////////////////////////////// - // Send the actual XML content - try { - Element dissemination = crosswalk.disseminateElement(context, item); - - SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); - // Allow the basics for XML - filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); - - SAXOutputter outputter = new SAXOutputter(); - outputter.setContentHandler(filter); - outputter.setLexicalHandler(filter); - outputter.output(dissemination); - } + if (crosswalk == null) + { + continue; + } + + String dmdID = getGenericID("dmd_"); + // Add our id to the list. + dmdSecIDS.append(" ").append(dmdID); + + //////////////////////////////// + // Start a metadata wrapper + attributes = new AttributeMap(); + attributes.put("ID", dmdID); + attributes.put("GROUPID", groupID); + startElement(METS, "dmdSec", attributes); + + //////////////////////////////// + // Start a metadata wrapper + attributes = new AttributeMap(); + if (isDefinedMETStype(dmdType)) + { + attributes.put("MDTYPE", dmdType); + } + else + { + attributes.put("MDTYPE", "OTHER"); + attributes.put("OTHERMDTYPE", dmdType); + } + startElement(METS, "mdWrap", attributes); + + // //////////////////////////////// + // Start the xml data + startElement(METS, "xmlData"); + + + // /////////////////////////////// + // Send the actual XML content + try { + Element dissemination = crosswalk.disseminateElement(context, item); + + SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); + // Allow the basics for XML + filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); + + SAXOutputter outputter = new SAXOutputter(); + outputter.setContentHandler(filter); + outputter.setLexicalHandler(filter); + outputter.output(dissemination); + } catch (JDOMException jdome) - { - throw new WingException(jdome); - } - catch (AuthorizeException ae) - { - // just ignore the authorize exception and continue on - // without parsing the xml document. - } - - + { + throw new WingException(jdome); + } + catch (AuthorizeException ae) + { + // just ignore the authorize exception and continue on + // without parsing the xml document. + } + // //////////////////////////////// // End elements - endElement(METS,"xmlData"); - endElement(METS,"mdWrap"); - endElement(METS,"dmdSec"); + endElement(METS, "xmlData"); + endElement(METS, "mdWrap"); + endElement(METS, "dmdSec"); } @@ -420,71 +424,70 @@ public class ItemAdapter extends AbstractAdapter Boolean include = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.bitstream.mods"); if (include && dmdTypes.contains("MODS")) { - // Generate a second group id for any extra metadata added. - String groupID2 = getGenericID("group_dmd_"); - - List bundles = itemService.getBundles(item, "METADATA"); - for (Bundle bundle : bundles) + // Generate a second group id for any extra metadata added. + String groupID2 = getGenericID("group_dmd_"); + + List bundles = itemService.getBundles(item, "METADATA"); + for (Bundle bundle : bundles) + { + Bitstream bitstream = bundleService.getBitstreamByName(bundle, "MODS.xml"); + + if (bitstream == null) { - Bitstream bitstream = bundleService.getBitstreamByName(bundle, "MODS.xml"); - - if (bitstream == null) - { - continue; - } - - - String dmdID = getGenericID("dmd_"); - - - //////////////////////////////// - // Start a metadata wrapper - attributes = new AttributeMap(); - attributes.put("ID", dmdID); - attributes.put("GROUPID", groupID2); - startElement(METS, "dmdSec", attributes); - - //////////////////////////////// - // Start a metadata wrapper - attributes = new AttributeMap(); - attributes.put("MDTYPE", "MODS"); - startElement(METS,"mdWrap",attributes); - - // //////////////////////////////// - // Start the xml data - startElement(METS,"xmlData"); - - - // /////////////////////////////// - // Send the actual XML content - - SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); - // Allow the basics for XML - filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); - - XMLReader reader = XMLReaderFactory.createXMLReader(); - reader.setContentHandler(filter); - reader.setProperty("http://xml.org/sax/properties/lexical-handler", filter); - try { - InputStream is = bitstreamService.retrieve(context, bitstream); - reader.parse(new InputSource(is)); - } - catch (AuthorizeException ae) - { - // just ignore the authorize exception and continue on - // without parsing the xml document. - } - - // //////////////////////////////// - // End elements - endElement(METS,"xmlData"); - endElement(METS,"mdWrap"); - endElement(METS, "dmdSec"); + continue; } + + + String dmdID = getGenericID("dmd_"); + + + //////////////////////////////// + // Start a metadata wrapper + attributes = new AttributeMap(); + attributes.put("ID", dmdID); + attributes.put("GROUPID", groupID2); + startElement(METS, "dmdSec", attributes); + + //////////////////////////////// + // Start a metadata wrapper + attributes = new AttributeMap(); + attributes.put("MDTYPE", "MODS"); + startElement(METS, "mdWrap", attributes); + + // //////////////////////////////// + // Start the xml data + startElement(METS, "xmlData"); + + + // /////////////////////////////// + // Send the actual XML content + + SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); + // Allow the basics for XML + filter.allowElements().allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); + + XMLReader reader = XMLReaderFactory.createXMLReader(); + reader.setContentHandler(filter); + reader.setProperty("http://xml.org/sax/properties/lexical-handler", filter); + try { + InputStream is = bitstreamService.retrieve(context, bitstream); + reader.parse(new InputSource(is)); + } + catch (AuthorizeException ae) + { + // just ignore the authorize exception and continue on + // without parsing the xml document. + } + + // //////////////////////////////// + // End elements + endElement(METS, "xmlData"); + endElement(METS, "mdWrap"); + endElement(METS, "dmdSec"); + } } - } - + /** * Render the METS administrative section. * @@ -514,72 +517,72 @@ public class ItemAdapter extends AbstractAdapter // Only create an , if we have amdTypes (or sub-sections) specified... // (this keeps our METS file small, by default, and hides all our admin metadata) - if(amdTypes.size() > 0) + if (amdTypes.size() > 0) { - //////////////////////////////// - // Start an administrative wrapper + //////////////////////////////// + // Start an administrative wrapper - // Administrative element's ID - String amdID = getGenericID("amd_"); - attributes = new AttributeMap(); - attributes.put("ID", amdID); - startElement(METS, "amdSec", attributes); + // Administrative element's ID + String amdID = getGenericID("amd_"); + attributes = new AttributeMap(); + attributes.put("ID", amdID); + startElement(METS, "amdSec", attributes); - groupID = getGenericID("group_amd_"); - attributes.put("GROUPID", groupID); + groupID = getGenericID("group_amd_"); + attributes.put("GROUPID", groupID); } // For each administrative metadata section specified for (String amdSecName : amdTypes.keySet()) { - // get a list of metadata crosswalks which will be used to build - // this administrative metadata section - List mdTypes = amdTypes.get(amdSecName); + // get a list of metadata crosswalks which will be used to build + // this administrative metadata section + List mdTypes = amdTypes.get(amdSecName); - // For each crosswalk - for (String mdType : mdTypes) - { - // get our dissemination crosswalk - DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(mdType); - - // skip, if we cannot find this crosswalk in config file - if (crosswalk == null) + // For each crosswalk + for (String mdType : mdTypes) { - continue; - } + // get our dissemination crosswalk + DisseminationCrosswalk crosswalk = getDisseminationCrosswalk(mdType); - // First, check if this crosswalk can handle disseminating Item-level Administrative metadata - if(crosswalk.canDisseminate(item)) - { - // Since this crosswalk works with items, first render a section for entire item - renderAmdSubSection(amdSecName, mdType, crosswalk, item); - } + // skip, if we cannot find this crosswalk in config file + if (crosswalk == null) + { + continue; + } - // Next, we'll try and render Bitstream-level administrative metadata - // (Although, we're only rendering this metadata for the bundles specified) - List bundles = findEnabledBundles(); - for (Bundle bundle : bundles) - { - List bitstreams = bundle.getBitstreams(); + // First, check if this crosswalk can handle disseminating Item-level Administrative metadata + if (crosswalk.canDisseminate(item)) + { + // Since this crosswalk works with items, first render a section for entire item + renderAmdSubSection(amdSecName, mdType, crosswalk, item); + } - // Create a sub-section of for each bitstream in bundle - for(Bitstream bitstream : bitstreams) - { - // Only render the section if crosswalk works with bitstreams - if(crosswalk.canDisseminate(bitstream)) - { - renderAmdSubSection(amdSecName, mdType, crosswalk, bitstream); - } - } // end for each bitstream - } // end for each bundle - } // end for each crosswalk + // Next, we'll try and render Bitstream-level administrative metadata + // (Although, we're only rendering this metadata for the bundles specified) + List bundles = findEnabledBundles(); + for (Bundle bundle : bundles) + { + List bitstreams = bundle.getBitstreams(); + + // Create a sub-section of for each bitstream in bundle + for(Bitstream bitstream : bitstreams) + { + // Only render the section if crosswalk works with bitstreams + if (crosswalk.canDisseminate(bitstream)) + { + renderAmdSubSection(amdSecName, mdType, crosswalk, bitstream); + } + } // end for each bitstream + } // end for each bundle + } // end for each crosswalk } // end for each amdSec - - if(amdTypes.size() > 0) + + if (amdTypes.size() > 0) { ////////////////////////////////// // End administrative section - endElement(METS,"amdSec"); + endElement(METS, "amdSec"); } } @@ -622,28 +625,28 @@ public class ItemAdapter extends AbstractAdapter // If this is a bitstream if (dso.getType() == Constants.BITSTREAM) { - // Add this to our list of each file's administrative section IDs - String fileID = getFileID((Bitstream) dso); - if(fileAmdSecIDs.containsKey(fileID)) - { - fileAmdSecIDs.get(fileID).append(" ").append(amdSecID); - } - else - { - fileAmdSecIDs.put(fileID, new StringBuffer(amdSecID)); - } + // Add this to our list of each file's administrative section IDs + String fileID = getFileID((Bitstream) dso); + if (fileAmdSecIDs.containsKey(fileID)) + { + fileAmdSecIDs.get(fileID).append(" ").append(amdSecID); + } + else + { + fileAmdSecIDs.put(fileID, new StringBuffer(amdSecID)); + } } // else if an Item else if (dso.getType() == Constants.ITEM) { - // Add this to our list of item's administrative section IDs - if(amdSecIDS==null) - { - amdSecIDS = new StringBuffer(amdSecID); - } - else - { - amdSecIDS.append(" ").append(amdSecID); - } + // Add this to our list of item's administrative section IDs + if (amdSecIDS == null) + { + amdSecIDS = new StringBuffer(amdSecID); + } + else + { + amdSecIDS.append(" ").append(amdSecID); + } } //////////////////////////////// @@ -655,14 +658,14 @@ public class ItemAdapter extends AbstractAdapter } else { - attributes.put("MDTYPE","OTHER"); + attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", mdType); } - startElement(METS,"mdWrap",attributes); + startElement(METS, "mdWrap", attributes); ////////////////////////////////// // Start the xml data - startElement(METS,"xmlData"); + startElement(METS, "xmlData"); ///////////////////////////////// // Send the actual XML content, @@ -691,9 +694,9 @@ public class ItemAdapter extends AbstractAdapter // //////////////////////////////// // End elements - endElement(METS,"xmlData"); - endElement(METS,"mdWrap"); - endElement(METS,amdSecName); + endElement(METS, "xmlData"); + endElement(METS, "mdWrap"); + endElement(METS, amdSecName); } /** @@ -722,21 +725,22 @@ public class ItemAdapter extends AbstractAdapter * @throws org.xml.sax.SAXException passed through. */ @Override - protected void renderFileSection(Context context) throws SQLException, SAXException + protected void renderFileSection(Context context) + throws SQLException, SAXException { AttributeMap attributes; - + // ////////////////////// // Start a new file section - startElement(METS,"fileSec"); - + startElement(METS, "fileSec"); + // Check if the user is requested a specific bundle or // the all bundles. List bundles = findEnabledBundles(); // Suppress license? Boolean showLicense = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.licence_bundle.show"); - + // Loop over all requested bundles for (Bundle bundle : bundles) { @@ -765,14 +769,14 @@ public class ItemAdapter extends AbstractAdapter // Start bundle's file group attributes = new AttributeMap(); attributes.put("USE", use); - startElement(METS,"fileGrp",attributes); - + startElement(METS, "fileGrp", attributes); + for (Bitstream bitstream : bundle.getBitstreams()) { // ////////////////////////////// // Determine the file's IDs String fileID = getFileID(bitstream); - + Bitstream originalBitstream = null; if (isDerivedBundle) { @@ -782,11 +786,11 @@ public class ItemAdapter extends AbstractAdapter // Check if there were administrative metadata sections corresponding to this file String admIDs = null; - if(fileAmdSecIDs.containsKey(fileID)) + if (fileAmdSecIDs.containsKey(fileID)) { admIDs = fileAmdSecIDs.get(fileID).toString(); } - + // Render the actual file & flocate elements. renderFileWithAllowed(item, bitstream, fileID, groupID, admIDs); @@ -801,18 +805,18 @@ public class ItemAdapter extends AbstractAdapter } } } - + // /////////////////// // End the bundle's file group - endElement(METS,"fileGrp"); + endElement(METS, "fileGrp"); } - + // ////////////////////// // End the file section - endElement(METS,"fileSec"); + endElement(METS, "fileSec"); } - + /** * Render the item's structural map. This includes a list of * content bitstreams, those are bitstreams that are typically @@ -832,16 +836,17 @@ public class ItemAdapter extends AbstractAdapter * @throws org.xml.sax.SAXException passed through. */ @Override - protected void renderStructureMap() throws SQLException, SAXException + protected void renderStructureMap() + throws SQLException, SAXException { AttributeMap attributes; - + // /////////////////////// // Start a new structure map attributes = new AttributeMap(); attributes.put("TYPE", "LOGICAL"); attributes.put("LABEL", "DSpace"); - startElement(METS,"structMap",attributes); + startElement(METS, "structMap", attributes); // //////////////////////////////// // Start the special first division @@ -857,53 +862,53 @@ public class ItemAdapter extends AbstractAdapter { attributes.put("AMDID", amdSecIDS.toString()); } - startElement(METS,"div",attributes); - + startElement(METS, "div", attributes); + // add a fptr pointer to the primary bitstream. if (primaryBitstream != null) { - // //////////////////////////////// - // Start & end a reference to the primary bitstream. - attributes = new AttributeMap(); - String fileID = getFileID(primaryBitstream); - attributes.put("FILEID", fileID); - - startElement(METS,"fptr",attributes); - endElement(METS,"fptr"); + // //////////////////////////////// + // Start & end a reference to the primary bitstream. + attributes = new AttributeMap(); + String fileID = getFileID(primaryBitstream); + attributes.put("FILEID", fileID); + + startElement(METS, "fptr", attributes); + endElement(METS, "fptr"); } for (Bitstream bitstream : contentBitstreams) { - // //////////////////////////////////// - // Start a div for each publicly viewable bitstream - attributes = new AttributeMap(); - attributes.put("ID", getGenericID("div_")); - attributes.put("TYPE", "DSpace Content Bitstream"); - startElement(METS,"div",attributes); + // //////////////////////////////////// + // Start a div for each publicly viewable bitstream + attributes = new AttributeMap(); + attributes.put("ID", getGenericID("div_")); + attributes.put("TYPE", "DSpace Content Bitstream"); + startElement(METS, "div", attributes); - // //////////////////////////////// - // Start a the actualy pointer to the bitstream FIXME: what? - attributes = new AttributeMap(); - String fileID = getFileID(bitstream); - attributes.put("FILEID", fileID); - - startElement(METS,"fptr",attributes); - endElement(METS,"fptr"); - - // /////////////////////////////// - // End the div - endElement(METS,"div"); + // //////////////////////////////// + // Start a the actualy pointer to the bitstream FIXME: what? + attributes = new AttributeMap(); + String fileID = getFileID(bitstream); + attributes.put("FILEID", fileID); + + startElement(METS, "fptr", attributes); + endElement(METS, "fptr"); + + // /////////////////////////////// + // End the div + endElement(METS, "div"); } // //////////////////////////////// // End the special first division - endElement(METS,"div"); - + endElement(METS, "div"); + // /////////////////////// // End the structure map - endElement(METS,"structMap"); + endElement(METS, "structMap"); } - + /** @@ -922,45 +927,45 @@ public class ItemAdapter extends AbstractAdapter { return; } - - + + List bundles = itemService.getBundles(item, "METADATA"); for (Bundle bundle : bundles) { - Bitstream bitstream = bundleService.getBitstreamByName(bundle, "METS.xml"); + Bitstream bitstream = bundleService.getBitstreamByName(bundle, "METS.xml"); - if (bitstream == null) - { - continue; - } + if (bitstream == null) + { + continue; + } - // /////////////////////////////// - // Send the actual XML content - try { - SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); - // Allow the basics for XML - filter.allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); - // Special option, only allow elements below the second level to pass through. This - // will trim out the METS declaration and only leave the actual METS parts to be - // included. - filter.allowElements(1); - - - XMLReader reader = XMLReaderFactory.createXMLReader(); - reader.setContentHandler(filter); - reader.setProperty("http://xml.org/sax/properties/lexical-handler", filter); - reader.parse(new InputSource(bitstreamService.retrieve(context, bitstream))); - } - catch (AuthorizeException ae) - { - // just ignore the authorize exception and continue on - // without parsing the xml document. - } + // /////////////////////////////// + // Send the actual XML content + try { + SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, namespaces); + // Allow the basics for XML + filter.allowIgnorableWhitespace().allowCharacters().allowCDATA().allowPrefixMappings(); + // Special option, only allow elements below the second level to pass through. This + // will trim out the METS declaration and only leave the actual METS parts to be + // included. + filter.allowElements(1); + + + XMLReader reader = XMLReaderFactory.createXMLReader(); + reader.setContentHandler(filter); + reader.setProperty("http://xml.org/sax/properties/lexical-handler", filter); + reader.parse(new InputSource(bitstreamService.retrieve(context, bitstream))); + } + catch (AuthorizeException ae) + { + // just ignore the authorize exception and continue on + // without parsing the xml document. + } } } - + /** * Checks which Bundles of current item a user has requested. * If none specifically requested, then all Bundles are returned. @@ -979,19 +984,19 @@ public class ItemAdapter extends AbstractAdapter } else { - bundles = new ArrayList<>(); - for (String fileGrpType : fileGrpTypes) + bundles = new ArrayList<>(); + for (String fileGrpType : fileGrpTypes) + { + for (Bundle newBundle : itemService.getBundles(item, fileGrpType)) { - for (Bundle newBundle : itemService.getBundles(item, fileGrpType)) - { - bundles.add(newBundle); - } + bundles.add(newBundle); } + } } - + return bundles; } - + /** * For a bitstream that's a thumbnail or extracted text, find the @@ -1005,7 +1010,7 @@ public class ItemAdapter extends AbstractAdapter * @return the corresponding original bitstream (or null) * @throws java.sql.SQLException passed through. */ - protected static Bitstream findOriginalBitstream(Item item,Bitstream derived) throws SQLException + protected static Bitstream findOriginalBitstream(Item item, Bitstream derived) throws SQLException { // FIXME: this method is a copy of the one found below. However, the // original method is protected so we can't use it here. I think that @@ -1026,7 +1031,7 @@ public class ItemAdapter extends AbstractAdapter for (Bundle bundle : bundles) { if ((bundle.getName() != null) - && bundle.getName().equals("ORIGINAL")) + && bundle.getName().equals("ORIGINAL")) { // Now find the corresponding bitstream List bitstreams = bundle.getBitstreams(); @@ -1047,7 +1052,7 @@ public class ItemAdapter extends AbstractAdapter /** * Generate a METS file element for a given bitstream. - * + * * @param item * If the bitstream is associated with an item provide the item * otherwise leave null. @@ -1064,15 +1069,15 @@ public class ItemAdapter extends AbstractAdapter * @throws org.xml.sax.SAXException passed through. * @throws java.sql.SQLException passed through. */ - + // FIXME: this method is a copy of the one inherited. However the // original method is final so we must rename it. - protected void renderFileWithAllowed(Item item, Bitstream bitstream, String fileID, String groupID, String admID) throws SAXException, SQLException + protected void renderFileWithAllowed(Item item, Bitstream bitstream, String fileID, String groupID, String admID) throws SAXException, SQLException { - AttributeMap attributes; - - // ////////////////////////////// - // Determine the file attributes + AttributeMap attributes; + + // ////////////////////////////// + // Determine the file attributes BitstreamFormat format = bitstream.getFormat(context); String mimeType = null; if (format != null) @@ -1082,12 +1087,12 @@ public class ItemAdapter extends AbstractAdapter String checksumType = bitstream.getChecksumAlgorithm(); String checksum = bitstream.getChecksum(); long size = bitstream.getSize(); - + // //////////////////////////////// // Start the actual file attributes = new AttributeMap(); attributes.put("ID", fileID); - attributes.put("GROUPID",groupID); + attributes.put("GROUPID", groupID); if (admID != null && admID.length()>0) { attributes.put("ADMID", admID); @@ -1098,19 +1103,19 @@ public class ItemAdapter extends AbstractAdapter } if (checksumType != null && checksum != null) { - attributes.put("CHECKSUM", checksum); - attributes.put("CHECKSUMTYPE", checksumType); + attributes.put("CHECKSUM", checksum); + attributes.put("CHECKSUMTYPE", checksumType); } attributes.put("SIZE", String.valueOf(size)); - startElement(METS,"file",attributes); - - + startElement(METS, "file", attributes); + + // //////////////////////////////////// // Determine the file location attributes String name = bitstream.getName(); String description = bitstream.getDescription(); - + // If possible reference this bitstream via a handle, however this may // be null if a handle has not yet been assigned. In this case reference the // item its internal id. In the last case where the bitstream is not associated @@ -1128,14 +1133,14 @@ public class ItemAdapter extends AbstractAdapter { identifier = "id/" + bitstream.getID(); } - - + + String url = contextPath + "/bitstream/"+identifier+"/"; - + // If we can put the pretty name of the bitstream on the end of the URL try { - if (bitstream.getName() != null) + if (bitstream.getName() != null) { url += Util.encodeBitstreamName(bitstream.getName(), "UTF-8"); } @@ -1143,22 +1148,22 @@ public class ItemAdapter extends AbstractAdapter catch (UnsupportedEncodingException uee) { // just ignore it, we don't have to have a pretty - // name on the end of the URL because the sequence id will - // locate it. However it means that links in this file might - // not work.... + // name on the end of the URL because the sequence id will + // locate it. However it means that links in this file might + // not work.... } - + url += "?sequence="+bitstream.getSequenceID(); - // Test if we are allowed to see this item - String isAllowed = "n"; - try { - if (authorizeService.authorizeActionBoolean(context, bitstream, Constants.READ)) { - isAllowed = "y"; - } - } catch (SQLException e) {/* Do nothing */} - - url += "&isAllowed=" + isAllowed; + // Test if we are allowed to see this item + String isAllowed = "n"; + try { + if (authorizeService.authorizeActionBoolean(context, bitstream, Constants.READ)) { + isAllowed = "y"; + } + } catch (SQLException e) {/* Do nothing */} + + url += "&isAllowed=" + isAllowed; // ////////////////////// // Start the file location @@ -1166,22 +1171,22 @@ public class ItemAdapter extends AbstractAdapter AttributeMap attributesXLINK = new AttributeMap(); attributesXLINK.setNamespace(XLINK); attributes.put("LOCTYPE", "URL"); - attributesXLINK.put("type","locator"); + attributesXLINK.put("type", "locator"); attributesXLINK.put("title", name); if (description != null) { attributesXLINK.put("label", description); } attributesXLINK.put("href", url); - startElement(METS,"FLocat",attributes,attributesXLINK); - + startElement(METS, "FLocat", attributes, attributesXLINK); + // /////////////////////// // End file location - endElement(METS,"FLocate"); - + endElement(METS, "FLocate"); + // //////////////////////////////// // End the file - endElement(METS,"file"); - } + endElement(METS, "file"); + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/RepositoryAdapter.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/RepositoryAdapter.java index 4015ae0d3b..ffcb639fe2 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/RepositoryAdapter.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/RepositoryAdapter.java @@ -25,28 +25,28 @@ import org.dspace.handle.service.HandleService; import org.xml.sax.SAXException; /** - * This is an an adapter which translates a DSpace repository into a METS + * This is an an adapter which translates a DSpace repository into a METS * document. Unfortunately, there is no real definition of what this is. So * we just kind of made it up based upon what we saw for the item profile. - * + * * The basic structure is simply two parts: the descriptive metadata and a - * structural map. The descriptive metadata is a place to put metadata about + * structural map. The descriptive metadata is a place to put metadata about * the whole repository. The structural map is used to map relationships * between communities and collections in DSpace. - * + * * @author Scott Phillips */ public class RepositoryAdapter extends AbstractAdapter { - /** MODS namespace */ + /** MODS namespace */ public static final String MODS_URI = "http://www.loc.gov/mods/v3"; public static final Namespace MODS = new Namespace(MODS_URI); - + /** A space separated list of descriptive metadata sections */ private String dmdSecIDS; - + /** Dspace context to be able to look up additional objects */ private final Context context; @@ -55,10 +55,10 @@ public class RepositoryAdapter extends AbstractAdapter /** * Construct a new RepositoryAdapter - * + * * @param context * The DSpace context to look up communities / collections. - * + * * @param contextPath * The context Path of this web application. */ @@ -86,25 +86,27 @@ public class RepositoryAdapter extends AbstractAdapter { return handleService.getPrefix(); } - - /** - * The OBJID is used to encode the URL to the object, in this - * case the repository which is just at the contextPath. + + /** + * The OBJID is used to encode the URL to the object, in this + * case the repository which is just at the contextPath. * @return local path to the object. * @throws org.dspace.app.xmlui.wing.WingException passed through. - */ + */ @Override - protected String getMETSOBJID() throws WingException { - - if (contextPath == null) + protected String getMETSOBJID() + throws WingException + { + + if (contextPath == null) { return "/"; } - else + else { return contextPath + "/"; } - } + } /** * @return Return the URL for editing this item @@ -136,7 +138,7 @@ public class RepositoryAdapter extends AbstractAdapter return "DSpace Repository"; } - + /** * * @@ -150,19 +152,20 @@ public class RepositoryAdapter extends AbstractAdapter /** * Render the repository's descriptive metadata section. * - * For a the DSpace repository we just grab a few items - * from the config file and put them into the descriptive - * section, such as the name, hostname, handle prefix, and + * For a the DSpace repository we just grab a few items + * from the config file and put them into the descriptive + * section, such as the name, hostname, handle prefix, and * default language. - * + * * @throws org.xml.sax.SAXException passed through. */ @Override - protected void renderDescriptiveSection() throws SAXException + protected void renderDescriptiveSection() + throws SAXException { - AttributeMap attributes; - - // Generate our ids + AttributeMap attributes; + + // Generate our ids String dmdID = getGenericID("dmd_"); String groupID = getGenericID("group_dmd_"); @@ -171,66 +174,66 @@ public class RepositoryAdapter extends AbstractAdapter attributes = new AttributeMap(); attributes.put("ID", dmdID); attributes.put("GROUPID", groupID); - startElement(METS,"dmdSec",attributes); + startElement(METS, "dmdSec", attributes); // //////////////////////////////// // Start a metadata wrapper (hardcoded to mods) attributes = new AttributeMap(); attributes.put("MDTYPE", "OTHER"); attributes.put("OTHERMDTYPE", "DIM"); - startElement(METS,"mdWrap",attributes); + startElement(METS, "mdWrap", attributes); // //////////////////////////////// // Start the xml data - startElement(METS,"xmlData"); - + startElement(METS, "xmlData"); + ///////////////////////////////// - // Start the DIM element - attributes = new AttributeMap(); - attributes.put("dspaceType", Constants.typeText[Constants.SITE]); - startElement(DIM,"dim",attributes); - - // Entry for dspace.name - attributes = new AttributeMap(); - attributes.put("mdschema","dspace"); - attributes.put("element", "name"); - startElement(DIM,"field",attributes); - sendCharacters(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.name")); - endElement(DIM,"field"); - - // Entry for dspace.hostname - attributes = new AttributeMap(); - attributes.put("mdschema","dspace"); - attributes.put("element", "hostname"); - startElement(DIM,"field",attributes); - sendCharacters(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.hostname")); - endElement(DIM,"field"); - - // Entry for handle.prefix - attributes = new AttributeMap(); - attributes.put("mdschema","dspace"); - attributes.put("element", "handle"); - startElement(DIM,"field",attributes); - sendCharacters(handleService.getPrefix()); - endElement(DIM,"field"); - - // Entry for default.language - attributes = new AttributeMap(); - attributes.put("mdschema","dspace"); - attributes.put("element", "default"); - attributes.put("qualifier", "language"); - startElement(DIM,"field",attributes); - sendCharacters(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("default.language")); - endElement(DIM,"field"); - + // Start the DIM element + attributes = new AttributeMap(); + attributes.put("dspaceType", Constants.typeText[Constants.SITE]); + startElement(DIM, "dim", attributes); + + // Entry for dspace.name + attributes = new AttributeMap(); + attributes.put("mdschema", "dspace"); + attributes.put("element", "name"); + startElement(DIM, "field", attributes); + sendCharacters(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.name")); + endElement(DIM, "field"); + + // Entry for dspace.hostname + attributes = new AttributeMap(); + attributes.put("mdschema", "dspace"); + attributes.put("element", "hostname"); + startElement(DIM, "field", attributes); + sendCharacters(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.hostname")); + endElement(DIM, "field"); + + // Entry for handle.prefix + attributes = new AttributeMap(); + attributes.put("mdschema", "dspace"); + attributes.put("element", "handle"); + startElement(DIM, "field", attributes); + sendCharacters(handleService.getPrefix()); + endElement(DIM, "field"); + + // Entry for default.language + attributes = new AttributeMap(); + attributes.put("mdschema", "dspace"); + attributes.put("element", "default"); + attributes.put("qualifier", "language"); + startElement(DIM, "field", attributes); + sendCharacters(DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("default.language")); + endElement(DIM, "field"); + // /////////////////////////////// // End the DIM element - endElement(DIM,"dim"); - + endElement(DIM, "dim"); + // End all the open elements. - endElement(METS,"xmlData"); - endElement(METS,"mdWrap"); - endElement(METS,"dmdSec"); + endElement(METS, "xmlData"); + endElement(METS, "mdWrap"); + endElement(METS, "dmdSec"); // Remember the IDS this.dmdSecIDS = dmdID; @@ -239,22 +242,22 @@ public class RepositoryAdapter extends AbstractAdapter /** * Render the repository's structure map. This map will include a reference to * all the community and collection objects showing how they are related to - * one another. + * one another. * @throws java.sql.SQLException passed through. * @throws org.xml.sax.SAXException passed through. */ @Override - protected void renderStructureMap() throws SQLException, SAXException + protected void renderStructureMap() throws SQLException, SAXException { - AttributeMap attributes; - - // ////////////////////////// - // Start the new struct map + AttributeMap attributes; + + // ////////////////////////// + // Start the new struct map attributes = new AttributeMap(); attributes.put("TYPE", "LOGICAL"); attributes.put("LABEL", "DSpace"); - startElement(METS,"structMap",attributes); - + startElement(METS, "structMap", attributes); + // //////////////////////////////// // Start the special first division attributes = new AttributeMap(); @@ -264,20 +267,20 @@ public class RepositoryAdapter extends AbstractAdapter { attributes.put("DMDID", dmdSecIDS); } - startElement(METS,"div",attributes); + startElement(METS, "div", attributes); // Put each root level node into the document. for (Community community : communityService.findAllTop(context)) { renderStructuralDiv(community); } - - + + // ////////////////// // Close special first division and structural map - endElement(METS,"div"); - endElement(METS,"structMap"); - + endElement(METS, "div"); + endElement(METS, "structMap"); + } /** @@ -298,7 +301,7 @@ public class RepositoryAdapter extends AbstractAdapter */ private void renderStructuralDiv(DSpaceObject dso) throws SAXException, SQLException { - AttributeMap attributes; + AttributeMap attributes; // //////////////////////////////// // Start the new div for this repository container @@ -311,36 +314,36 @@ public class RepositoryAdapter extends AbstractAdapter { attributes.put("TYPE", "DSpace Collection"); } - startElement(METS,"div",attributes); - + startElement(METS, "div", attributes); + // ////////////////////////////////// // Start a metadata pointer for this container attributes = new AttributeMap(); AttributeMap attributesXLINK = new AttributeMap(); attributesXLINK.setNamespace(XLINK); - + attributes.put("LOCTYPE", "URL"); attributesXLINK.put("href", "/metadata/handle/"+ dso.getHandle() +"/mets.xml"); - startElement(METS,"mptr",attributes,attributesXLINK); - endElement(METS,"mptr"); - + startElement(METS, "mptr", attributes, attributesXLINK); + endElement(METS, "mptr"); + // Recurse to ensure that our children are also included even if this // node already existed in the div structure. if (dso instanceof Community) { - for (DSpaceObject child : ((Community)dso).getCollections()) + for (DSpaceObject child : ((Community)dso).getCollections()) { renderStructuralDiv(child); } - - for (DSpaceObject child : ((Community)dso).getSubcommunities()) + + for (DSpaceObject child : ((Community)dso).getSubcommunities()) { renderStructuralDiv(child); } } - + // //////////////////// // Close division - endElement(METS,"div"); + endElement(METS, "div"); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/SAXFilter.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/SAXFilter.java index c6b8b82e9b..96c4c8d54a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/SAXFilter.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/objectmanager/SAXFilter.java @@ -15,250 +15,250 @@ import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.NamespaceSupport; -/** - * This is a Swiss army like SAX Filter, its purpose is to filter out - * undesirable SAX events from the stream. The primary application of - * this is for inserting SAX fragment into an existing SAX pipeline, - * under this scenario you would not want new startDocument or - * endDocument events interfering with the existing pipeline thus +/** + * This is a Swiss army like SAX Filter, its purpose is to filter out + * undesirable SAX events from the stream. The primary application of + * this is for inserting SAX fragment into an existing SAX pipeline, + * under this scenario you would not want new startDocument or + * endDocument events interfering with the existing pipeline thus * this class can filter those out. - * - * The Swiss army part comes in because it's configurable. Instead of + * + * The Swiss army part comes in because it's configurable. Instead of * defining a static set of events that are filled out by default all * events are filled out and must be turned on to allow each type * individually. - * - * Primarily you can filter events based upon their type, i.e. start/end + * + * Primarily you can filter events based upon their type, i.e. start/end * elements or start/end documents. However there is one special control, * and that is to only allow elements below a minimum level. - * . - * + * . + * * @author Scott Phillips */ public class SAXFilter implements ContentHandler, LexicalHandler { - - /** Control for which type of SAX events to allow */ - private boolean allowDocuments = false; - private boolean allowDocumentLocators = false; - private boolean allowProcessingInstructions = false; - private boolean allowPrefixMappings = false; - private boolean allowElements = false; - private boolean allowIgnorableWhitespace = false; - private boolean allowSkippedEntities = false; - private boolean allowCharacters = false; - private boolean allowDTDs = false; - private boolean allowEntities = false; - private boolean allowCDATA = false; - private boolean allowComments = false; - - - /** The minimum level an element must be before it will be allowed */ - private int minimumElementLevel = -1; - - /** - * The current XML level, each time start element is encountered this - * is increased, and each time an end element is encountered it is - * decreased. - */ - private int currentElementLevel = 0; - - - /** - * If no URI is provided then substitute this default prefix and URI: - */ - private String defaultURI; - - /** The SAX handlers and namespace support */ - private ContentHandler contentHandler; - private LexicalHandler lexicalHandler; - private NamespaceSupport namespaces; + /** Control for which type of SAX events to allow */ + private boolean allowDocuments = false; + private boolean allowDocumentLocators = false; + private boolean allowProcessingInstructions = false; + private boolean allowPrefixMappings = false; + private boolean allowElements = false; + private boolean allowIgnorableWhitespace = false; + private boolean allowSkippedEntities = false; + private boolean allowCharacters = false; - /** - * Construct a new SAXFilter such that the allowed events will be routed - * to the corresponding content and lexical handlers. - * - * @param contentHandler The SAX content handler. - * @param lexicalHandler The SAX lexical handler. - * @param namespaces Namespace support which records what prefixes have been defined. - */ - public SAXFilter(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) - { - this.contentHandler = contentHandler; - this.lexicalHandler = lexicalHandler; - this.namespaces = namespaces; - } + private boolean allowDTDs = false; + private boolean allowEntities = false; + private boolean allowCDATA = false; + private boolean allowComments = false; - /** Allow start/end document events + + /** The minimum level an element must be before it will be allowed */ + private int minimumElementLevel = -1; + + /** + * The current XML level, each time start element is encountered this + * is increased, and each time an end element is encountered it is + * decreased. + */ + private int currentElementLevel = 0; + + + /** + * If no URI is provided then substitute this default prefix and URI: + */ + private String defaultURI; + + /** The SAX handlers and namespace support */ + private ContentHandler contentHandler; + private LexicalHandler lexicalHandler; + private NamespaceSupport namespaces; + + /** + * Construct a new SAXFilter such that the allowed events will be routed + * to the corresponding content and lexical handlers. + * + * @param contentHandler The SAX content handler. + * @param lexicalHandler The SAX lexical handler. + * @param namespaces Namespace support which records what prefixes have been defined. + */ + public SAXFilter(ContentHandler contentHandler, LexicalHandler lexicalHandler, NamespaceSupport namespaces) + { + this.contentHandler = contentHandler; + this.lexicalHandler = lexicalHandler; + this.namespaces = namespaces; + } + + /** Allow start/end document events * @return this instance. */ - public SAXFilter allowDocuments() { - this.allowDocuments = true; - return this; - } - - /** Allow document locator events + public SAXFilter allowDocuments() { + this.allowDocuments = true; + return this; + } + + /** Allow document locator events * @return this instance. */ - public SAXFilter allowDocumentLocators() { - this.allowDocumentLocators = true; - return this; - } - - /** Allow processing instruction events + public SAXFilter allowDocumentLocators() { + this.allowDocumentLocators = true; + return this; + } + + /** Allow processing instruction events * @return this instance. */ - public SAXFilter allowProcessingInstructions() { - this.allowProcessingInstructions = true; - return this; - } - - /** allow start/end prefix mapping events + public SAXFilter allowProcessingInstructions() { + this.allowProcessingInstructions = true; + return this; + } + + /** allow start/end prefix mapping events * @return this instance. */ - public SAXFilter allowPrefixMappings() { - this.allowPrefixMappings = true; - return this; - } - - /** allow start/end element events + public SAXFilter allowPrefixMappings() { + this.allowPrefixMappings = true; + return this; + } + + /** allow start/end element events * @return this instance. */ - public SAXFilter allowElements() { - this.allowElements = true; - return this; - } - - /** - * Allow start/end element events. - * - * However only allow those start / end events if - * they are below the given XML level. I.e. each nested - * element is a new level. - * - * @param minimumElementLevel - * the minimum level required. - * @return this SAXFilter instance. - */ - public SAXFilter allowElements(int minimumElementLevel) - { - this.allowElements = true; - this.minimumElementLevel = minimumElementLevel; - return this; - } - - /** Allow ignorable whitespace events + public SAXFilter allowElements() { + this.allowElements = true; + return this; + } + + /** + * Allow start/end element events. + * + * However only allow those start / end events if + * they are below the given XML level. I.e. each nested + * element is a new level. + * + * @param minimumElementLevel + * the minimum level required. + * @return this SAXFilter instance. + */ + public SAXFilter allowElements(int minimumElementLevel) + { + this.allowElements = true; + this.minimumElementLevel = minimumElementLevel; + return this; + } + + /** Allow ignorable whitespace events * @return this instance. */ - public SAXFilter allowIgnorableWhitespace() { - this.allowIgnorableWhitespace = true; - return this; - } - - /** Allow start / end events for skipped entities + public SAXFilter allowIgnorableWhitespace() { + this.allowIgnorableWhitespace = true; + return this; + } + + /** Allow start / end events for skipped entities * @return this instance. */ - public SAXFilter allowSkippedEntities() { - this.allowSkippedEntities = true; - return this; - } - - /** Allow character events + public SAXFilter allowSkippedEntities() { + this.allowSkippedEntities = true; + return this; + } + + /** Allow character events * @return this instance. */ - public SAXFilter allowCharacters() { - this.allowCharacters = true; - return this; - } - - /** Allow DTD events + public SAXFilter allowCharacters() { + this.allowCharacters = true; + return this; + } + + /** Allow DTD events * @return this instance. */ - public SAXFilter allowDTDs() { - this.allowDTDs = true; - return this; - } - - /** Allow XML entities events + public SAXFilter allowDTDs() { + this.allowDTDs = true; + return this; + } + + /** Allow XML entities events * @return this instance. */ - public SAXFilter allowEntities() { - this.allowEntities = true; - return this; - } - - /** Allow CDATA events + public SAXFilter allowEntities() { + this.allowEntities = true; + return this; + } + + /** Allow CDATA events * @return this instance. */ - public SAXFilter allowCDATA() { - this.allowCDATA = true; - return this; - } - - /** Allow comment events + public SAXFilter allowCDATA() { + this.allowCDATA = true; + return this; + } + + /** Allow comment events * @return this instance. */ - public SAXFilter allowComments() { - this.allowComments = true; - return this; - } - - /** - * Add a default namespace is none is provided. The namespace - * should have already been declared (add added to the - * namespace support object - * - * @param uri the default namespace uri. - * @return this instance. - */ - public SAXFilter setDefaultNamespace(String uri) - { - this.defaultURI = uri; - return this; - } + public SAXFilter allowComments() { + this.allowComments = true; + return this; + } - /* - * SAX Content events + /** + * Add a default namespace is none is provided. The namespace + * should have already been declared (add added to the + * namespace support object + * + * @param uri the default namespace uri. + * @return this instance. + */ + public SAXFilter setDefaultNamespace(String uri) + { + this.defaultURI = uri; + return this; + } + + /* + * SAX Content events */ /** * Start of the document. * @throws org.xml.sax.SAXException passed through. - */ + */ @Override - public void startDocument() throws SAXException - { - if (allowDocuments) + public void startDocument() throws SAXException + { + if (allowDocuments) { contentHandler.startDocument(); } - } + } /** * End of the document. * @throws SAXException passed through. */ @Override - public void endDocument() throws SAXException - { - if (allowDocuments) + public void endDocument() throws SAXException + { + if (allowDocuments) { contentHandler.endDocument(); } - } - + } + /** * Supply a callback object for location awareness. * * @param locator the new locator. */ @Override - public void setDocumentLocator(Locator locator) - { - if (allowDocumentLocators) + public void setDocumentLocator(Locator locator) + { + if (allowDocumentLocators) { contentHandler.setDocumentLocator(locator); } - } - + } + /** * A processing instruction was parsed. * @@ -267,15 +267,15 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void processingInstruction(String target, String data) - throws SAXException - { - if (allowProcessingInstructions) + public void processingInstruction(String target, String data) + throws SAXException + { + if (allowProcessingInstructions) { contentHandler.processingInstruction(target, data); } - } - + } + /** * A namespace prefix is declared. * @@ -284,15 +284,15 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void startPrefixMapping(String prefix, String uri) - throws SAXException - { - if (allowPrefixMappings) + public void startPrefixMapping(String prefix, String uri) + throws SAXException + { + if (allowPrefixMappings) { contentHandler.startPrefixMapping(prefix, uri); } - } - + } + /** * End of a prefix mapping. * @@ -300,14 +300,14 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void endPrefixMapping(String prefix) throws SAXException - { - if (allowPrefixMappings) + public void endPrefixMapping(String prefix) throws SAXException + { + if (allowPrefixMappings) { contentHandler.endPrefixMapping(prefix); } - } - + } + /** * Start of an element. * @@ -318,34 +318,34 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException - { - if (allowElements) - { - currentElementLevel++; - // check if we are past the minimum level requirement - if (minimumElementLevel < currentElementLevel) - { - if (defaultURI != null && (uri == null || "".equals(uri))) - { - // No namespace provided, use the default namespace. - String prefix = namespaces.getPrefix(defaultURI); - - if (!(prefix == null || "".equals(prefix))) - { - qName = prefix+":"+localName; - } - - contentHandler.startElement(defaultURI, localName, qName, atts); - } - else - { - // let the event pass through unmodified. - contentHandler.startElement(uri, localName, localName, atts); - } - } - } - } + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException + { + if (allowElements) + { + currentElementLevel++; + // check if we are past the minimum level requirement + if (minimumElementLevel < currentElementLevel) + { + if (defaultURI != null && (uri == null || "".equals(uri))) + { + // No namespace provided, use the default namespace. + String prefix = namespaces.getPrefix(defaultURI); + + if (!(prefix == null || "".equals(prefix))) + { + qName = prefix+":"+localName; + } + + contentHandler.startElement(defaultURI, localName, qName, atts); + } + else + { + // let the event pass through unmodified. + contentHandler.startElement(uri, localName, localName, atts); + } + } + } + } /** * End of an element. @@ -356,35 +356,35 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void endElement(String uri, String localName, String qName) - throws SAXException - { - if (allowElements) - { - // check if we are past the minimum level requirements - if (minimumElementLevel < currentElementLevel) - { - if (defaultURI != null && (uri == null || "".equals(uri))) - { - // No namespace provided, use the default namespace. - String prefix = namespaces.getPrefix(defaultURI); - - if (!(prefix == null || "".equals(prefix))) - { - qName = prefix+":"+localName; - } - - contentHandler.endElement(defaultURI, localName, qName); - } - else - { - // Let the event pass through unmodified. - contentHandler.endElement(uri, localName, localName); - } - } - currentElementLevel--; - } - } + public void endElement(String uri, String localName, String qName) + throws SAXException + { + if (allowElements) + { + // check if we are past the minimum level requirements + if (minimumElementLevel < currentElementLevel) + { + if (defaultURI != null && (uri == null || "".equals(uri))) + { + // No namespace provided, use the default namespace. + String prefix = namespaces.getPrefix(defaultURI); + + if (!(prefix == null || "".equals(prefix))) + { + qName = prefix+":"+localName; + } + + contentHandler.endElement(defaultURI, localName, qName); + } + else + { + // Let the event pass through unmodified. + contentHandler.endElement(uri, localName, localName); + } + } + currentElementLevel--; + } + } /** * Ignorable whitespace is recognized. @@ -395,14 +395,14 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void ignorableWhitespace(char[] ch, int start, int length) - throws SAXException - { - if (allowIgnorableWhitespace) + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException + { + if (allowIgnorableWhitespace) { contentHandler.ignorableWhitespace(ch, start, length); } - } + } /** * Recognize a skipped entity. @@ -411,13 +411,13 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void skippedEntity(String name) throws SAXException - { - if (allowSkippedEntities) + public void skippedEntity(String name) throws SAXException + { + if (allowSkippedEntities) { contentHandler.skippedEntity(name); } - } + } /** * Character content. @@ -428,17 +428,17 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void characters(char[] ch, int start, int length) - throws SAXException - { - if (allowCharacters) + public void characters(char[] ch, int start, int length) + throws SAXException + { + if (allowCharacters) { contentHandler.characters(ch, start, length); } - } - - /* - * SAX Lexical events + } + + /* + * SAX Lexical events */ /** @@ -448,17 +448,17 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @param publicId public identifier for the DTD. * @param systemId system identifier for the DTD. * @throws org.xml.sax.SAXException passed through. - */ + */ @Override - public void startDTD(String name, String publicId, String systemId) - throws SAXException - { - if (allowDTDs) + public void startDTD(String name, String publicId, String systemId) + throws SAXException + { + if (allowDTDs) { lexicalHandler.startDTD(name, publicId, systemId); } - } + } /** * End of a DTD declaration. @@ -466,13 +466,13 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void endDTD() throws SAXException - { - if (allowDTDs) + public void endDTD() throws SAXException + { + if (allowDTDs) { lexicalHandler.endDTD(); } - } + } /** * Start of an entity. @@ -481,14 +481,14 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void startEntity(String name) - throws SAXException - { - if (allowEntities) + public void startEntity(String name) + throws SAXException + { + if (allowEntities) { lexicalHandler.startEntity(name); } - } + } /** * End of an entity. @@ -497,14 +497,14 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through */ @Override - public void endEntity(String name) - throws SAXException - { - if (allowEntities) + public void endEntity(String name) + throws SAXException + { + if (allowEntities) { lexicalHandler.endEntity(name); } - } + } /** * Start of character data. @@ -512,14 +512,14 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void startCDATA() - throws SAXException - { - if (allowCDATA) + public void startCDATA() + throws SAXException + { + if (allowCDATA) { lexicalHandler.startCDATA(); } - } + } /** * End of character data. @@ -527,14 +527,14 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void endCDATA() - throws SAXException - { - if (allowCDATA) + public void endCDATA() + throws SAXException + { + if (allowCDATA) { lexicalHandler.endCDATA(); } - } + } /** * XML comment. @@ -545,14 +545,14 @@ public class SAXFilter implements ContentHandler, LexicalHandler * @throws SAXException passed through. */ @Override - public void comment(char[] ch, int start, int length) - throws SAXException - { - if (allowComments) + public void comment(char[] ch, int start, int length) + throws SAXException + { + if (allowComments) { lexicalHandler.comment(ch, start, length); } - } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/opensearch/DiscoveryOpenSearchGenerator.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/opensearch/DiscoveryOpenSearchGenerator.java index bb3be336db..af7c071778 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/opensearch/DiscoveryOpenSearchGenerator.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/opensearch/DiscoveryOpenSearchGenerator.java @@ -48,7 +48,7 @@ import org.xml.sax.*; * @author Nestor Oviedo */ public class DiscoveryOpenSearchGenerator extends AbstractOpenSearchGenerator - implements CacheableProcessingComponent, Recyclable + implements CacheableProcessingComponent, Recyclable { /** the search service to use */ @@ -58,29 +58,33 @@ public class DiscoveryOpenSearchGenerator extends AbstractOpenSearchGenerator * Setup the Discovery search service. Other paramas are setup in superclass's methods */ public void setup(SourceResolver resolver, Map objectModel, String src, - Parameters par) throws ProcessingException, SAXException, IOException + Parameters par) + throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, par); - + searchService = SearchUtils.getSearchService(); - if(searchService == null) + if (searchService == null) + { throw new IllegalStateException("Couldn't get a search service instance"); + } } - + /** * Generate the search results document. */ - public void generate() throws IOException, SAXException, ProcessingException + public void generate() + throws IOException, SAXException, ProcessingException { try { if (resultsDoc == null) { - Context context = ContextUtil.obtainContext(objectModel); + Context context = ContextUtil.obtainContext(objectModel); DiscoverQuery queryArgs = new DiscoverQuery(); - // Sets the query + // Sets the query queryArgs.setQuery(query); // start -1 because Solr indexing starts at 0 and OpenSearch // indexing starts at 1. @@ -88,28 +92,39 @@ public class DiscoveryOpenSearchGenerator extends AbstractOpenSearchGenerator queryArgs.setMaxResults(rpp); // we want Items only - queryArgs.setDSpaceObjectFilter(Constants.ITEM); - + queryArgs.setDSpaceObjectFilter(Constants.ITEM); + // sort info - if(sort != null) + if (sort != null) { - String sortField = this.searchService.toSortFieldIndex(sort.getMetadata(), sort.getType()); - if(SortOption.ASCENDING.equals( sortOrder )) + String sortField = this.searchService.toSortFieldIndex( + sort.getMetadata(), sort.getType()); + if (SortOption.ASCENDING.equals( sortOrder )) + { queryArgs.setSortField(sortField, DiscoverQuery.SORT_ORDER.asc); + } else + { queryArgs.setSortField(sortField, DiscoverQuery.SORT_ORDER.desc); + } } DiscoverResult queryResults = null; - if(scope == null) + if (scope == null) + { queryResults = SearchUtils.getSearchService().search(context, queryArgs); + } else + { queryResults = SearchUtils.getSearchService().search(context, scope, queryArgs); + } - // creates the results array and generates the OpenSearch result - List results = queryResults.getDspaceObjects(); - - resultsDoc = openSearchService.getResultsDoc(context, format, query, (int) queryResults.getTotalSearchResults(), start, rpp, scope, results, FeedUtils.i18nLabels); + // creates the results array and generates the OpenSearch result + List results = queryResults.getDspaceObjects(); + + resultsDoc = openSearchService.getResultsDoc(context, format, + query, (int) queryResults.getTotalSearchResults(), start, + rpp, scope, results, FeedUtils.i18nLabels); FeedUtils.unmangleI18N(resultsDoc); } @@ -118,23 +133,22 @@ public class DiscoveryOpenSearchGenerator extends AbstractOpenSearchGenerator streamer.stream(resultsDoc); } catch (SQLException sqle) - { - throw new SAXException(sqle); - } + { + throw new SAXException(sqle); + } catch (SearchServiceException se) - { - throw new ProcessingException(se); - } + { + throw new ProcessingException(se); + } } - + /** * Recycle */ - + public void recycle() { this.searchService = null; super.recycle(); } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/AuthenticationUtil.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/AuthenticationUtil.java index 5f38f754e6..c2f5d1523a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/AuthenticationUtil.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/AuthenticationUtil.java @@ -37,7 +37,7 @@ import org.dspace.eperson.service.GroupService; * Methods for authenticating the user. This is DSpace platform code, as opposed * to the site-specific authentication code, that resides in implementations of * the org.dspace.eperson.AuthenticationMethod interface. - * + * * @author Scott Phillips * @author Robert Tansley */ @@ -52,7 +52,7 @@ public class AuthenticationUtil */ public static final String REQUEST_INTERRUPTED = "dspace.request.interrupted"; public static final String REQUEST_RESUME = "dspace.request.resume"; - + /** * These store a message giving a reason for why the request is being interrupted. */ @@ -60,15 +60,15 @@ public class AuthenticationUtil public static final String REQUEST_INTERRUPTED_MESSAGE = "dspace.request.interrupted.message"; public static final String REQUEST_INTERRUPTED_CHARACTERS = "dspace.request.interrupted.characters"; - + /** * The IP address this user first logged in from, do not allow this session for * other IP addresses. */ private static final String CURRENT_IP_ADDRESS = "dspace.user.ip"; - + /** - * The effective user id, typically this will never change. However, if an administrator + * The effective user id, typically this will never change. However, if an administrator * has assumed login as this user then they will differ. */ private static final String EFFECTIVE_USER_ID = "dspace.user.effective"; @@ -83,7 +83,7 @@ public class AuthenticationUtil * Authenticate the current DSpace content based upon given authentication * credentials. The AuthenticationManager will consult the configured * authentication stack to determine the best method. - * + * * @param objectModel * Cocoon's object model. * @param email @@ -98,11 +98,11 @@ public class AuthenticationUtil * @throws java.sql.SQLException passed through. */ public static Context authenticate(Map objectModel, String email, String password, String realm) - throws SQLException + throws SQLException { // Get the real HttpRequest HttpServletRequest request = (HttpServletRequest) objectModel - .get(HttpEnvironment.HTTP_REQUEST_OBJECT); + .get(HttpEnvironment.HTTP_REQUEST_OBJECT); Context context = ContextUtil.obtainContext(objectModel); int implicitStatus = authenticationService.authenticateImplicit( @@ -118,21 +118,21 @@ public class AuthenticationUtil // If implicit authentication failed, fall over to explicit. int explicitStatus = authenticationService.authenticate(context, - email, password, realm, request); + email, password, realm, request); if (explicitStatus == AuthenticationMethod.SUCCESS) { // Logged in OK. log.info(LogManager - .getHeader(context, "login", "type=explicit")); + .getHeader(context, "login", "type=explicit")); AuthenticationUtil.logIn(context, request, context - .getCurrentUser()); + .getCurrentUser()); } else { log.info(LogManager.getHeader(context, "failed_login", "email=" - + email + ", realm=" + realm + ", result=" - + explicitStatus)); + + email + ", realm=" + realm + ", result=" + + explicitStatus)); } } @@ -145,7 +145,7 @@ public class AuthenticationUtil * this session. If the attempt was successful then the returned context * will have an eperson attached other wise the context will not have an * eperson attached. - * + * * @param objectModel * Cocoon's object model. * @return This requests DSpace context. @@ -156,11 +156,11 @@ public class AuthenticationUtil { // Get the real HttpRequest final HttpServletRequest request = (HttpServletRequest) objectModel - .get(HttpEnvironment.HTTP_REQUEST_OBJECT); + .get(HttpEnvironment.HTTP_REQUEST_OBJECT); Context context = ContextUtil.obtainContext(objectModel); int implicitStatus = authenticationService.authenticateImplicit( - context, null, null, null, request); + context, null, null, null, request); if (implicitStatus == AuthenticationMethod.SUCCESS) { @@ -172,9 +172,9 @@ public class AuthenticationUtil } /** - * Log the given user in as a real authenticated user. This should only be used after - * a user has presented credentials and they have been validated. - * + * Log the given user in as a real authenticated user. This should only be used after + * a user has presented credentials and they have been validated. + * * @param context * DSpace context * @param request @@ -183,13 +183,14 @@ public class AuthenticationUtil * the eperson logged in */ private static void logIn(Context context, HttpServletRequest request, - EPerson eperson) throws SQLException + EPerson eperson) + throws SQLException { if (eperson == null) { return; } - + HttpSession session = request.getSession(); context.setCurrentUser(eperson); @@ -197,11 +198,11 @@ public class AuthenticationUtil // Check to see if systemwide alerts is restricting sessions if (!authorizeService.isAdmin(context) && !SystemwideAlerts.canUserStartSession()) { - // Do not allow this user to login because sessions are being restricted by a systemwide alert. - context.setCurrentUser(null); - return; + // Do not allow this user to login because sessions are being restricted by a systemwide alert. + context.setCurrentUser(null); + return; } - + // Set any special groups - invoke the authentication manager. List groups = authenticationService.getSpecialGroups(context, request); @@ -213,36 +214,37 @@ public class AuthenticationUtil // and the remote IP address to compare against later requests // so we can detect session hijacking. session.setAttribute(CURRENT_IP_ADDRESS, request.getRemoteAddr()); - + // Set both the effective and authenticated user to the same. session.setAttribute(EFFECTIVE_USER_ID, eperson.getID()); session.setAttribute(AUTHENTICATED_USER_ID,eperson.getID()); - + } - + /** - * Log the given user in as a real authenticated user. This should only be used after - * a user has presented credentials and they have been validated. This method + * Log the given user in as a real authenticated user. This should only be used after + * a user has presented credentials and they have been validated. This method * signature is provided to be easier to call from flow scripts. - * - * @param objectModel - * The cocoon object model. + * + * @param objectModel + * The cocoon object model. * @param eperson * the eperson logged in * @throws java.sql.SQLException passed through. */ - public static void logIn(Map objectModel, EPerson eperson) throws SQLException + public static void logIn(Map objectModel, EPerson eperson) + throws SQLException { final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); Context context = ContextUtil.obtainContext(objectModel); - + logIn(context,request,eperson); } /** - * Check to see if there are any session attributes indicating a currently authenticated + * Check to see if there are any session attributes indicating a currently authenticated * user. If there is then log this user in. - * + * * @param context * DSpace context * @param request @@ -258,7 +260,7 @@ public class AuthenticationUtil { UUID id = (UUID) session.getAttribute(EFFECTIVE_USER_ID); UUID realid = (UUID) session.getAttribute(AUTHENTICATED_USER_ID); - + if (id != null) { // Should we check for an ip match from the start of the request to now? @@ -269,23 +271,22 @@ public class AuthenticationUtil { EPerson eperson = ePersonService.find(context, id); context.setCurrentUser(eperson); - + // Check to see if systemwide alerts is restricting sessions if (!authorizeService.isAdmin(context) && !SystemwideAlerts.canUserMaintainSession()) { - // Normal users can not maintain their sessions, check to see if this is really an - // administrator logging in as someone else. - - EPerson realEPerson = ePersonService.find(context, realid); - Group administrators = groupService.findByName(context, Group.ADMIN); - if (!groupService.isDirectMember(administrators, realEPerson)) - { - // Log this user out because sessions are being restricted by a systemwide alert. - context.setCurrentUser(null); - return; - } + // Normal users can not maintain their sessions, check to see if this is really an + // administrator logging in as someone else. + + EPerson realEPerson = ePersonService.find(context, realid); + Group administrators = groupService.findByName(context, Group.ADMIN); + if (!groupService.isDirectMember(administrators, realEPerson)) + { + // Log this user out because sessions are being restricted by a systemwide alert. + context.setCurrentUser(null); + return; + } } - // Set any special groups - invoke the authentication mgr. List groups = authenticationService.getSpecialGroups(context, request); @@ -306,97 +307,98 @@ public class AuthenticationUtil /** * Assume the login as another user. Only site administrators may perform the action. - * + * * @param context - * The current DSpace context logged in as a site administrator + * The current DSpace context logged in as a site administrator * @param request - * The real HTTP request. + * The real HTTP request. * @param loginAs - * Whom to login as. + * Whom to login as. * @throws SQLException passed through. * @throws AuthorizeException using an I18nTransformer key as the message */ - public static void loginAs(Context context, HttpServletRequest request, EPerson loginAs ) + public static void loginAs(Context context, HttpServletRequest request, EPerson loginAs ) throws SQLException, AuthorizeException { - // Only allow loginAs if the administrator has allowed it. - if (!DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.user.assumelogin", false)) + // Only allow loginAs if the administrator has allowed it. + if (!DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("webui.user.assumelogin", false)) { return; } - - // Only super administrators can login as someone else. - if (!authorizeService.isAdmin(context)) + + // Only super administrators can login as someone else. + if (!authorizeService.isAdmin(context)) { throw new AuthorizeException("xmlui.utils.AuthenticationUtil.onlyAdmins"); } - - // Just to be double be sure, make sure the administrator - // is the one who actually authenticated himself. - HttpSession session = request.getSession(false); + + // Just to be double be sure, make sure the administrator + // is the one who actually authenticated himself. + HttpSession session = request.getSession(false); UUID authenticatedID = (UUID) session.getAttribute(AUTHENTICATED_USER_ID); - if (!context.getCurrentUser().getID().equals(authenticatedID)) + if (!context.getCurrentUser().getID().equals(authenticatedID)) { throw new AuthorizeException("xmlui.utils.AuthenticationUtil.onlyAuthenticatedAdmins"); } - - // You may not assume the login of another super administrator - if (loginAs == null) + + // You may not assume the login of another super administrator + if (loginAs == null) { return; } - Group administrators = groupService.findByName(context, Group.ADMIN); - if (groupService.isDirectMember(administrators, loginAs)) + Group administrators = groupService.findByName(context, Group.ADMIN); + if (groupService.isDirectMember(administrators, loginAs)) { throw new AuthorizeException("xmlui.utils.AuthenticationUtil.notAnotherAdmin"); } - - // Success, allow the user to login as another user. - context.setCurrentUser(loginAs); - + + // Success, allow the user to login as another user. + context.setCurrentUser(loginAs); + // Set any special groups - invoke the authentication mgr. List groups = authenticationService.getSpecialGroups(context, request); for (Group group : groups) { context.setSpecialGroup(group.getID()); } - + // Set both the effective and authenticated user to the same. session.setAttribute(EFFECTIVE_USER_ID, loginAs.getID()); } - - + + /** * Log the user out. - * + * * @param context * DSpace context * @param request * HTTP request * @throws java.sql.SQLException passed through. */ - public static void logOut(Context context, HttpServletRequest request) throws SQLException + public static void logOut(Context context, HttpServletRequest request) + throws SQLException { HttpSession session = request.getSession(); if (session.getAttribute(EFFECTIVE_USER_ID) != null && - session.getAttribute(AUTHENTICATED_USER_ID) != null) + session.getAttribute(AUTHENTICATED_USER_ID) != null) { - UUID effectiveID = (UUID) session.getAttribute(EFFECTIVE_USER_ID); - UUID authenticatedID = (UUID) session.getAttribute(AUTHENTICATED_USER_ID); - - if (!effectiveID.equals(authenticatedID)) - { - // The user has login in as another user, instead of logging them out, - // revert back to their previous login name. - - EPerson authenticatedUser = ePersonService.find(context, authenticatedID); - context.setCurrentUser(authenticatedUser); - session.setAttribute(EFFECTIVE_USER_ID, authenticatedID); - return; - } + UUID effectiveID = (UUID) session.getAttribute(EFFECTIVE_USER_ID); + UUID authenticatedID = (UUID) session.getAttribute(AUTHENTICATED_USER_ID); + + if (!effectiveID.equals(authenticatedID)) + { + // The user has login in as another user, instead of logging them out, + // revert back to their previous login name. + + EPerson authenticatedUser = ePersonService.find(context, authenticatedID); + context.setCurrentUser(authenticatedUser); + session.setAttribute(EFFECTIVE_USER_ID, authenticatedID); + return; + } } - + // Otherwise, just log the person out as normal. context.setCurrentUser(null); session.removeAttribute(EFFECTIVE_USER_ID); @@ -407,7 +409,7 @@ public class AuthenticationUtil /** * Determine if the email can register itself or needs to be * created by a site administrator first. - * + * * @param objectModel * The Cocoon object model * @param email @@ -415,11 +417,12 @@ public class AuthenticationUtil * @return true if the email can register, otherwise false. * @throws java.sql.SQLException passed through. */ - public static boolean canSelfRegister(Map objectModel, String email) throws SQLException + public static boolean canSelfRegister(Map objectModel, String email) + throws SQLException { final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); Context context = ContextUtil.obtainContext(objectModel); - + if (SystemwideAlerts.canUserStartSession()) { return authenticationService.canSelfRegister(context, request, email); @@ -430,11 +433,11 @@ public class AuthenticationUtil return false; } } - + /** * Determine if the EPerson (to be created or already created) has the * ability to set their own password. - * + * * @param objectModel * The Cocoon object model * @param email @@ -443,19 +446,19 @@ public class AuthenticationUtil * @throws java.sql.SQLException passed through. */ public static boolean allowSetPassword(Map objectModel, String email) - throws SQLException + throws SQLException { final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); Context context = ContextUtil.obtainContext(objectModel); - + return authenticationService.allowSetPassword(context, request, email); } - + /** * Construct a new, mostly blank, eperson for the given email address. * This should only be called once the email address has been verified. - * - * @param objectModel + * + * @param objectModel * The Cocoon object model. * @param email * The email address of the new eperson. @@ -463,12 +466,12 @@ public class AuthenticationUtil * @throws java.sql.SQLException passed through. * @throws org.dspace.authorize.AuthorizeException passed through. */ - public static EPerson createNewEperson(Map objectModel, String email) throws - SQLException, AuthorizeException + public static EPerson createNewEperson(Map objectModel, String email) + throws SQLException, AuthorizeException { - final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); Context context = ContextUtil.obtainContext(objectModel); - + // Need to create new eperson // FIXME: TEMPORARILY need to turn off authentication, as usually // only site admins can create e-people @@ -479,42 +482,42 @@ public class AuthenticationUtil eperson.setSelfRegistered(true); ePersonService.update(context, eperson); context.restoreAuthSystemState(); - + // Give site auth a chance to set/override appropriate fields authenticationService.initEPerson(context, request, eperson); - - return eperson; + + return eperson; } /** * Is there a currently interrupted request? - * + * * @param objectModel The Cocoon object Model * @return true if there is an interrupted or un-resumed request. */ - public static boolean isInterupptedRequest(Map objectModel) + public static boolean isInterupptedRequest(Map objectModel) { - final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + final HttpServletRequest request = (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); - HttpSession session = request.getSession(); - - Object interruptedObject = session.getAttribute(REQUEST_INTERRUPTED); - - if (interruptedObject instanceof RequestInfo) - { - // There is currently either an interrupted or yet-to-be resumed request. - return true; - } - - // There are not interrupted requests. - return false; + HttpSession session = request.getSession(); + + Object interruptedObject = session.getAttribute(REQUEST_INTERRUPTED); + + if (interruptedObject instanceof RequestInfo) + { + // There is currently either an interrupted or yet-to-be resumed request. + return true; + } + + // There are not interrupted requests. + return false; } /** * Interrupt the current request and store if for later resumption. This * request will send an HTTP redirect telling the client to authenticate * first. Once that has been finished then the request can be resumed. - * + * * @param objectModel The Cocoon object Model * @param header A message header (i18n tag) * @param message A message for why the request was interrupted (i18n tag) @@ -522,109 +525,110 @@ public class AuthenticationUtil */ public static void interruptRequest(Map objectModel, String header, String message, String characters) { - final HttpServletRequest request = - (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + final HttpServletRequest request = + (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + + HttpSession session = request.getSession(); - HttpSession session = request.getSession(); - // Store this interrupted request until after the user successfully authenticates. RequestInfo interruptedRequest = new RequestInfo(request); - + // Set the request as interrupted session.setAttribute(REQUEST_INTERRUPTED,interruptedRequest); session.setAttribute(REQUEST_RESUME, null); // just to be clear. - + // Set the interrupt message session.setAttribute(REQUEST_INTERRUPTED_HEADER, header); session.setAttribute(REQUEST_INTERRUPTED_MESSAGE, message); session.setAttribute(REQUEST_INTERRUPTED_CHARACTERS, characters); - - } - - + + /** * Set the interrupted request to a resumable state. The * next request that the server receives (for this session) that * has the same servletPath will be replaced with the previously * interrupted request. - * + * * @param objectModel The Cocoon object Model * @return null. */ public static String resumeInterruptedRequest(Map objectModel) { - final HttpServletRequest request = - (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + final HttpServletRequest request = + (HttpServletRequest) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT); + + HttpSession session = request.getSession(); + + // Clear the interrupt message + session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER, null); + session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE, null); + session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS, null); - HttpSession session = request.getSession(); - - // Clear the interrupt message - session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_HEADER, null); - session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_MESSAGE, null); - session.setAttribute(AuthenticationUtil.REQUEST_INTERRUPTED_CHARACTERS, null); - // Set the request as interrupted Object interruptedObject = session.getAttribute(REQUEST_INTERRUPTED); if (interruptedObject instanceof RequestInfo) { - RequestInfo interruptedRequest = (RequestInfo) interruptedObject; - - session.setAttribute(REQUEST_INTERRUPTED, null); - session.setAttribute(REQUEST_RESUME, interruptedRequest); - - // Return the path for which this request belongs too. Only URLs - // for this path may be resumed. - if (interruptedRequest.getServletPath() == null || interruptedRequest.getServletPath().length() == 0) { + RequestInfo interruptedRequest = (RequestInfo) interruptedObject; + + session.setAttribute(REQUEST_INTERRUPTED, null); + session.setAttribute(REQUEST_RESUME, interruptedRequest); + + // Return the path for which this request belongs too. Only URLs + // for this path may be resumed. + if (interruptedRequest.getServletPath() == null || interruptedRequest.getServletPath().length() == 0) + { return interruptedRequest.getActualPath(); - } else { - return interruptedRequest.getServletPath(); + } + else + { + return interruptedRequest.getServletPath(); } } - + // No request was interrupted. return null; } - - - + + + /** * Check to see if this request should be resumed. - * + * * @param realHttpRequest The current real request * @return Either the current real request or a stored request that was previously interrupted. */ - public static HttpServletRequest resumeRequest(HttpServletRequest realHttpRequest) + public static HttpServletRequest resumeRequest(HttpServletRequest realHttpRequest) { - // First check to see if there is a resumed request. - HttpSession session = realHttpRequest.getSession(); - //session.setMaxInactiveInterval(60); + // First check to see if there is a resumed request. + HttpSession session = realHttpRequest.getSession(); + //session.setMaxInactiveInterval(60); Object object = session.getAttribute(REQUEST_RESUME); - - // Next check to make sure it's the right type of object, - // there should be no condition where it is not - but always + + // Next check to make sure it's the right type of object, + // there should be no condition where it is not - but always // safe to check. if (object instanceof RequestInfo) { - RequestInfo interruptedRequest = (RequestInfo) object; - - // Next, check to make sure this real request if for the same URL - // path, if so then resume the previous request. - String interruptedServletPath = interruptedRequest.getServletPath(); - String realServletPath = realHttpRequest.getServletPath(); - - if (realServletPath != null && - realServletPath.equals(interruptedServletPath)) - { - // Clear the resumed request and send the request back to be resumed. - session.setAttribute(REQUEST_INTERRUPTED, null); - session.setAttribute(REQUEST_RESUME, null); - - return interruptedRequest.wrapRequest(realHttpRequest); - } + RequestInfo interruptedRequest = (RequestInfo) object; + + // Next, check to make sure this real request if for the same URL + // path, if so then resume the previous request. + String interruptedServletPath = interruptedRequest.getServletPath(); + String realServletPath = realHttpRequest.getServletPath(); + + if (realServletPath != null && + realServletPath.equals(interruptedServletPath)) + { + // Clear the resumed request and send the request back to be resumed. + session.setAttribute(REQUEST_INTERRUPTED, null); + session.setAttribute(REQUEST_RESUME, null); + + return interruptedRequest.wrapRequest(realHttpRequest); + } } - // Otherwise return the real request. - return realHttpRequest; + // Otherwise return the real request. + return realHttpRequest; } /** diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/ContextUtil.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/ContextUtil.java index e702a7bf15..b4bbb5396b 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/ContextUtil.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/ContextUtil.java @@ -54,7 +54,8 @@ public class ContextUtil * @return a context object * @throws java.sql.SQLException passed through. */ - public static Context obtainContext(Map objectModel) throws SQLException + public static Context obtainContext(Map objectModel) + throws SQLException { return obtainContext(ObjectModelHelper.getRequest(objectModel)); } @@ -66,13 +67,13 @@ public class ContextUtil * @return True if a context has previously been created, false otherwise. */ public static boolean isContextAvailable(Map objectModel) { - Request request = ObjectModelHelper.getRequest(objectModel); - Object object = request.getAttribute(DSPACE_CONTEXT); - - if (object instanceof Context) - return true; - else - return false; + Request request = ObjectModelHelper.getRequest(objectModel); + Object object = request.getAttribute(DSPACE_CONTEXT); + + if (object instanceof Context) + return true; + else + return false; } /** @@ -85,7 +86,8 @@ public class ContextUtil * @return a context object * @throws java.sql.SQLException passed through. */ - public static Context obtainContext(HttpServletRequest request) throws SQLException + public static Context obtainContext(HttpServletRequest request) + throws SQLException { Context context = (Context) request.getAttribute(DSPACE_CONTEXT); @@ -114,17 +116,17 @@ public class ContextUtil if (useProxies == null) { useProxies = DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("useProxies", false); } - if(useProxies && request.getHeader("X-Forwarded-For") != null) + if (useProxies && request.getHeader("X-Forwarded-For") != null) { /* This header is a comma delimited list */ - for(String xfip : request.getHeader("X-Forwarded-For").split(",")) + for (String xfip : request.getHeader("X-Forwarded-For").split(",")) { - if(!request.getHeader("X-Forwarded-For").contains(ip)) + if (!request.getHeader("X-Forwarded-For").contains(ip)) { ip = xfip.trim(); } } - } + } context.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip); // Store the context in the request @@ -141,21 +143,22 @@ public class ContextUtil * The request object * @throws javax.servlet.ServletException on failure. */ - public static void completeContext(HttpServletRequest request) throws ServletException + public static void completeContext(HttpServletRequest request) + throws ServletException { - Context context = (Context) request.getAttribute(DSPACE_CONTEXT); + Context context = (Context) request.getAttribute(DSPACE_CONTEXT); - if (context != null && context.isValid()) - { - try - { - context.complete(); - } - catch (SQLException e) - { - throw new ServletException(e); - } - } + if (context != null && context.isValid()) + { + try + { + context.complete(); + } + catch (SQLException e) + { + throw new ServletException(e); + } + } } /** @@ -163,14 +166,13 @@ public class ContextUtil * * @param request the request to be aborted. */ - public static void abortContext(HttpServletRequest request) - { - Context context = (Context) request.getAttribute(DSPACE_CONTEXT); - - if (context != null && context.isValid()) - { - context.abort(); - } - } + public static void abortContext(HttpServletRequest request) + { + Context context = (Context) request.getAttribute(DSPACE_CONTEXT); + if (context != null && context.isValid()) + { + context.abort(); + } + } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/DSpaceValidity.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/DSpaceValidity.java index 2ead3817e3..922ca6efe9 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/DSpaceValidity.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/DSpaceValidity.java @@ -23,56 +23,56 @@ import org.dspace.eperson.EPerson; import org.dspace.eperson.Group; /** - * This is a validity object specifically implemented for the caching + * This is a validity object specifically implemented for the caching * needs of DSpace, Manakin, and Cocoon. - * + * *

    The basic idea is that, each time a DSpace object is rendered by a Cocoon * component, the object and everything about it that makes it unique should - * be reflected in the validity object for the component. By following this + * be reflected in the validity object for the component. By following this * principle, if the object has been updated externally then the cache will be * invalidated. - * + * *

    This DSpaceValidity object makes this processes easier by abstracting out * the processes of determining what is unique about a DSpace object. A class - * is expected to create a new DSpaceValidity object and add() to it all - * DSpaceObjects that are rendered by the component. This validity object will + * is expected to create a new DSpaceValidity object and add() to it all + * DSpaceObjects that are rendered by the component. This validity object will * serialize all those objects to a string, take a hash of the string and compare * the hash of the string for any updates. - * + * * @author Scott Phillips */ public class DSpaceValidity implements SourceValidity { - + private static final long serialVersionUID = 1L; - + /** The validityKey while it is being build, once it is completed. */ protected StringBuffer validityKey; - + /** Simple flag to note if the object has been completed. */ protected boolean completed = false; - + /** A hash of the validityKey taken after completion */ protected long hash; - + /** The time when the validity is no longer assumed to be valid */ protected long assumedValidityTime = 0; - + /** The length of time that a cache is assumed to be valid */ protected long assumedValidityDelay = 0; transient protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); - transient protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); + transient protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); transient protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); /** - * Create a new DSpace validity object. - * + * Create a new DSpace validity object. + * * @param initialValidityKey - * The initial string + * The initial string */ public DSpaceValidity(String initialValidityKey) { @@ -88,136 +88,136 @@ public class DSpaceValidity implements SourceValidity { this(null); } - + /** * Complete this validity object. After the completion no more * objects may be added to the validity object and the object * will return as valid. * @return this. */ - public DSpaceValidity complete() - { + public DSpaceValidity complete() + { this.completed = true; this.hash = HashUtil.hash(validityKey); this.validityKey = null; - + // Set the forced validity time. if (assumedValidityDelay > 0) { resetAssumedValidityTime(); } - + return this; } - + /** - * Set the time delay for how long this cache will be assumed + * Set the time delay for how long this cache will be assumed * to be valid. When it is assumed valid no other checks will be - * made to consider its validity, and once the time has expired - * a full validation will occur on the next cache hit. If the - * cache proves to be validated on this hit then the assumed + * made to consider its validity, and once the time has expired + * a full validation will occur on the next cache hit. If the + * cache proves to be validated on this hit then the assumed * validity timer is reset. - * + * * @param milliseconds The delay time in millieseconds. */ public void setAssumedValidityDelay(long milliseconds ) { - // record the delay time. - this.assumedValidityDelay = milliseconds; - - // Also add the delay time to the validity hash so if the - // admin changes the delay time then all the previous caches - // are invalidated. - this.validityKey.append("AssumedValidityDelay:").append(milliseconds); + // record the delay time. + this.assumedValidityDelay = milliseconds; + + // Also add the delay time to the validity hash so if the + // admin changes the delay time then all the previous caches + // are invalidated. + this.validityKey.append("AssumedValidityDelay:").append(milliseconds); } - + /** * Set the time delay for how long this cache will be assumed to be valid. - * + * *

    This method takes a string which is parsed for the delay time. The string * must be of the following form: "{@code }" where scale is days, * hours, minutes, or seconds. - * + * *

    Examples: "1 day" or "12 hours" or "1 hour" or "30 minutes" - * + * * @see #setAssumedValidityDelay(long) - * + * * @param delay The delay time in a variable scale. */ public void setAssumedValidityDelay(String delay) { - if (delay == null || delay.length() == 0) + if (delay == null || delay.length() == 0) { return; } - - String[] parts = delay.split(" "); - - if (parts == null || parts.length != 2) + + String[] parts = delay.split(" "); + + if (parts == null || parts.length != 2) { throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \"" + delay + "\". All delays must be of the form \" \" where scale is either seconds, minutes, hours, or days."); } - long milliseconds = 0; - - long value = 0; - try { value = Long.valueOf(parts[0]); } - catch (NumberFormatException nfe) { - throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \""+delay+"\". All delays must be of the form \" \" where scale is either seconds, minutes, hours, or days.",nfe); - } - - String scale = parts[1].toLowerCase(); - - if (scale.equals("weeks") || scale.equals("week")) - { - // milliseconds * seconds * minutes * hours * days * weeks - // 1000 * 60 * 60 * 24 * 7 * 1 = 604,800,000 - milliseconds = value * 604800000; - } - else if (scale.equals("days") || scale.equals("day")) - { - // milliseconds * seconds * minutes * hours * days - // 1000 * 60 * 60 * 24 * 1 = 86,400,000 - milliseconds = value * 86400000; - } - else if (scale.equals("hours") || scale.equals("hour")) - { - // milliseconds * seconds * minutes * hours - // 1000 * 60 * 60 * 1 = 3,600,000 - milliseconds = value * 3600000; - } - else if (scale.equals("minutes") || scale.equals("minute")) - { - // milliseconds * second * minute - // 1000 * 60 * 1 = 60,000 - milliseconds = value * 60000; - } - else if (scale.equals("seconds") || scale.equals("second")) - { - // milliseconds * second - // 1000 * 1 = 1000 - milliseconds = value * 1000; - } - else - { - throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \""+delay+"\". All delays must be of the form \" \" where scale is either seconds, minutes, hours, or days."); + long milliseconds = 0; + + long value = 0; + try { value = Long.valueOf(parts[0]); } + catch (NumberFormatException nfe) { + throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \""+delay+"\". All delays must be of the form \" \" where scale is either seconds, minutes, hours, or days.",nfe); } - - // Now set the actual delay. - setAssumedValidityDelay(milliseconds); + + String scale = parts[1].toLowerCase(); + + if (scale.equals("weeks") || scale.equals("week")) + { + // milliseconds * seconds * minutes * hours * days * weeks + // 1000 * 60 * 60 * 24 * 7 * 1 = 604,800,000 + milliseconds = value * 604800000; + } + else if (scale.equals("days") || scale.equals("day")) + { + // milliseconds * seconds * minutes * hours * days + // 1000 * 60 * 60 * 24 * 1 = 86,400,000 + milliseconds = value * 86400000; + } + else if (scale.equals("hours") || scale.equals("hour")) + { + // milliseconds * seconds * minutes * hours + // 1000 * 60 * 60 * 1 = 3,600,000 + milliseconds = value * 3600000; + } + else if (scale.equals("minutes") || scale.equals("minute")) + { + // milliseconds * second * minute + // 1000 * 60 * 1 = 60,000 + milliseconds = value * 60000; + } + else if (scale.equals("seconds") || scale.equals("second")) + { + // milliseconds * second + // 1000 * 1 = 1000 + milliseconds = value * 1000; + } + else + { + throw new IllegalArgumentException("Error unable to parse the assumed validity delay time: \""+delay+"\". All delays must be of the form \" \" where scale is either seconds, minutes, hours, or days."); + } + + // Now set the actual delay. + setAssumedValidityDelay(milliseconds); } - - + + /** - * Add a DSpace object to the validity. The order in which objects - * are added to the validity object is important, ensure that - * objects are added in the *exact* same order each time a + * Add a DSpace object to the validity. The order in which objects + * are added to the validity object is important, ensure that + * objects are added in the *exact* same order each time a * validity object is created. - * - * Below are the following transitive rules for adding + * + * Below are the following transitive rules for adding * objects, i.e. if an item is added then all the item's * bundles and bitstreams will also be added. - * + * *

    * {@literal Communities -> logo bitstream} *
    @@ -228,7 +228,7 @@ public class DSpaceValidity implements SourceValidity * {@literal Bundles -> bitstreams} *
    * {@literal EPeople -> groups} - * + * * @param context * session context. * @param dso @@ -241,10 +241,10 @@ public class DSpaceValidity implements SourceValidity { throw new IllegalStateException("Cannot add DSpaceObject to a completed validity object"); } - - if (dso == null) + + if (dso == null) { - this.validityKey.append("null"); + this.validityKey.append("null"); } else if (dso instanceof Community) { @@ -257,15 +257,15 @@ public class DSpaceValidity implements SourceValidity validityKey.append(communityService.getMetadata(community, "side_bar_text")); validityKey.append(communityService.getMetadata(community, "copyright_text")); validityKey.append(communityService.getMetadata(community, "name")); - + // Add the communities logo this.add(context, community.getLogo()); - } + } else if (dso instanceof Collection) { Collection collection = (Collection) dso; - + validityKey.append("Collection:"); validityKey.append(collection.getHandle()); validityKey.append(collectionService.getMetadata(collection, "introductory_text")); @@ -274,18 +274,18 @@ public class DSpaceValidity implements SourceValidity validityKey.append(collectionService.getMetadata(collection, "provenance_description")); validityKey.append(collectionService.getMetadata(collection, "copyright_text")); validityKey.append(collectionService.getMetadata(collection, "license")); - validityKey.append(collectionService.getMetadata(collection, "name")); - + validityKey.append(collectionService.getMetadata(collection, "name")); + // Add the logo also; this.add(context, collection.getLogo()); - + } else if (dso instanceof Item) { Item item = (Item) dso; - + validityKey.append("Item:"); - validityKey.append(item.getHandle()); + validityKey.append(item.getHandle()); validityKey.append(item.getOwningCollection()); validityKey.append(item.getLastModified()); // Include all metadata values in the validity key. @@ -296,7 +296,7 @@ public class DSpaceValidity implements SourceValidity validityKey.append(dcv.getLanguage()).append("="); validityKey.append(dcv.getValue()); } - + for(Bundle bundle : item.getBundles()) { // Add each of the items bundles & bitstreams. @@ -306,13 +306,13 @@ public class DSpaceValidity implements SourceValidity else if (dso instanceof Bundle) { Bundle bundle = (Bundle) dso; - + validityKey.append("Bundle:"); validityKey.append(bundle.getID()); validityKey.append(bundle.getName()); validityKey.append(bundle.getPrimaryBitstream() != null ? bundle.getPrimaryBitstream().getID() : ""); - - for(Bitstream bitstream : bundle.getBitstreams()) + + for (Bitstream bitstream : bundle.getBitstreams()) { this.add(context, bitstream); } @@ -320,7 +320,7 @@ public class DSpaceValidity implements SourceValidity else if (dso instanceof Bitstream) { Bitstream bitstream = (Bitstream) dso; - + validityKey.append("Bundle:"); validityKey.append(bitstream.getID()); validityKey.append(bitstream.getSequenceID()); @@ -336,7 +336,7 @@ public class DSpaceValidity implements SourceValidity else if (dso instanceof EPerson) { EPerson eperson = (EPerson) dso; - + validityKey.append("Bundle:"); validityKey.append(eperson.getID()); validityKey.append(eperson.getEmail()); @@ -349,23 +349,23 @@ public class DSpaceValidity implements SourceValidity else if (dso instanceof Group) { Group group = (Group) dso; - + validityKey.append("Group:"); - + validityKey.append(group.getID()); validityKey.append(group.getName()); } else { throw new IllegalArgumentException("DSpaceObject of type '"+dso.getClass().getName()+"' is not supported by the DSpaceValidity object."); - } + } } - + /** - * Add a non-DSpaceObject to the validity, the object should be - * serialized into a string form. The order in which objects - * are added to the validity object is important, ensure that - * objects are added in the *exact* same order each time a + * Add a non-DSpaceObject to the validity, the object should be + * serialized into a string form. The order in which objects + * are added to the validity object is important, ensure that + * objects are added in the *exact* same order each time a * validity object is created. * * @param nonDSpaceObject @@ -380,29 +380,29 @@ public class DSpaceValidity implements SourceValidity /** * This method is used during serialization. When Tomcat is shutdown, Cocoon's in-memory - * cache is serialized and written to disk to later be read back into memory on start - * up. When this class is read back into memory the readObject(stream) method will be + * cache is serialized and written to disk to later be read back into memory on start + * up. When this class is read back into memory the readObject(stream) method will be * called. * - * This method will re-read the serialization back into memory but it will then set + * This method will re-read the serialization back into memory but it will then set * the assume validity time to zero. This means the next cache hit after a server startup * will never be assumed valid. Only after it has been checked once will the regular assume * validity mechanism be used. - * + * * @param in stream for reading serialized data. * @throws IOException passed through. * @throws ClassNotFoundException passed through. */ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - // Read in this object as normal. - in.defaultReadObject(); - - // After reading from serialization do not assume validity anymore until it - // has been checked at least once. - this.assumedValidityTime = 0; + // Read in this object as normal. + in.defaultReadObject(); + + // After reading from serialization do not assume validity anymore until it + // has been checked at least once. + this.assumedValidityTime = 0; } - + /** * Reset the assume validity time. This should be called only when the validity of this cache * has been confirmed to be accurate. This will reset the assume valid timer based upon the @@ -410,9 +410,9 @@ public class DSpaceValidity implements SourceValidity */ private void resetAssumedValidityTime() { - this.assumedValidityTime = System.currentTimeMillis() + this.assumedValidityDelay; + this.assumedValidityTime = System.currentTimeMillis() + this.assumedValidityDelay; } - + /** * Determine if the cache is still valid * @return {@link org.apache.excalibur.source.SourceValidity#VALID}, @@ -425,32 +425,32 @@ public class DSpaceValidity implements SourceValidity // Return true if we have a hash. if (this.completed) { - // Check if we are configured to assume validity for a period of time. - if (this.assumedValidityDelay > 0) - { - // Check if we should assume validitity. - if (System.currentTimeMillis() < this.assumedValidityTime) - { - // Assume the cache is valid without rechecking another validity object. - return SourceValidity.VALID; - } - } - - return SourceValidity.UNKNOWN; + // Check if we are configured to assume validity for a period of time. + if (this.assumedValidityDelay > 0) + { + // Check if we should assume validitity. + if (System.currentTimeMillis() < this.assumedValidityTime) + { + // Assume the cache is valid without rechecking another validity object. + return SourceValidity.VALID; + } + } + + return SourceValidity.UNKNOWN; } else { - // This is an error state. We are being asked whether we are valid before - // we have been initialized. + // This is an error state. We are being asked whether we are valid before + // we have been initialized. return SourceValidity.INVALID; } } /** - * Determine if the cache is still valid based + * Determine if the cache is still valid based * upon the other validity object. - * - * @param otherObject + * + * @param otherObject * The other validity object. * @return {@link org.apache.excalibur.source.SourceValidity#VALID} * or {@link org.apache.excalibur.source.SourceValidity#INVALID}. diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestInfo.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestInfo.java index 640c3621ab..3d1e4a2192 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestInfo.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestInfo.java @@ -18,64 +18,64 @@ import javax.servlet.http.HttpServletRequestWrapper; /** * Stores information about an HTTP request. This is used so that the request * can be replicated during a later request, once authentication has - * successfully occurred. - * + * successfully occurred. + * * This class is the same as found in the JSPUI; however, a few extra methods were added to * remember the original path information (info, translated, uri, url, etc..) that Cocoon * needs in order to be able to resume a request. - * + * * @author Robert Tansley * @author Scott Phillips * @version $Revision$ */ public class RequestInfo { - - /** Request characteristics that are stored for later resumption */ - private final String authType; - private final String contextPath; - private final String method; - private final String pathInfo; - private final String pathTranslated; - private final String queryString; - private final String requestURI; - private final StringBuffer requestURL; - private final String servletPath; - private final String scheme; - private final boolean secure; - - private final Map parameters; + + /** Request characteristics that are stored for later resumption */ + private final String authType; + private final String contextPath; + private final String method; + private final String pathInfo; + private final String pathTranslated; + private final String queryString; + private final String requestURI; + private final StringBuffer requestURL; + private final String servletPath; + private final String scheme; + private final boolean secure; + + private final Map parameters; /** * Construct a request info object storing information about the given * request - * + * * @param request * the request to get information from */ public RequestInfo(HttpServletRequest request) { - this.authType = request.getAuthType(); - this.contextPath = request.getContextPath(); - this.method = request.getMethod(); - this.pathInfo = request.getPathInfo(); - this.pathTranslated = request.getPathTranslated(); - this.queryString = request.getQueryString(); - this.requestURI = request.getRequestURI(); - this.requestURL = request.getRequestURL(); - this.servletPath = request.getServletPath(); - this.scheme = request.getScheme(); - this.secure = request.isSecure(); - - // Copy the parameters - this.parameters = new HashMap(); - Enumeration enumeration = request.getParameterNames(); - while (enumeration.hasMoreElements()) - { - String key = (String) enumeration.nextElement(); - String[] values = request.getParameterValues(key); - this.parameters.put(key, values); - } + this.authType = request.getAuthType(); + this.contextPath = request.getContextPath(); + this.method = request.getMethod(); + this.pathInfo = request.getPathInfo(); + this.pathTranslated = request.getPathTranslated(); + this.queryString = request.getQueryString(); + this.requestURI = request.getRequestURI(); + this.requestURL = request.getRequestURL(); + this.servletPath = request.getServletPath(); + this.scheme = request.getScheme(); + this.secure = request.isSecure(); + + // Copy the parameters + this.parameters = new HashMap(); + Enumeration enumeration = request.getParameterNames(); + while (enumeration.hasMoreElements()) + { + String key = (String) enumeration.nextElement(); + String[] values = request.getParameterValues(key); + this.parameters.put(key, values); + } } /** @@ -84,7 +84,7 @@ public class RequestInfo */ public String getServletPath() { - return this.servletPath; + return this.servletPath; } /** @@ -93,16 +93,16 @@ public class RequestInfo */ public String getActualPath() { - return this.pathInfo + ((queryString == null || queryString.length() == 0) ? "" : "?"+queryString); + return this.pathInfo + ((queryString == null || queryString.length() == 0) ? "" : "?"+queryString); } - + /** * Wrap an incoming request to make it look like the request that the * constructor was called with - * + * * @param request * the request to wrap - * + * * @return a wrapper around the request passed into this method, wrapped so * that it looks like the request passed into the constructor */ @@ -117,136 +117,136 @@ public class RequestInfo */ class RequestWrapper extends HttpServletRequestWrapper { - - public RequestWrapper(HttpServletRequest request) { - super(request); - } - - @Override - public String getAuthType() { - return authType; - } + + public RequestWrapper(HttpServletRequest request) { + super(request); + } @Override - public String getContextPath() { - return contextPath; - } + public String getAuthType() { + return authType; + } @Override - public String getMethod() { - return method; - } + public String getContextPath() { + return contextPath; + } @Override - public String getPathInfo() { - return pathInfo; - } + public String getMethod() { + return method; + } @Override - public String getPathTranslated() { - return pathTranslated; - } + public String getPathInfo() { + return pathInfo; + } @Override - public String getQueryString() { - return queryString; - } + public String getPathTranslated() { + return pathTranslated; + } @Override - public String getRequestURI() { - return requestURI; - } + public String getQueryString() { + return queryString; + } @Override - public StringBuffer getRequestURL() { - return requestURL; - } + public String getRequestURI() { + return requestURI; + } @Override - public String getServletPath() { - return servletPath; - } + public StringBuffer getRequestURL() { + return requestURL; + } @Override - public String getParameter(String arg0) { - String[] values = parameters.get(arg0); - - if (values == null || values.length == 0) + public String getServletPath() { + return servletPath; + } + + @Override + public String getParameter(String arg0) { + String[] values = parameters.get(arg0); + + if (values == null || values.length == 0) { return null; } - else + else { return values[0]; } - } + } @Override - public Map getParameterMap() { - return parameters; - } + public Map getParameterMap() { + return parameters; + } @Override - public Enumeration getParameterNames() { - Iterator parameterIterator = parameters.keySet().iterator(); - return new EnumIterator(parameterIterator); - } + public Enumeration getParameterNames() { + Iterator parameterIterator = parameters.keySet().iterator(); + return new EnumIterator(parameterIterator); + } @Override - public String[] getParameterValues(String arg0) { - return parameters.get(arg0); - } - - @Override - public String getScheme() { - return scheme; - } + public String[] getParameterValues(String arg0) { + return parameters.get(arg0); + } @Override - public boolean isSecure() { - return secure; - } + public String getScheme() { + return scheme; + } - -// Here are other prototypes that are included in the 2.3 servlet spec: -// -// public Cookie[] getCookies() -// public long getDateHeader(String arg0) -// public String getHeader(String arg0) -// public Enumeration getHeaderNames() -// public Enumeration getHeaders(String arg0) -// public int getIntHeader(String arg0) -// public String getRemoteUser() -// public String getRequestedSessionId() -// public HttpSession getSession() -// public HttpSession getSession(boolean arg0) -// public Principal getUserPrincipal() -// public boolean isRequestedSessionIdFromCookie() -// public boolean isRequestedSessionIdFromURL() -// public boolean isRequestedSessionIdFromUrl() -// public boolean isRequestedSessionIdValid() -// public boolean isUserInRole(String arg0) -// public Object getAttribute(String arg0) -// public Enumeration getAttributeNames() -// public String getCharacterEncoding() -// public int getContentLength() -// public String getContentType() -// public ServletInputStream getInputStream() throws IOException -// public Locale getLocale() -// public Enumeration getLocales() -// public String getProtocol() -// public BufferedReader getReader() throws IOException -// public String getRealPath(String arg0) -// public String getRemoteAddr() -// public String getRemoteHost() -// public RequestDispatcher getRequestDispatcher(String arg0) -// public String getServerName() -// public int getServerPort() -// public void removeAttribute(String arg0) -// public void setAttribute(String arg0, Object arg1) -// public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException - - /** + @Override + public boolean isSecure() { + return secure; + } + + +// Here are other prototypes that are included in the 2.3 servlet spec: +// +// public Cookie[] getCookies() +// public long getDateHeader(String arg0) +// public String getHeader(String arg0) +// public Enumeration getHeaderNames() +// public Enumeration getHeaders(String arg0) +// public int getIntHeader(String arg0) +// public String getRemoteUser() +// public String getRequestedSessionId() +// public HttpSession getSession() +// public HttpSession getSession(boolean arg0) +// public Principal getUserPrincipal() +// public boolean isRequestedSessionIdFromCookie() +// public boolean isRequestedSessionIdFromURL() +// public boolean isRequestedSessionIdFromUrl() +// public boolean isRequestedSessionIdValid() +// public boolean isUserInRole(String arg0) +// public Object getAttribute(String arg0) +// public Enumeration getAttributeNames() +// public String getCharacterEncoding() +// public int getContentLength() +// public String getContentType() +// public ServletInputStream getInputStream() throws IOException +// public Locale getLocale() +// public Enumeration getLocales() +// public String getProtocol() +// public BufferedReader getReader() throws IOException +// public String getRealPath(String arg0) +// public String getRemoteAddr() +// public String getRemoteHost() +// public RequestDispatcher getRequestDispatcher(String arg0) +// public String getServerName() +// public int getServerPort() +// public void removeAttribute(String arg0) +// public void setAttribute(String arg0, Object arg1) +// public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException + + /** * This class converts an iterator into an enumerator. This is done * because we have the parameters as a Map (JDK 1.2 style), but for some * weird reason the HttpServletRequest interface returns an Enumeration diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestUtils.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestUtils.java index 8a5ff38d5d..fee1cdd940 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestUtils.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/utils/RequestUtils.java @@ -14,186 +14,184 @@ import org.apache.cocoon.environment.Request; /** * General utilities for common operations on Request objects. - * + * * @author Scott Phillips */ public class RequestUtils { - - /** - * Get values for a field from a DRI multi value field, since a field may - * have multiple values this method will check for fieldName + "_n" until - * it does not find any more values. The result is a list of all values - * for a field. - * - * If the value has been selected to be removed then it is removed from - * the list. - * - * @param request - * The request containing the form information - * @param compositeFieldName - * The fieldName of the composite field - * @param componentFieldName - * The fieldName of the component field - * @return a List of Strings - */ - public static List getCompositeFieldValues(Request request, String compositeFieldName, String componentFieldName) - { - List values = new ArrayList(); - int i = -1; + /** + * Get values for a field from a DRI multi value field, since a field may + * have multiple values this method will check for fieldName + "_n" until + * it does not find any more values. The result is a list of all values + * for a field. + * + * If the value has been selected to be removed then it is removed from + * the list. + * + * @param request + * The request containing the form information + * @param compositeFieldName + * The fieldName of the composite field + * @param componentFieldName + * The fieldName of the component field + * @return a List of Strings + */ + public static List getCompositeFieldValues(Request request, String compositeFieldName, String componentFieldName) + { + List values = new ArrayList(); - // Iterate through the values in the form. - valueLoop: while (true) - { - i++; - String value = null; + int i = -1; - // Get the component field's name - if (i == 0) + // Iterate through the values in the form. + valueLoop: while (true) + { + i++; + String value = null; + + // Get the component field's name + if (i == 0) { value = request.getParameter(componentFieldName); } - else + else { value = request.getParameter(componentFieldName + "_" + i); } - // If this is null then it's the last one. - if (value == null) + // If this is null then it's the last one. + if (value == null) { break valueLoop; } - // Check to make sure that this value is not selected to be removed. - String[] selected = request.getParameterValues(compositeFieldName + "_selected"); + // Check to make sure that this value is not selected to be removed. + String[] selected = request.getParameterValues(compositeFieldName + "_selected"); - if (selected != null) - { - for (String select : selected) - { - if (select.equals(compositeFieldName + "_" + i)) - { - // Found, the user has requested that this value be deleted. - continue valueLoop; - } - } - } + if (selected != null) + { + for (String select : selected) + { + if (select.equals(compositeFieldName + "_" + i)) + { + // Found, the user has requested that this value be deleted. + continue valueLoop; + } + } + } - // Only add non-blank items to the list - if (value.length() == 0) + // Only add non-blank items to the list + if (value.length() == 0) { continue valueLoop; } - - // Finally, add it to the list - values.add(value.trim()); - } - return values; - } + // Finally, add it to the list + values.add(value.trim()); + } + + return values; + } - /** - * Get values from a DRI multi value field, since a field may have multiple - * values this method will check for fieldName + "_n" until it does not - * find any more values. The result is a list of all values for a field. - * - * If the value has been selected to be removed then it is removed from - * the list. - * - * @param request - * The request containing the form information - * @param fieldName - * The fieldName of the composite field - * @return a List of Strings - */ - public static List getFieldValues(Request request, String fieldName) - { - List values = new ArrayList(); + /** + * Get values from a DRI multi value field, since a field may have multiple + * values this method will check for fieldName + "_n" until it does not + * find any more values. The result is a list of all values for a field. + * + * If the value has been selected to be removed then it is removed from + * the list. + * + * @param request + * The request containing the form information + * @param fieldName + * The fieldName of the composite field + * @return a List of Strings + */ + public static List getFieldValues(Request request, String fieldName) + { + List values = new ArrayList(); - int i = -1; + int i = -1; - // Iterate through the values in the form. - valueLoop: while (true) - { - i++; - String value = null; + // Iterate through the values in the form. + valueLoop: while (true) + { + i++; + String value = null; - // Get the component field's name - if (i == 0) + // Get the component field's name + if (i == 0) { value = request.getParameter(fieldName); } - else + else { value = request.getParameter(fieldName + "_" + i); } - // If this is null then it's the last one. - if (value == null) + // If this is null then it's the last one. + if (value == null) { break valueLoop; } - // Check to make sure that this value is not selected to be removed. - String[] selected = request.getParameterValues(fieldName + "_selected"); + // Check to make sure that this value is not selected to be removed. + String[] selected = request.getParameterValues(fieldName + "_selected"); - if (selected != null) - { - for (String select : selected) - { - if (select.equals(fieldName + "_" + i)) - { - // Found, the user has requested that this value be deleted. - continue valueLoop; - } - } - } + if (selected != null) + { + for (String select : selected) + { + if (select.equals(fieldName + "_" + i)) + { + // Found, the user has requested that this value be deleted. + continue valueLoop; + } + } + } - // Only add non-blank items to the list - if (value.length() == 0) + // Only add non-blank items to the list + if (value.length() == 0) { continue valueLoop; } - - // Finally, add it to the list - values.add(value.trim()); - } - return values; - } - + // Finally, add it to the list + values.add(value.trim()); + } + + return values; + } + /** * Obtain a parameter from the given request as an int. -1 is * returned if the parameter is garbled or does not exist. - * + * * @param request * the HTTP request * @param param * the name of the parameter - * + * * @return the integer value of the parameter, or -1 */ public static int getIntParameter(Request request, String param) { String val = request.getParameter(param); - if (val != null) - { - try - { - return Integer.parseInt(val.trim()); - } - catch (Exception e) - { - // Problem with parameter -- ignore - } - } - return -1; + if (val != null) + { + try + { + return Integer.parseInt(val.trim()); + } + catch (Exception e) + { + // Problem with parameter -- ignore + } + } + return -1; } - - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/IncludePageMeta.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/IncludePageMeta.java index 37beedcdf8..03aecec25a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/IncludePageMeta.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/IncludePageMeta.java @@ -107,8 +107,8 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl */ @Override public void setup(SourceResolver resolver, Map objectModel, String src, - Parameters parameters) throws ProcessingException, SAXException, - IOException + Parameters parameters) + throws ProcessingException, SAXException, IOException { try { @@ -116,10 +116,10 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl metadataList = new ArrayList<>(); for (String name : names) { - String[] nameParts = name.split("#"); + String[] nameParts = name.split("#"); - String dcName = null; - int order = -1; + String dcName = null; + int order = -1; switch (nameParts.length) { case 1: @@ -158,7 +158,8 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl String value = parameters.getParameter(name); - Metadata metadata = new Metadata(element,qualifier,language,order,value); + Metadata metadata = new Metadata( + element, qualifier, language, order, value); metadataList.add(metadata); } @@ -180,7 +181,9 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl } // concatenation - if (DSpaceServicesFactory.getInstance().getConfigurationService().getBooleanProperty("xmlui.theme.enableConcatenation",false)) { + if (DSpaceServicesFactory.getInstance().getConfigurationService() + .getBooleanProperty("xmlui.theme.enableConcatenation", false)) + { metadataList = enableConcatenation(); } } @@ -198,13 +201,16 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl { // only try to concatenate css and js String curfile = metadata.getValue(); - if (curfile.lastIndexOf('?') != -1) { + if (curfile.lastIndexOf('?') != -1) + { curfile = curfile.substring(0, curfile.lastIndexOf('?')); } - if (curfile.endsWith(".css") || curfile.endsWith(".js") || curfile.endsWith(".json")) { + if (curfile.endsWith(".css") || curfile.endsWith(".js") || curfile.endsWith(".json")) + { String curval = metadata.getValue(); // check if this metadata and the last one are compatible - if(last != null && checkConcatenateMerge(last, metadata)) { + if (last != null && checkConcatenateMerge(last, metadata)) + { // merge String lastval = last.getValue(); curval = metadata.getValue(); @@ -212,28 +218,38 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl newval += curval.substring(curval.lastIndexOf('/')+1,curval.lastIndexOf('.')); newval += lastval.substring(lastval.lastIndexOf('.')); last.value = newval; - } else { + } + else + { // no merge, so add to list newMetadataList.add(metadata); // handle query string cases - if(curval.lastIndexOf('?') != -1) { - if(curval.substring(curval.lastIndexOf('?')).equals("?nominify")) { + if (curval.lastIndexOf('?') != -1) + { + if (curval.substring(curval.lastIndexOf('?')).equals("?nominify")) + { // concat should still be possible, so set last last = metadata; - } else if(curval.substring(curval.lastIndexOf('?')).equals("?noconcat")) { + } + else if (curval.substring(curval.lastIndexOf('?')).equals("?noconcat")) + { // no concat should be possible so set last to null last = null; // query string can be removed curval = curval.substring(0, curval.lastIndexOf('?')); metadata.value = curval; - } else { + } + else + { // no concat should be possible so set last to null last = null; // query string should be set to "nominify" curval = curval.substring(0, curval.lastIndexOf('?')) + "?nominify"; metadata.value = curval; } - } else { + } + else + { // multiple possibilities: // * last == null, so set it // * no merge is possible, so change last to this metadata @@ -241,7 +257,9 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl last = metadata; } } - } else { + } + else + { // wrong extension newMetadataList.add(metadata); } @@ -251,27 +269,39 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl private boolean checkConcatenateMerge(Metadata last, Metadata current) { // check if elements are equal - if(last.getElement() == null) { - if(current.getElement() != null) { + if (last.getElement() == null) + { + if (current.getElement() != null) + { return false; } - } else if(!last.getElement().equals(current.getElement())) { + } + else if (!last.getElement().equals(current.getElement())) + { return false; } // check if qualifiers are equal - if(last.getQualifier() == null) { - if(current.getQualifier() != null) { + if (last.getQualifier() == null) + { + if (current.getQualifier() != null) + { return false; } - } else if(!last.getQualifier().equals(current.getQualifier())) { + } + else if (!last.getQualifier().equals(current.getQualifier())) + { return false; } // check if languages are equal - if(last.getLanguage() == null) { - if(current.getLanguage() != null) { + if (last.getLanguage() == null) + { + if (current.getLanguage() != null) + { return false; } - } else if(!last.getLanguage().equals(current.getLanguage())) { + } + else if (!last.getLanguage().equals(current.getLanguage())) + { return false; } @@ -279,36 +309,40 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl String curval = current.getValue(); String lastval = last.getValue(); // check if extensions and query strings are equal - if(!lastval.substring(lastval.lastIndexOf('.')).equals(curval.substring(curval.lastIndexOf('.')))) { + if (!lastval.substring(lastval.lastIndexOf('.')) + .equals(curval.substring(curval.lastIndexOf('.')))) + { return false; } // check if paths are equal - if(!lastval.substring(0,lastval.lastIndexOf('/')+1).equals(curval.substring(0,curval.lastIndexOf('/')+1))) { + if (!lastval.substring(0, lastval.lastIndexOf('/') + 1) + .equals(curval.substring(0, curval.lastIndexOf('/') + 1))) + { return false; } // only valid nonempty query string is "nominify" - return !(curval.lastIndexOf('?') != -1 - && !"?nominify".equals(curval.substring(curval.lastIndexOf('?')))); - + return !(curval.lastIndexOf('?') != -1 && + !"?nominify".equals(curval.substring(curval.lastIndexOf('?')))); } /** * Include the metadata in the page metadata. * @throws org.dspace.app.xmlui.wing.WingException passed through. */ @Override - public void addPageMeta(PageMeta pageMeta) throws WingException + public void addPageMeta(PageMeta pageMeta) + throws WingException { for (Metadata metadata : metadataList) { - String element = metadata.getElement(); - String qualifier = metadata.getQualifier(); - String language = metadata.getLanguage(); + String element = metadata.getElement(); + String qualifier = metadata.getQualifier(); + String language = metadata.getLanguage(); String value = metadata.getValue(); // Add our new metadata. pageMeta.addMetadata(element, qualifier, language) - .addContent(value); + .addContent(value); } } @@ -318,87 +352,86 @@ public class IncludePageMeta extends AbstractWingTransformer implements Cacheabl */ static class Metadata implements Comparable { - private final String element; - private final String qualifier; - private final String language; - private final int order; - private String value; + private final String element; + private final String qualifier; + private final String language; + private final int order; + private String value; - public Metadata(String element,String qualifier, String language, int order, String value) - { - this.element = element; - this.qualifier = qualifier; - this.language = language; - this.order = order; - this.value = value; - } + public Metadata(String element,String qualifier, String language, int order, String value) + { + this.element = element; + this.qualifier = qualifier; + this.language = language; + this.order = order; + this.value = value; + } - public String getElement() - { - return this.element; - } + public String getElement() + { + return this.element; + } - public String getQualifier() - { - return this.qualifier; - } + public String getQualifier() + { + return this.qualifier; + } - public String getLanguage() - { - return this.language; - } + public String getLanguage() + { + return this.language; + } - public int getOrder() - { - return this.order; - } + public int getOrder() + { + return this.order; + } - public String getName() - { - String name = this.element; - if (this.qualifier != null) - { - name += "." + this.qualifier; - if (this.language != null) - { - name += "." + this.language; - } - } + public String getName() + { + String name = this.element; + if (this.qualifier != null) + { + name += "." + this.qualifier; + if (this.language != null) + { + name += "." + this.language; + } + } - name += "#" + order; - return name; - } + name += "#" + order; + return name; + } - public String getValue() - { - return this.value; - } + public String getValue() + { + return this.value; + } @Override - public int compareTo(Metadata other) - { - String myName = this.element + "." +this.qualifier + "." + this.language; - String otherName = other.element + "." + other.qualifier + "." + other.language; + public int compareTo(Metadata other) + { + String myName = this.element + "." + this.qualifier + "." + this.language; + String otherName = other.element + "." + other.qualifier + "." + other.language; - int result = myName.compareTo(otherName); - if (result == 0) - { - if (this.order == other.order ) - { - result = 0; // These two metadata element's names are completely identical. - } - else if (this.order > other.order) - { - result = 1; // The other metadata element belongs AFTER this element. - } - else - { - result = -1; // The other metadata element belongs BEFORE this element. - } - } + int result = myName.compareTo(otherName); + if (result == 0) + { + if (this.order == other.order ) + { + result = 0; // These two metadata element's names are completely identical. + } + else if (this.order > other.order) + { + result = 1; // The other metadata element belongs AFTER this element. + } + else + { + result = -1; // The other metadata element belongs BEFORE this element. + } + } - return result; - } + return result; + } } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/PageMeta.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/PageMeta.java index 4308b9dc06..7a4abe4e00 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/PageMeta.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/PageMeta.java @@ -22,7 +22,7 @@ import org.xml.sax.helpers.NamespaceSupport; /** * A class representing a set of metadata about the page being generated. - * + * * @author Scott Phillips */ public class PageMeta extends AbstractWingElement implements @@ -35,9 +35,9 @@ public class PageMeta extends AbstractWingElement implements private boolean merged = false; - /** - * A page meta may hold two types of elements, trails or - * metadata. Each of these types are separated so that + /** + * A page meta may hold two types of elements, trails or + * metadata. Each of these types are separated so that * we can search through each time as we merge documents. */ private List metadatum = new ArrayList<>(); @@ -45,34 +45,36 @@ public class PageMeta extends AbstractWingElement implements /** * Construct a new pageMeta - * + * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * @throws org.dspace.app.xmlui.wing.WingException passed through. */ - protected PageMeta(WingContext context) throws WingException + protected PageMeta(WingContext context) + throws WingException { super(context); } /** - * Add metadata about this page. - * - * @param element - * (Required) The metadata element. - * @param qualifier - * (May be null) The metadata qualifier. - * @param language - * (May be null) The metadata language - * @param allowMultiple - * (Required) determine if multiple metadata elements with the same - * element, qualifier and language are allowed. - * @return A new metadata + * Add metadata about this page. + * + * @param element + * (Required) The metadata element. + * @param qualifier + * (May be null) The metadata qualifier. + * @param language + * (May be null) The metadata language + * @param allowMultiple + * (Required) determine if multiple metadata elements with the same + * element, qualifier and language are allowed. + * @return A new metadata * @throws org.dspace.app.xmlui.wing.WingException passed through. - */ + */ public Metadata addMetadata(String element, String qualifier, - String language, boolean allowMultiple) throws WingException + String language, boolean allowMultiple) + throws WingException { Metadata metadata = new Metadata(context, element, qualifier, language, allowMultiple); metadatum.add(metadata); @@ -80,26 +82,26 @@ public class PageMeta extends AbstractWingElement implements } /** - * Add metadata about this page. - * - * @param element - * (Required) The metadata element. - * @param qualifier - * (May be null) The metadata qualifier. - * @param language - * (May be null) The metadata language - * @return A new metadata + * Add metadata about this page. + * + * @param element + * (Required) The metadata element. + * @param qualifier + * (May be null) The metadata qualifier. + * @param language + * (May be null) The metadata language + * @return A new metadata * @throws org.dspace.app.xmlui.wing.WingException passed through. - */ + */ public Metadata addMetadata(String element, String qualifier, String language) - throws WingException + throws WingException { return addMetadata(element, qualifier, language, false); } - + /** * Add metadata about this page. - * + * * @param element * (Required) The metadata element. * @param qualifier @@ -108,27 +110,28 @@ public class PageMeta extends AbstractWingElement implements * @throws org.dspace.app.xmlui.wing.WingException passed through. */ public Metadata addMetadata(String element, String qualifier) - throws WingException + throws WingException { return addMetadata(element, qualifier, null, false); } /** * Add metadata about this page. - * + * * @param element * (Required) The metadata element. * @return A new metadata * @throws org.dspace.app.xmlui.wing.WingException passed through. */ - public Metadata addMetadata(String element) throws WingException + public Metadata addMetadata(String element) + throws WingException { return addMetadata(element, null, null, false); } /** * Add a new trail to the page. - * + * * @param target * (May be null) Target URL for this trail item. * @param rend @@ -137,7 +140,7 @@ public class PageMeta extends AbstractWingElement implements * @throws org.dspace.app.xmlui.wing.WingException passed through. */ public Trail addTrail(String target, String rend) - throws WingException + throws WingException { Trail trail = new Trail(context, target, rend); trails.add(trail); @@ -146,19 +149,19 @@ public class PageMeta extends AbstractWingElement implements /** * Add a new trail to the page without a link or render attribute. - * + * * @return a new trail * @throws org.dspace.app.xmlui.wing.WingException passed through. */ public Trail addTrail() - throws WingException + throws WingException { return addTrail(null,null); } - + /** * Add a new trail link to the page. - * + * * @param target * (May be null) The Target URL for this trail item. * @param characters @@ -166,7 +169,7 @@ public class PageMeta extends AbstractWingElement implements * @throws org.dspace.app.xmlui.wing.WingException passed through. */ public void addTrailLink(String target, String characters) - throws WingException + throws WingException { Trail trail = addTrail(target, null); trail.addContent(characters); @@ -174,7 +177,7 @@ public class PageMeta extends AbstractWingElement implements /** * Add a new trail link to the page. - * + * * @param target * (May be null) The Target URL for this trail item. * @param message @@ -183,7 +186,7 @@ public class PageMeta extends AbstractWingElement implements * @throws org.dspace.app.xmlui.wing.WingException passed through. */ public void addTrailLink(String target, Message message) - throws WingException + throws WingException { Trail trail = addTrail(target, null); trail.addContent(message); @@ -191,7 +194,7 @@ public class PageMeta extends AbstractWingElement implements /** * Determine if the given SAX event is a PageMeta element. - * + * * @param namespace * The element's name space * @param localName @@ -204,7 +207,8 @@ public class PageMeta extends AbstractWingElement implements */ @Override public boolean mergeEqual(String namespace, String localName, String qName, - Attributes attributes) throws SAXException, WingException + Attributes attributes) + throws SAXException, WingException { if (!WingConstants.DRI.URI.equals(namespace)) @@ -231,44 +235,44 @@ public class PageMeta extends AbstractWingElement implements */ @Override public WingMergeableElement mergeChild(String namespace, String localName, - String qName, Attributes attributes) throws SAXException, - WingException + String qName, Attributes attributes) + throws SAXException, WingException { - // We don't merge our children but we do have one special optimization, - // if some metadata or trail is already in the document then we do not add - // our own trail or metadata for that particular item. - if (WingConstants.DRI.URI.equals(namespace) && Trail.E_TRAIL.equals(localName)) - { + // We don't merge our children but we do have one special optimization, + // if some metadata or trail is already in the document then we do not add + // our own trail or metadata for that particular item. + if (WingConstants.DRI.URI.equals(namespace) && Trail.E_TRAIL.equals(localName)) + { for (Trail trail : trails) { trail.dispose(); } - trails.clear(); - } - - if (WingConstants.DRI.URI.equals(namespace) && Metadata.E_METADATA.equals(localName)) - { - String element = attributes.getValue(Metadata.A_ELEMENT); - String qualifier = attributes.getValue(Metadata.A_QUALIFIER); - String language = attributes.getValue(Metadata.A_LANGUAGE); - - List remove = new ArrayList<>(); - for (Metadata metadata : metadatum) - { - if (metadata.equals(element,qualifier,language) && !metadata.allowMultiple()) - { - remove.add(metadata); - } - } - - // Remove all the metadata elements we found. - for (Metadata metadata : remove) - { - metadata.dispose(); - metadatum.remove(metadata); - } - } - + trails.clear(); + } + + if (WingConstants.DRI.URI.equals(namespace) && Metadata.E_METADATA.equals(localName)) + { + String element = attributes.getValue(Metadata.A_ELEMENT); + String qualifier = attributes.getValue(Metadata.A_QUALIFIER); + String language = attributes.getValue(Metadata.A_LANGUAGE); + + List remove = new ArrayList<>(); + for (Metadata metadata : metadatum) + { + if (metadata.equals(element,qualifier,language) && !metadata.allowMultiple()) + { + remove.add(metadata); + } + } + + // Remove all the metadata elements we found. + for (Metadata metadata : remove) + { + metadata.dispose(); + metadatum.remove(metadata); + } + } + return null; } @@ -276,8 +280,8 @@ public class PageMeta extends AbstractWingElement implements * Inform this element that it is being merged with an existing element. */ @Override - public Attributes merge(Attributes attributes) throws SAXException, - WingException + public Attributes merge(Attributes attributes) + throws SAXException, WingException { this.merged = true; return attributes; @@ -285,20 +289,21 @@ public class PageMeta extends AbstractWingElement implements /** * Translate this element into SAX events. - * + * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler - * (Required) The registered lexicalHandler where lexical + * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able * to determine the correct prefix for a given namespace URI. */ @Override - public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, - NamespaceSupport namespaces) throws SAXException + public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, + NamespaceSupport namespaces) + throws SAXException { if (!merged) { @@ -309,7 +314,7 @@ public class PageMeta extends AbstractWingElement implements { metadata.toSAX(contentHandler, lexicalHandler, namespaces); } - + for (Trail trail : trails) { trail.toSAX(contentHandler, lexicalHandler, namespaces); @@ -324,21 +329,21 @@ public class PageMeta extends AbstractWingElement implements @Override public void dispose() { - for (Metadata metadata : metadatum) + for (Metadata metadata : metadatum) { metadata.dispose(); } - - for (Trail trail : trails) + + for (Trail trail : trails) { trail.dispose(); } - - trails.clear(); - trails = null; - metadatum.clear(); - metadatum = null; - + + trails.clear(); + trails = null; + metadatum.clear(); + metadatum = null; + super.dispose(); } } diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/RepositoryMeta.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/RepositoryMeta.java index 0f9be31a7d..e358c169d6 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/RepositoryMeta.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/RepositoryMeta.java @@ -23,7 +23,7 @@ import org.xml.sax.helpers.NamespaceSupport; /** * A class representing a set of all referenced repositories in the DRI document. - * + * * @author Scott Phillips */ public class RepositoryMeta extends AbstractWingElement implements WingMergeableElement, MetadataElement @@ -36,39 +36,40 @@ public class RepositoryMeta extends AbstractWingElement implements WingMergeable /** The name of this repository identifier attribute*/ public static final String A_REPOSITORY_ID = "repositoryID"; - + /** The unique url of this repository */ public static final String A_REPOSITORY_URL = "url"; - + /** Has this repositoryMeta element been merged? */ private boolean merged = false; - + /** The registered repositories on this page */ private Map repositories = new HashMap<>(); /** * Construct a new RepositoryMeta - * + * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * @throws org.dspace.app.xmlui.wing.WingException passed through. */ - protected RepositoryMeta(WingContext context) throws WingException + protected RepositoryMeta(WingContext context) + throws WingException { super(context); - + ObjectManager objectManager = context.getObjectManager(); if (!(objectManager == null)) { - this.repositories = objectManager.getAllManagedRepositories(); + this.repositories = objectManager.getAllManagedRepositories(); } } /** * Determine if the given SAX event is a ObjectMeta element. - * + * * @param namespace * The element's name space * @param localName @@ -81,7 +82,8 @@ public class RepositoryMeta extends AbstractWingElement implements WingMergeable */ @Override public boolean mergeEqual(String namespace, String localName, String qName, - Attributes attributes) throws SAXException, WingException + Attributes attributes) + throws SAXException, WingException { if (!WingConstants.DRI.URI.equals(namespace)) @@ -95,10 +97,10 @@ public class RepositoryMeta extends AbstractWingElement implements WingMergeable /** * Since we will only add to the object set and never modify an existing * object we do not merge any child elements. - * + * * However we will notify the object manager of each identifier we * encounter. - * + * * @param namespace * The element's name space * @param localName @@ -111,28 +113,28 @@ public class RepositoryMeta extends AbstractWingElement implements WingMergeable */ @Override public WingMergeableElement mergeChild(String namespace, String localName, - String qName, Attributes attributes) throws SAXException, - WingException + String qName, Attributes attributes) + throws SAXException, WingException { // Check if it's in our name space and an options element. if (!WingConstants.DRI.URI.equals(namespace)) { return null; } - + if (!E_REPOSITORY.equals(localName)) { return null; } - + // Get the repositoryIdentefier String repositoryIdentifier = attributes.getValue(A_REPOSITORY_ID); if (repositories.containsKey(repositoryIdentifier)) { - repositories.remove(repositoryIdentifier); + repositories.remove(repositoryIdentifier); } - + return null; } @@ -140,8 +142,8 @@ public class RepositoryMeta extends AbstractWingElement implements WingMergeable * Inform this element that it is being merged with an existing element. */ @Override - public Attributes merge(Attributes attributes) throws SAXException, - WingException + public Attributes merge(Attributes attributes) + throws SAXException, WingException { this.merged = true; @@ -150,12 +152,12 @@ public class RepositoryMeta extends AbstractWingElement implements WingMergeable /** * Translate this element into SAX events. - * + * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler - * (Required) The registered lexicalHandler where lexical + * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able @@ -170,18 +172,17 @@ public class RepositoryMeta extends AbstractWingElement implements WingMergeable { startElement(contentHandler, namespaces, E_REPOSITORY_META, null); } - - for (String identifier : repositories.keySet()) - { - // add the repository XML - AttributeMap attributes = new AttributeMap(); - attributes.put(A_REPOSITORY_ID, identifier); - attributes.put(A_REPOSITORY_URL, repositories.get(identifier)); - - startElement(contentHandler,namespaces,E_REPOSITORY,attributes); - endElement(contentHandler,namespaces,E_REPOSITORY); - } - + + for (String identifier : repositories.keySet()) + { + // add the repository XML + AttributeMap attributes = new AttributeMap(); + attributes.put(A_REPOSITORY_ID, identifier); + attributes.put(A_REPOSITORY_URL, repositories.get(identifier)); + + startElement(contentHandler,namespaces,E_REPOSITORY,attributes); + endElement(contentHandler,namespaces,E_REPOSITORY); + } if (!merged) { diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/SimpleHTMLFragment.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/SimpleHTMLFragment.java index 2117f3cc0d..0ba1c96c47 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/SimpleHTMLFragment.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/SimpleHTMLFragment.java @@ -34,454 +34,521 @@ import org.xml.sax.helpers.NamespaceSupport; /** * This class represents data that is translated from simple HTML or plain text. - * + * *

    This class represents a simple HTML fragment. It allows for user-supplied * HTML to be translated on the fly into DRI. - * + * *

    At the present time it only supports the following tags: h1, h2, h3, h4, h5, * p, a, b, i, u, ol, li and img. Each are translated into their DRI equivalents. * Note that the "h" tags are translated into a paragraph of rend=heading. - * + * *

    If the {@code linkbreaks} flag is set then line breaks are treated as paragraphs. This - * allows plain text files to also be included and they will be mapped into DRI as + * allows plain text files to also be included and they will be mapped into DRI as * well. - * + * * @author Scott Phillips * @author Jay Paz */ public class SimpleHTMLFragment extends AbstractWingElement { - /** The HTML Fragment */ - private final String fragment; + /** The HTML Fragment */ + private final String fragment; - /** Determine if blank lines mark a new paragraph */ - private final boolean blankLines; + /** Determine if blank lines mark a new paragraph */ + private final boolean blankLines; - /** - * Construct a fragment object for translating into DRI. - * - * @param context - * (Required) The context this element is contained in, such as - * where to route SAX events and what i18n catalogue to use. - * @param blankLines - * (Required) Determine if blank lines should be treated as - * paragraphs delimeters. - * @param fragment - * (Required) The HTML Fragment to be translated into DRI. - * @throws WingException passed through. - */ - protected SimpleHTMLFragment(WingContext context, boolean blankLines, - String fragment) throws WingException { - super(context); - this.blankLines = blankLines; - this.fragment = fragment; - } + /** + * Construct a fragment object for translating into DRI. + * + * @param context + * (Required) The context this element is contained in, such as + * where to route SAX events and what i18n catalogue to use. + * @param blankLines + * (Required) Determine if blank lines should be treated as + * paragraphs delimeters. + * @param fragment + * (Required) The HTML Fragment to be translated into DRI. + * @throws WingException passed through. + */ + protected SimpleHTMLFragment(WingContext context, boolean blankLines, + String fragment) throws WingException { + super(context); + this.blankLines = blankLines; + this.fragment = fragment; + } - /** - * Translate this element into SAX - * - * @param contentHandler - * (Required) The registered contentHandler where SAX events - * should be routed too. - * @param lexicalHandler - * (Required) The registered lexicalHandler where lexical events - * (such as CDATA, DTD, etc) should be routed too. - * @param namespaces - * (Required) SAX Helper class to keep track of namespaces able - * to determine the correct prefix for a given namespace URI. + /** + * Translate this element into SAX + * + * @param contentHandler + * (Required) The registered contentHandler where SAX events + * should be routed too. + * @param lexicalHandler + * (Required) The registered lexicalHandler where lexical events + * (such as CDATA, DTD, etc) should be routed too. + * @param namespaces + * (Required) SAX Helper class to keep track of namespaces able + * to determine the correct prefix for a given namespace URI. * @throws org.xml.sax.SAXException on I/O error. - */ + */ @Override - public void toSAX(ContentHandler contentHandler, - LexicalHandler lexicalHandler, NamespaceSupport namespaces) - throws SAXException { - try { - String xml = "" + fragment + ""; + public void toSAX(ContentHandler contentHandler, + LexicalHandler lexicalHandler, NamespaceSupport namespaces) + throws SAXException + { + try + { + String xml = "" + fragment + ""; - ByteArrayInputStream inputStream = new ByteArrayInputStream(xml - .getBytes("UTF-8")); + ByteArrayInputStream inputStream = new ByteArrayInputStream( + xml.getBytes("UTF-8")); - SAXBuilder builder = new SAXBuilder(); - Document document = builder.build(inputStream); + SAXBuilder builder = new SAXBuilder(); + Document document = builder.build(inputStream); - try { - translate(document.getRootElement()); - } catch (RuntimeException e) { + try + { + translate(document.getRootElement()); + } + catch (RuntimeException e) + { throw e; - } catch (Exception e) { - throw new JDOMException( - "Error translating HTML fragment into DRI", e); - } + } + catch (Exception e) + { + throw new JDOMException( + "Error translating HTML fragment into DRI", e); + } - SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, - namespaces); - SAXOutputter outputter = new SAXOutputter(); - outputter.setContentHandler(filter); - outputter.setLexicalHandler(filter); + SAXFilter filter = new SAXFilter(contentHandler, lexicalHandler, + namespaces); + SAXOutputter outputter = new SAXOutputter(); + outputter.setContentHandler(filter); + outputter.setLexicalHandler(filter); - Element root = document.getRootElement(); + Element root = document.getRootElement(); - @SuppressWarnings("unchecked") - // This cast is correct - List children = root.getChildren(); - for (Element child : children) { - outputter.output(child); - } + @SuppressWarnings("unchecked") + // This cast is correct + List children = root.getChildren(); + for (Element child : children) { + outputter.output(child); + } + } + catch (JDOMException e) + { + // If we are here, then a parsing error occurred within the XHTML + // fragment. We'll just assume that this is not supposed to be + // XHTML and display the fragment as plain text within tags. + startElement(contentHandler, namespaces, Para.E_PARA, null); + sendCharacters(contentHandler, fragment); + endElement(contentHandler, namespaces, Para.E_PARA); + } + catch (IOException ioe) + { + throw new SAXException(ioe); + } + } - } catch (JDOMException e) { - // If we are here, then a parsing error occurred within the XHTML fragment. We'll just assume - // that this is not supposed to be XHTML and display the fragment as plain text within tags. - startElement(contentHandler, namespaces, Para.E_PARA, null); - sendCharacters(contentHandler, fragment); - endElement(contentHandler, namespaces, Para.E_PARA); - } catch (IOException ioe) { - throw new SAXException(ioe); - } - } + /** + * Remove the given content from the Element. + * + * If the content is an element then render it as text and include it's + * children in the parent. + * + * @param content + * The DOM Content to be removed. + */ + private void removeContent(Content content) + { + if (content instanceof Element) + { + // If it's an element replace the content with a text node. + Element element = (Element) content; - /** - * Remove the given content from the Element. - * - * If the content is an element then render it as text and include it's - * children in the parent. - * - * @param content - * The DOM Content to be removed. - */ - private void removeContent(Content content) { - if (content instanceof Element) { - // If it's an element replace the content with a text node. - Element element = (Element) content; + if (element.getContent().isEmpty()) + { + // The element contains nothing, we can use shorthand notation + // for it. + StringBuilder replacement = new StringBuilder().append("<").append(element.getName()); - if (element.getContent().isEmpty()) { - // The element contains nothing, we can use shorthand notation - // for it. - StringBuilder replacement = new StringBuilder().append("<").append(element.getName()); + @SuppressWarnings("unchecked") + // This cast is correct + List attributes = element.getAttributes(); + for (Attribute attribute : attributes) + { + replacement .append(" ").append(attribute.getName()).append("=\"").append(attribute.getValue()).append("\"").toString(); + } + replacement.append("/>"); - @SuppressWarnings("unchecked") - // This cast is correct - List attributes = element.getAttributes(); - for (Attribute attribute : attributes) { - replacement .append(" ").append(attribute.getName()).append("=\"").append(attribute.getValue()).append("\"").toString(); - } - replacement.append("/>"); + Element parent = element.getParentElement(); + int index = parent.indexOf(element); + parent.setContent(index, new Text(replacement.toString())); + } + else + { + // The element contains data + StringBuilder prepend = new StringBuilder(); + prepend.append("<").append(element.getName()); - Element parent = element.getParentElement(); - int index = parent.indexOf(element); - parent.setContent(index, new Text(replacement.toString())); - } else { - // The element contains data - StringBuilder prepend = new StringBuilder(); - prepend.append("<").append(element.getName()); + @SuppressWarnings("unchecked") + // This cast is correct + List attributes = element.getAttributes(); + for (Attribute attribute : attributes) + { + prepend.append(" ").append(attribute.getName()).append("=\"").append(attribute.getValue()).append("\""); + } + prepend.append(">"); - @SuppressWarnings("unchecked") - // This cast is correct - List attributes = element.getAttributes(); - for (Attribute attribute : attributes) { - prepend.append(" ").append(attribute.getName()).append("=\"").append(attribute.getValue()).append("\""); - } - prepend.append(">"); + String postpend = ""; - String postpend = ""; + Element parent = element.getParentElement(); + int index = parent.indexOf(element); - Element parent = element.getParentElement(); - int index = parent.indexOf(element); + parent.addContent(index, new Text(postpend)); + parent.addContent(index, element.removeContent()); + parent.addContent(index, new Text(prepend.toString())); + parent.removeContent(element); + } + } + else + { + // If it's not an element just remove the content from the document. + Element parent = content.getParentElement(); + parent.removeContent(content); + } + } - parent.addContent(index, new Text(postpend)); - parent.addContent(index, element.removeContent()); - parent.addContent(index, new Text(prepend.toString())); - parent.removeContent(element); - } - } else { - // If it's not an element just remove the content from the document. - Element parent = content.getParentElement(); - parent.removeContent(content); - } - } - - /** - * Wrap the given set of contents into a paragraph and place it at the - * supplied index. - * - * This method will also check for trivial paragraphs, i.e. those that - * contain nothing but white space. If they are found then they are removed. - * - * @param parent - * The parent element to attach the wrapped paragraph, too. - * @param index - * The index within the parent for where the content should be - * attached. - * @param contents - * The contents that should be wrapped in a paragraph. - * @return whether a paragraph was actually added. - */ - private boolean paragraphWrap(Element parent, int index, - List contents) { - if (contents == null || contents.size() <= 0) + /** + * Wrap the given set of contents into a paragraph and place it at the + * supplied index. + * + * This method will also check for trivial paragraphs, i.e. those that + * contain nothing but white space. If they are found then they are removed. + * + * @param parent + * The parent element to attach the wrapped paragraph, too. + * @param index + * The index within the parent for where the content should be + * attached. + * @param contents + * The contents that should be wrapped in a paragraph. + * @return whether a paragraph was actually added. + */ + private boolean paragraphWrap(Element parent, int index, + List contents) + { + if (contents == null || contents.size() <= 0) { return false; } - boolean empty = true; - for (Content content : contents) { - if (!empty) + boolean empty = true; + for (Content content : contents) + { + if (!empty) { continue; } - if (content instanceof Text) { - Text text = (Text) content; - if (!"".equals(text.getTextNormalize())) + if (content instanceof Text) + { + Text text = (Text) content; + if (!"".equals(text.getTextNormalize())) { empty = false; } - } else { - empty = false; - } - } + } + else + { + empty = false; + } + } - if (empty) + if (empty) { return false; } - // May be useful for debugging: - // contents.add(0, new Text("("+index+") ")); + // May be useful for debugging: + // contents.add(0, new Text("("+index+") ")); - Element para = new Element(Para.E_PARA); - para.addContent(contents); - if (index >= 0) + Element para = new Element(Para.E_PARA); + para.addContent(contents); + if (index >= 0) { parent.addContent(index, para); } - else + else { parent.addContent(para); } - return true; - } + return true; + } - /** - * Ensure that the given element only has the supplied attributes. Also - * remove any possible namespaces on the attributes. - * - * @param element - * The element to be checked. - * @param names - * A list of all allowed attribute names, all others will be - * removed. - */ - private void limitAttributes(Element element, String... names) { - Map attributes = new HashMap<>(); - for (String name : names) { - String value = element.getAttributeValue(name); - if (value != null) + /** + * Ensure that the given element only has the supplied attributes. Also + * remove any possible namespaces on the attributes. + * + * @param element + * The element to be checked. + * @param names + * A list of all allowed attribute names, all others will be + * removed. + */ + private void limitAttributes(Element element, String... names) + { + Map attributes = new HashMap<>(); + for (String name : names) + { + String value = element.getAttributeValue(name); + if (value != null) { attributes.put(name, value); } - } + } - element.setAttributes(new ArrayList()); + element.setAttributes(new ArrayList()); - for (Map.Entry attr : attributes.entrySet()) { - element.setAttribute(attr.getKey(), attr.getValue()); - } - } + for (Map.Entry attr : attributes.entrySet()) + { + element.setAttribute(attr.getKey(), attr.getValue()); + } + } - /** - * Move the old attribute to a new attribute. - * - * @param element - * The element - * @param oldName - * The old attribute's name. - * @param newName - * The new attribute's name. - */ - private void moveAttribute(Element element, String oldName, String newName) { - Attribute attribute = element.getAttribute(oldName); - if (attribute != null) + /** + * Move the old attribute to a new attribute. + * + * @param element + * The element + * @param oldName + * The old attribute's name. + * @param newName + * The new attribute's name. + */ + private void moveAttribute(Element element, String oldName, String newName) + { + Attribute attribute = element.getAttribute(oldName); + if (attribute != null) { attribute.setName(newName); } - } + } - /** - * Translate the given HTML fragment into a DRI document. - * - * The translation is broken up into two steps, 1) recurse through all - * elements and either translate them into their DRI equivalents or remove - * them from the document. - * - * The second step, 2) is to iterate over all top level elements and ensure - * that they only consist of paragraphs. Also at this stage if linkBreaks is - * true then \n are treated as paragraph breaks. - * - * @param parent - * The Element to translate into DRI. - */ - private void translate(Element parent) { - // Step 1: - // Recurse through all elements and either - // translate them or remove them. - for (int i = 0; i < parent.getContentSize(); i++) { - Content decedent = parent.getContent(i); + /** + * Translate the given HTML fragment into a DRI document. + * + * The translation is broken up into two steps, 1) recurse through all + * elements and either translate them into their DRI equivalents or remove + * them from the document. + * + * The second step, 2) is to iterate over all top level elements and ensure + * that they only consist of paragraphs. Also at this stage if linkBreaks is + * true then \n are treated as paragraph breaks. + * + * @param parent + * The Element to translate into DRI. + */ + private void translate(Element parent) + { + // Step 1: + // Recurse through all elements and either + // translate them or remove them. + for (int i = 0; i < parent.getContentSize(); i++) + { + Content decedent = parent.getContent(i); - if (decedent instanceof org.jdom.Text) { + if (decedent instanceof org.jdom.Text) + { - } else if (decedent instanceof Element) { - Element element = (Element) decedent; - String name = element.getName(); + } + else if (decedent instanceof Element) + { + Element element = (Element) decedent; + String name = element.getName(); - // First all the DRI elements, allow them to pass. - if ("p".equals(name)) { - // Paragraphs are tricky, it may be either an HTML - // or DRI

    element. However, while HTML will allow - //

    to nest DRI does not, thus first we need to - // check if this is at the block level, if it is then - // we need remove it. + // First all the DRI elements, allow them to pass. + if ("p".equals(name)) + { + // Paragraphs are tricky, it may be either an HTML + // or DRI

    element. However, while HTML will allow + //

    to nest DRI does not, thus first we need to + // check if this is at the block level, if it is then + // we need remove it. - if (parent.isRootElement()) { - // The paragraph is not nested, so translate it to - // a DRI

    - moveAttribute(element, "class", "rend"); - limitAttributes(element, "id", "n", "rend"); + if (parent.isRootElement()) + { + // The paragraph is not nested, so translate it to + // a DRI

    + moveAttribute(element, "class", "rend"); + limitAttributes(element, "id", "n", "rend"); - translate(element); - } else { - // The paragraph is nested which is not allowed in - // DRI, so remove it. - removeContent(element); - } - } else if ("h1".equals(name) || "h2".equals(name) - || "h3".equals(name) || "h4".equals(name) - || "h5".equals(name)) { - // The HTML

    tag is translated into the DRI - //

    tag. - if (parent.isRootElement()) { - limitAttributes(element); - element.setName("p"); - element.setAttribute("rend", "heading"); + translate(element); + } + else + { + // The paragraph is nested which is not allowed in + // DRI, so remove it. + removeContent(element); + } + } + else if ("h1".equals(name) || "h2".equals(name) || + "h3".equals(name) || "h4".equals(name) || + "h5".equals(name)) + { + // The HTML

    tag is translated into the DRI + //

    tag. + if (parent.isRootElement()) + { + limitAttributes(element); + element.setName("p"); + element.setAttribute("rend", "heading"); - translate(element); - } else { - // DRI paragraphs can not be nested. - removeContent(element); - } - } else if ("a".equals(name)) { - // The HTML tag is translated into the DRI - // tag. - moveAttribute(element, "href", "target"); - limitAttributes(element, "target"); - element.setName("xref"); + translate(element); + } + else + { + // DRI paragraphs can not be nested. + removeContent(element); + } + } + else if ("a".equals(name)) + { + // The HTML tag is translated into the DRI + // tag. + moveAttribute(element, "href", "target"); + limitAttributes(element, "target"); + element.setName("xref"); - translate(element); - } else if ("ol".equals(name)) { - // the HTML tag

      its translated into the DRI - // tag - // - moveAttribute(element, "class", "rend"); - limitAttributes(element, "id", "n", "rend"); - element.setName("list"); - element.setAttribute("type", "ordered"); - translate(element); - } else if ("li".equals(name)) { - // the HTML tag
    1. its translated into the DRI - // tag - moveAttribute(element, "class", "rend"); - limitAttributes(element, "id", "n", "rend"); - element.setName("item"); - translate(element); - } else if ("b".equals(name)) { - // The HTML tag is translated to a highlight - // element with a rend of bold. - limitAttributes(element); - element.setName("hi"); - element.setAttribute("rend", "bold"); + translate(element); + } + else if ("ol".equals(name)) + { + // the HTML tag
        its translated into the DRI + // tag + // + moveAttribute(element, "class", "rend"); + limitAttributes(element, "id", "n", "rend"); + element.setName("list"); + element.setAttribute("type", "ordered"); + translate(element); + } + else if ("li".equals(name)) + { + // the HTML tag
      1. its translated into the DRI + // tag + moveAttribute(element, "class", "rend"); + limitAttributes(element, "id", "n", "rend"); + element.setName("item"); + translate(element); + } + else if ("b".equals(name)) + { + // The HTML tag is translated to a highlight + // element with a rend of bold. + limitAttributes(element); + element.setName("hi"); + element.setAttribute("rend", "bold"); - translate(element); - } else if ("i".equals(name)) { - // The HTML tag is translated to a highlight - // element with a rend of italic. - limitAttributes(element); - element.setName("hi"); - element.setAttribute("rend", "italic"); + translate(element); + } + else if ("i".equals(name)) + { + // The HTML tag is translated to a highlight + // element with a rend of italic. + limitAttributes(element); + element.setName("hi"); + element.setAttribute("rend", "italic"); - translate(element); - } else if ("u".equals(name)) { - // The HTML tag is translated to a highlight - // element with a rend of underline. - limitAttributes(element); - element.setName("hi"); - element.setAttribute("rend", "underline"); + translate(element); + } + else if ("u".equals(name)) + { + // The HTML tag is translated to a highlight + // element with a rend of underline. + limitAttributes(element); + element.setName("hi"); + element.setAttribute("rend", "underline"); - translate(element); - } else if ("img".equals(name)) { - // The HTML element is translated into a DRI figure - moveAttribute(element, "src", "source"); - limitAttributes(element, "source"); - element.setName("figure"); + translate(element); + } + else if ("img".equals(name)) + { + // The HTML element is translated into a DRI figure + moveAttribute(element, "src", "source"); + limitAttributes(element, "source"); + element.setName("figure"); - translate(element); - } - // Next all the DRI elements that we allow to pass through. - else if ("hi".equals(name)) { - limitAttributes(element, "rend"); + translate(element); + } + // Next all the DRI elements that we allow to pass through. + else if ("hi".equals(name)) { + limitAttributes(element, "rend"); - translate(element); - } else if ("xref".equals(name)) { - limitAttributes(element, "target"); + translate(element); + } + else if ("xref".equals(name)) + { + limitAttributes(element, "target"); - translate(element); - } else if ("figure".equals(name)) { - limitAttributes(element, "rend", "source", "target"); + translate(element); + } + else if ("figure".equals(name)) + { + limitAttributes(element, "rend", "source", "target"); - translate(element); - } else { - removeContent(decedent); - } - } else { - removeContent(decedent); - } - } + translate(element); + } + else + { + removeContent(decedent); + } + } + else + { + removeContent(decedent); + } + } - // Step 2: - // Ensure that all top level elements are encapsulated inside - // a block level element (i.e. a paragraph) - if (parent.isRootElement()) { - List removed = new ArrayList<>(); - for (int i = 0; i < parent.getContentSize(); i++) { - Content current = parent.getContent(i); - - if ((current instanceof Element) - && ("p".equals(((Element) current).getName()))) { - // A paragraph is being open, combine anything up to this - // point into a paragraph. - if (paragraphWrap(parent, i, removed)) { - removed.clear(); - i++; // account for the field added - } - } else if ((current instanceof Element) - && ("list".equals(((Element) current).getName()))) { - if (paragraphWrap(parent, i, removed)) { - removed.clear(); - i++; // account for the field added - } - } else { - // If we break paragraphs based upon blank lines then we - // need to check if - // there are any in this text element. - if (this.blankLines && current instanceof Text) { - String rawText = ((Text) current).getText(); - parent.removeContent(current); - i--;// account text field removed. + // Step 2: + // Ensure that all top level elements are encapsulated inside + // a block level element (i.e. a paragraph) + if (parent.isRootElement()) { + List removed = new ArrayList<>(); + for (int i = 0; i < parent.getContentSize(); i++) { + Content current = parent.getContent(i); - // Regular expression to split based upon blank lines. - // FIXME: This may not work for windows people who - // insist on using \r\n for line breaks. - @SuppressWarnings("unchecked") + if ((current instanceof Element) + && ("p".equals(((Element) current).getName()))) { + // A paragraph is being open, combine anything up to this + // point into a paragraph. + if (paragraphWrap(parent, i, removed)) { + removed.clear(); + i++; // account for the field added + } + } else if ((current instanceof Element) + && ("list".equals(((Element) current).getName()))) { + if (paragraphWrap(parent, i, removed)) { + removed.clear(); + i++; // account for the field added + } + } + else + { + // If we break paragraphs based upon blank lines then we + // need to check if + // there are any in this text element. + if (this.blankLines && current instanceof Text) { + String rawText = ((Text) current).getText(); + parent.removeContent(current); + i--;// account text field removed. + + // Regular expression to split based upon blank lines. + // FIXME: This may not work for windows people who + // insist on using \r\n for line breaks. + @SuppressWarnings("unchecked") String[] parts = rawText.split("\n\\s*\n"); if (parts.length > 0) { for (int partIdx = 0; partIdx < parts.length - 1; partIdx++) { @@ -495,178 +562,179 @@ public class SimpleHTMLFragment extends AbstractWingElement { removed.add(new Text(parts[parts.length - 1])); } - } else { - removed.add(current); - parent.removeContent(current); - i--; // move back to account for the removed content. - } - } - } + } + else + { + removed.add(current); + parent.removeContent(current); + i--; // move back to account for the removed content. + } + } + } - // if anything is left, wrap it up in a para also. - if (removed.size() > 0) { - paragraphWrap(parent, -1, removed); - removed.clear(); - } - } - } + // if anything is left, wrap it up in a para also. + if (removed.size() > 0) { + paragraphWrap(parent, -1, removed); + removed.clear(); + } + } + } - /** - * This is a simple SAX Handler that filters out start and end documents. - * This class is needed for two reasons, 1) namespaces need to be corrected - * from the originating HTML fragment, 2) to get around a JDOM bug where it - * can not output SAX events for just a document fragment. Since it only - * works with documents this class was created to filter out the events. - * - *

        As far as I can tell, the first time the bug was identified is in the - * following email, point #1: - * - * + /** + * This is a simple SAX Handler that filters out start and end documents. + * This class is needed for two reasons, 1) namespaces need to be corrected + * from the originating HTML fragment, 2) to get around a JDOM bug where it + * can not output SAX events for just a document fragment. Since it only + * works with documents this class was created to filter out the events. + * + *

        As far as I can tell, the first time the bug was identified is in the + * following email, point #1: + * + * * {@literal http://www.servlets.com/archive/servlet/ReadMsg?msgId=491592&listName=jdom-interest} * - * - *

        I, Scott Phillips, checked the JDOM CVS source tree on 3-8-2006 and the - * bug had not been patched at that time. - */ - public static class SAXFilter implements ContentHandler, LexicalHandler { + * + *

        I, Scott Phillips, checked the JDOM CVS source tree on 3-8-2006 and the + * bug had not been patched at that time. + */ + public static class SAXFilter implements ContentHandler, LexicalHandler { - private final String URI = WingConstants.DRI.URI; + private final String URI = WingConstants.DRI.URI; - private final ContentHandler contentHandler; + private final ContentHandler contentHandler; - // private LexicalHandler lexicalHandler; may be used in the future - private final NamespaceSupport namespaces; + // private LexicalHandler lexicalHandler; may be used in the future + private final NamespaceSupport namespaces; - public SAXFilter(ContentHandler contentHandler, - LexicalHandler lexicalHandler, NamespaceSupport namespaces) { - this.contentHandler = contentHandler; - // this.lexicalHandler = lexicalHandler; - this.namespaces = namespaces; - } + public SAXFilter(ContentHandler contentHandler, + LexicalHandler lexicalHandler, NamespaceSupport namespaces) { + this.contentHandler = contentHandler; + // this.lexicalHandler = lexicalHandler; + this.namespaces = namespaces; + } - /** - * Create the qName for the element with the given localName and - * namespace prefix. - * - * @param localName - * (Required) The element's local name. - * @return - */ - private String qName(String localName) { - String prefix = namespaces.getPrefix(URI); + /** + * Create the qName for the element with the given localName and + * namespace prefix. + * + * @param localName + * (Required) The element's local name. + * @return + */ + private String qName(String localName) { + String prefix = namespaces.getPrefix(URI); - if (prefix == null || prefix.equals("")) + if (prefix == null || prefix.equals("")) { return localName; } - else + else { return prefix + ":" + localName; } - } + } - /** ContentHandler methods: */ + /** ContentHandler methods: */ @Override - public void endDocument() { - // Filter out endDocument events - } + public void endDocument() { + // Filter out endDocument events + } @Override - public void startDocument() { - // filter out startDocument events - } + public void startDocument() { + // filter out startDocument events + } @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - contentHandler.characters(ch, start, length); - } + public void characters(char[] ch, int start, int length) + throws SAXException { + contentHandler.characters(ch, start, length); + } @Override - public void endElement(String uri, String localName, String qName) - throws SAXException { + public void endElement(String uri, String localName, String qName) + throws SAXException { - contentHandler.endElement(URI, localName, qName(localName)); - } + contentHandler.endElement(URI, localName, qName(localName)); + } @Override - public void endPrefixMapping(String prefix) throws SAXException { - // No namespaces may be declared. - } + public void endPrefixMapping(String prefix) throws SAXException { + // No namespaces may be declared. + } @Override - public void ignorableWhitespace(char[] ch, int start, int length) - throws SAXException { - contentHandler.ignorableWhitespace(ch, start, length); - } + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + contentHandler.ignorableWhitespace(ch, start, length); + } @Override - public void processingInstruction(String target, String data) - throws SAXException { - // filter out processing instructions - } + public void processingInstruction(String target, String data) + throws SAXException { + // filter out processing instructions + } @Override - public void setDocumentLocator(Locator locator) { - // filter out document locators - } + public void setDocumentLocator(Locator locator) { + // filter out document locators + } @Override - public void skippedEntity(String name) throws SAXException { - contentHandler.skippedEntity(name); - } + public void skippedEntity(String name) throws SAXException { + contentHandler.skippedEntity(name); + } @Override - public void startElement(String uri, String localName, String qName, - Attributes atts) throws SAXException { - contentHandler.startElement(URI, localName, qName(localName), atts); - } + public void startElement(String uri, String localName, String qName, + Attributes atts) throws SAXException { + contentHandler.startElement(URI, localName, qName(localName), atts); + } @Override - public void startPrefixMapping(String prefix, String uri) - throws SAXException { - // No namespaces can be declared. - } + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + // No namespaces can be declared. + } - /* Lexical Handler methods: */ + /* Lexical Handler methods: */ @Override - public void startDTD(String name, String publicId, String systemId) - throws SAXException { - // filter out DTDs - } + public void startDTD(String name, String publicId, String systemId) + throws SAXException { + // filter out DTDs + } @Override - public void endDTD() throws SAXException { - // filter out DTDs - } + public void endDTD() throws SAXException { + // filter out DTDs + } @Override - public void startEntity(String name) throws SAXException { - // filter out Entities - } + public void startEntity(String name) throws SAXException { + // filter out Entities + } @Override - public void endEntity(String name) throws SAXException { - // filter out Entities - } + public void endEntity(String name) throws SAXException { + // filter out Entities + } @Override - public void startCDATA() throws SAXException { - // filter out CDATA - } + public void startCDATA() throws SAXException { + // filter out CDATA + } @Override - public void endCDATA() throws SAXException { - // filter out CDATA - } + public void endCDATA() throws SAXException { + // filter out CDATA + } @Override - public void comment(char[] ch, int start, int length) - throws SAXException { - // filter out comments; - } - } + public void comment(char[] ch, int start, int length) + throws SAXException { + // filter out comments; + } + } } - diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/UserMeta.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/UserMeta.java index 52ba201844..cd80f489f6 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/UserMeta.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/wing/element/UserMeta.java @@ -23,7 +23,7 @@ import org.xml.sax.helpers.NamespaceSupport; /** * A class representing a set of metadata about the user generating this page. - * + * * @author Scott Phillips */ public class UserMeta extends AbstractWingElement implements @@ -46,20 +46,21 @@ public class UserMeta extends AbstractWingElement implements /** * Construct a new userMeta - * + * * @param context * (Required) The context this element is contained in, such as * where to route SAX events and what i18n catalogue to use. * @throws org.dspace.app.xmlui.wing.WingException passed through. */ - protected UserMeta(WingContext context) throws WingException + protected UserMeta(WingContext context) + throws WingException { super(context); } /** * Set the user described in the meta object as authenticated. - * + * * @param authenticated * (Required) True if the user is authenticated, false otherwise. */ @@ -69,22 +70,23 @@ public class UserMeta extends AbstractWingElement implements } /** - * Add metadata about the requesting user to the document. - * - * @param element - * (Required) The metadata element. - * @param qualifier - * (May be null) The metadata qualifier. - * @param language - * (May be null) The metadata's language - * @param allowMultiple - * (Required) determine if multiple metadata elements with the same - * element, qualifier and language are allowed. - * @return A new metadata + * Add metadata about the requesting user to the document. + * + * @param element + * (Required) The metadata element. + * @param qualifier + * (May be null) The metadata qualifier. + * @param language + * (May be null) The metadata's language + * @param allowMultiple + * (Required) determine if multiple metadata elements with the same + * element, qualifier and language are allowed. + * @return A new metadata * @throws org.dspace.app.xmlui.wing.WingException passed through. - */ + */ public Metadata addMetadata(String element, String qualifier, - String language, boolean allowMultiple) throws WingException + String language, boolean allowMultiple) + throws WingException { Metadata metadata = new Metadata(context, element, qualifier, language, allowMultiple); metadatum.add(metadata); @@ -93,7 +95,7 @@ public class UserMeta extends AbstractWingElement implements /** * Add metadata about the requesting user to the document. - * + * * @param element * (Required) The metadata element. * @param qualifier @@ -104,14 +106,15 @@ public class UserMeta extends AbstractWingElement implements * @throws org.dspace.app.xmlui.wing.WingException passed through. */ public Metadata addMetadata(String element, String qualifier, - String language) throws WingException + String language) + throws WingException { - return addMetadata(element, qualifier, null, false); + return addMetadata(element, qualifier, null, false); } - + /** * Add metadata about the requesting user to the document. - * + * * @param element * (Required) The metadata element. * @param qualifier @@ -120,27 +123,28 @@ public class UserMeta extends AbstractWingElement implements * @throws org.dspace.app.xmlui.wing.WingException passed through. */ public Metadata addMetadata(String element, String qualifier) - throws WingException + throws WingException { return addMetadata(element, qualifier, null, false); } /** * Add metadata about the requesting user to the document. - * + * * @param element * (Required) The metadata element. * @return A new metadata * @throws org.dspace.app.xmlui.wing.WingException passed through. */ - public Metadata addMetadata(String element) throws WingException + public Metadata addMetadata(String element) + throws WingException { return addMetadata(element, null, null, false); } /** * Determine if the given SAX event is a UserMeta element. - * + * * @param namespace * The element's name space * @param localName @@ -153,7 +157,8 @@ public class UserMeta extends AbstractWingElement implements */ @Override public boolean mergeEqual(String namespace, String localName, String qName, - Attributes attributes) throws SAXException, WingException + Attributes attributes) + throws SAXException, WingException { if (!WingConstants.DRI.URI.equals(namespace)) @@ -171,7 +176,7 @@ public class UserMeta extends AbstractWingElement implements /** * Since metadata can not be merged there are no mergeable children. This * just return's null. - * + * * @param namespace * The element's name space * @param localName @@ -184,36 +189,36 @@ public class UserMeta extends AbstractWingElement implements */ @Override public WingMergeableElement mergeChild(String namespace, String localName, - String qName, Attributes attributes) throws SAXException, - WingException + String qName, Attributes attributes) + throws SAXException, WingException { - // We don't merge our children but we do have one special optimization: - // if a metadata is already in the document and it is tagged as not allowing - // multiples then we do not add the new metadata to the document. - - if (WingConstants.DRI.URI.equals(namespace) && Metadata.E_METADATA.equals(localName)) - { - String element = attributes.getValue(Metadata.A_ELEMENT); - String qualifier = attributes.getValue(Metadata.A_QUALIFIER); - String language = attributes.getValue(Metadata.A_LANGUAGE); - - List remove = new ArrayList(); - for (Metadata metadata : metadatum) - { - if (metadata.equals(element,qualifier,language) && !metadata.allowMultiple()) - { - remove.add(metadata); - } - } - - // Remove all the metadata elements we found. - for (Metadata metadata : remove) - { - metadata.dispose(); - metadatum.remove(metadata); - } - } - + // We don't merge our children but we do have one special optimization: + // if a metadata is already in the document and it is tagged as not allowing + // multiples then we do not add the new metadata to the document. + + if (WingConstants.DRI.URI.equals(namespace) && Metadata.E_METADATA.equals(localName)) + { + String element = attributes.getValue(Metadata.A_ELEMENT); + String qualifier = attributes.getValue(Metadata.A_QUALIFIER); + String language = attributes.getValue(Metadata.A_LANGUAGE); + + List remove = new ArrayList(); + for (Metadata metadata : metadatum) + { + if (metadata.equals(element,qualifier,language) && !metadata.allowMultiple()) + { + remove.add(metadata); + } + } + + // Remove all the metadata elements we found. + for (Metadata metadata : remove) + { + metadata.dispose(); + metadatum.remove(metadata); + } + } + return null; } @@ -221,8 +226,8 @@ public class UserMeta extends AbstractWingElement implements * Inform this element that it is being merged with an existing element. */ @Override - public Attributes merge(Attributes attributes) throws SAXException, - WingException + public Attributes merge(Attributes attributes) + throws SAXException, WingException { this.merged = true; @@ -244,12 +249,12 @@ public class UserMeta extends AbstractWingElement implements int index = attributesImpl.getIndex(A_AUTHENTICATED); if (index >= 0) { - attributesImpl.setValue(index,"yes"); - } + attributesImpl.setValue(index,"yes"); + } else { - attributesImpl.addAttribute("", - A_AUTHENTICATED, A_AUTHENTICATED, "CDATA", "yes"); + attributesImpl.addAttribute("", + A_AUTHENTICATED, A_AUTHENTICATED, "CDATA", "yes"); } attributes = attributesImpl; } @@ -269,12 +274,12 @@ public class UserMeta extends AbstractWingElement implements /** * Translate this element into SAX events. - * + * * @param contentHandler * (Required) The registered contentHandler where SAX events * should be routed too. * @param lexicalHandler - * (Required) The registered lexicalHandler where lexical + * (Required) The registered lexicalHandler where lexical * events (such as CDATA, DTD, etc) should be routed too. * @param namespaces * (Required) SAX Helper class to keep track of namespaces able @@ -282,7 +287,8 @@ public class UserMeta extends AbstractWingElement implements */ @Override public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler, - NamespaceSupport namespaces) throws SAXException + NamespaceSupport namespaces) + throws SAXException { if (!merged) { diff --git a/dspace-xmlui/src/main/java/org/dspace/springmvc/BibTexView.java b/dspace-xmlui/src/main/java/org/dspace/springmvc/BibTexView.java index 64a84f2081..302a64dba0 100644 --- a/dspace-xmlui/src/main/java/org/dspace/springmvc/BibTexView.java +++ b/dspace-xmlui/src/main/java/org/dspace/springmvc/BibTexView.java @@ -36,13 +36,13 @@ import java.util.StringTokenizer; public class BibTexView implements View { - private static final Logger LOGGER = LoggerFactory.getLogger(BibTexView.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BibTexView.class); private static final String EOL = "\r\n"; - private String resourceIdentifier=null; - + private String resourceIdentifier = null; + protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - + public String getContentType() { @@ -71,22 +71,22 @@ public class BibTexView implements View { } private void write(HttpServletResponse aResponse, String aContent, String aFileName) throws IOException { - aResponse.setContentType("text/plain;charset=utf-8"); - aResponse.setContentLength(aContent.length()); - aResponse.setHeader("Content-Disposition", "attachment; filename=\"" - + aFileName + "\""); + aResponse.setContentType("text/plain;charset=utf-8"); + aResponse.setContentLength(aContent.length()); + aResponse.setHeader("Content-Disposition", "attachment; filename=\"" + + aFileName + "\""); - // It's all over but the writing... - PrintWriter writer = aResponse.getWriter(); - writer.print(aContent); - writer.close(); - } + // It's all over but the writing... + PrintWriter writer = aResponse.getWriter(); + writer.print(aContent); + writer.close(); + } private String getFileName(DSpaceObject item) { String fileName = resourceIdentifier; - if(resourceIdentifier.lastIndexOf("/") !=-1) + if (resourceIdentifier.lastIndexOf("/") != -1) { fileName = resourceIdentifier.replaceAll("/", "_") + ".bib"; } @@ -96,43 +96,43 @@ public class BibTexView implements View { private String getBibTex(Item item, String resourceIdentifier) { - // No standardized format for data so using 'misc' for now - StringBuilder builder = new StringBuilder("@misc{"); + // No standardized format for data so using 'misc' for now + StringBuilder builder = new StringBuilder("@misc{"); - String[] authors = getAuthors(item); - String year = getYear(item); + String[] authors = getAuthors(item); + String year = getYear(item); String title = getMetadataValue(item, "dc.title"); - builder.append(resourceIdentifier).append(',').append(EOL); + builder.append(resourceIdentifier).append(',').append(EOL); - if (title != null) { - builder.append(" title = {").append(title).append("},"); - builder.append(EOL); - } + if (title != null) { + builder.append(" title = {").append(title).append("},"); + builder.append(EOL); + } - if (authors.length > 0) { - builder.append(" author = {"); + if (authors.length > 0) { + builder.append(" author = {"); - // Bibtex needs the comma... do we want full names here? - for (int index = 0; index < authors.length; index++) { - if (index + 1 >= authors.length) { // last one - builder.append(authors[index].replace(" ", ", ")); - } - else if (index + 1 < authors.length) { // not last one - builder.append(authors[index].replace(" ", ", ")); - builder.append(" and "); - } - } + // Bibtex needs the comma... do we want full names here? + for (int index = 0; index < authors.length; index++) { + if (index + 1 >= authors.length) { // last one + builder.append(authors[index].replace(" ", ", ")); + } + else if (index + 1 < authors.length) { // not last one + builder.append(authors[index].replace(" ", ", ")); + builder.append(" and "); + } + } - builder.append("},").append(EOL); - } + builder.append("},").append(EOL); + } - if (year != null) { - builder.append(" year = {").append(year).append("},").append(EOL); - } + if (year != null) { + builder.append(" year = {").append(year).append("},").append(EOL); + } - return builder.append("}").append(EOL).toString(); - } + return builder.append("}").append(EOL).toString(); + } private String getMetadataValue(Item item, String metadatafield) { @@ -215,5 +215,4 @@ public class BibTexView implements View { } return authors; } - } diff --git a/dspace-xmlui/src/main/java/org/dspace/springmvc/RisView.java b/dspace-xmlui/src/main/java/org/dspace/springmvc/RisView.java index 4115140c2d..6b07d21f4a 100644 --- a/dspace-xmlui/src/main/java/org/dspace/springmvc/RisView.java +++ b/dspace-xmlui/src/main/java/org/dspace/springmvc/RisView.java @@ -37,12 +37,12 @@ import java.util.StringTokenizer; public class RisView implements View { - private static final Logger LOGGER = LoggerFactory.getLogger(RisView.class); + private static final Logger LOGGER = LoggerFactory.getLogger(RisView.class); private static final String EOL = "\r\n"; - private String resourceIdentifier=null; + private String resourceIdentifier = null; protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); - + public RisView(String resourceIdentifier) { this.resourceIdentifier = resourceIdentifier; @@ -50,11 +50,12 @@ public class RisView implements View { public String getContentType() { - return "text/plain;charset=utf-8"; } - public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { + public void render(Map model, HttpServletRequest request, HttpServletResponse response) + throws Exception + { DSpaceObject item = (DSpaceObject)request.getAttribute(ResourceIdentifierController.DSPACE_OBJECT); @@ -71,87 +72,88 @@ public class RisView implements View { private String getFileName(DSpaceObject item) { String fileName = resourceIdentifier; - if(resourceIdentifier.indexOf("/") !=-1) + if (resourceIdentifier.indexOf("/") !=-1) { fileName = resourceIdentifier.replaceAll("/", "_") + ".ris"; } return fileName; } - private void write(HttpServletResponse aResponse, String aContent, String aFileName) throws IOException + private void write(HttpServletResponse aResponse, String aContent, String aFileName) + throws IOException { - aResponse.setContentType("text/plain;charset=utf-8"); - aResponse.setContentLength(aContent.length()); - aResponse.setHeader("Content-Disposition", "attachment; filename=\"" + aFileName + "\""); + aResponse.setContentType("text/plain;charset=utf-8"); + aResponse.setContentLength(aContent.length()); + aResponse.setHeader("Content-Disposition", "attachment; filename=\"" + aFileName + "\""); - // It's all over but the writing... - PrintWriter writer = aResponse.getWriter(); - writer.print(aContent); - writer.close(); - } + // It's all over but the writing... + PrintWriter writer = aResponse.getWriter(); + writer.print(aContent); + writer.close(); + } private String getRIS(Item item, String resourceIdentifier) { - StringBuilder builder = new StringBuilder("TY - DATA").append(EOL); + StringBuilder builder = new StringBuilder("TY - DATA").append(EOL); String[] dateParts = getDate(item); - String title = getMetadataValue(item, "dc.title"); - String description = getMetadataValue(item, "dc.description"); + String title = getMetadataValue(item, "dc.title"); + String description = getMetadataValue(item, "dc.description"); String[] keywords = getKeywords(item); - if (resourceIdentifier != null) + if (resourceIdentifier != null) { - builder.append("ID - ").append(resourceIdentifier).append(EOL); - } + builder.append("ID - ").append(resourceIdentifier).append(EOL); + } - if (title != null) + if (title != null) { - builder.append("T1 - ").append(title).append(EOL); - } + builder.append("T1 - ").append(title).append(EOL); + } - for (String author : getAuthors(item)) { - builder.append("AU - ").append(author).append(EOL); - } + for (String author : getAuthors(item)) { + builder.append("AU - ").append(author).append(EOL); + } - // Date for data package - if (dateParts.length > 0) + // Date for data package + if (dateParts.length > 0) { - int count = 3; + int count = 3; - builder.append("Y1 - "); + builder.append("Y1 - "); - if (dateParts.length < 3) + if (dateParts.length < 3) { - count = dateParts.length; - } + count = dateParts.length; + } - for (int index = 0; index < count; index++) { - builder.append(dateParts[index]).append("/"); - } + for (int index = 0; index < count; index++) { + builder.append(dateParts[index]).append("/"); + } - for (; count < 3; count++) + for (; count < 3; count++) { - builder.append('/'); - } + builder.append('/'); + } - builder.append(EOL); - } + builder.append(EOL); + } - if (description != null) + if (description != null) { - builder.append("N2 - ").append(description).append(EOL); - } + builder.append("N2 - ").append(description).append(EOL); + } - for (String keyword : keywords) + for (String keyword : keywords) { - builder.append("KW - ").append(keyword).append(EOL); - } + builder.append("KW - ").append(keyword).append(EOL); + } - return builder.append("ER - ").append(EOL).toString(); - } + return builder.append("ER - ").append(EOL).toString(); + } private String[] getAuthors(Item aItem) diff --git a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/HttpException.java b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/HttpException.java index 6f62782a6d..51b6177d68 100644 --- a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/HttpException.java +++ b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/HttpException.java @@ -17,24 +17,24 @@ package org.dspace.sword.client.exceptions; public class HttpException extends Exception { - public HttpException() - { - super(); - } + public HttpException() + { + super(); + } - public HttpException(String arg0, Throwable arg1) - { - super(arg0, arg1); - } + public HttpException(String arg0, Throwable arg1) + { + super(arg0, arg1); + } - public HttpException(String arg0) - { - super(arg0); - } + public HttpException(String arg0) + { + super(arg0); + } - public HttpException(Throwable arg0) - { - super(arg0); - } + public HttpException(Throwable arg0) + { + super(arg0); + } -} \ No newline at end of file +} diff --git a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/InvalidHandleException.java b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/InvalidHandleException.java index 99e543fc9e..d4a5f71567 100644 --- a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/InvalidHandleException.java +++ b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/InvalidHandleException.java @@ -17,24 +17,24 @@ package org.dspace.sword.client.exceptions; public class InvalidHandleException extends Exception { - public InvalidHandleException() - { - super(); - } + public InvalidHandleException() + { + super(); + } - public InvalidHandleException(String arg0, Throwable arg1) - { - super(arg0, arg1); - } + public InvalidHandleException(String arg0, Throwable arg1) + { + super(arg0, arg1); + } - public InvalidHandleException(String arg0) - { - super(arg0); - } + public InvalidHandleException(String arg0) + { + super(arg0); + } - public InvalidHandleException(Throwable arg0) - { - super(arg0); - } + public InvalidHandleException(Throwable arg0) + { + super(arg0); + } -} \ No newline at end of file +} diff --git a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackageFormatException.java b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackageFormatException.java index 4898e8831a..5c89494016 100644 --- a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackageFormatException.java +++ b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackageFormatException.java @@ -17,24 +17,24 @@ package org.dspace.sword.client.exceptions; public class PackageFormatException extends Exception { - public PackageFormatException() - { - super(); - } + public PackageFormatException() + { + super(); + } - public PackageFormatException(String arg0, Throwable arg1) - { - super(arg0, arg1); - } + public PackageFormatException(String arg0, Throwable arg1) + { + super(arg0, arg1); + } - public PackageFormatException(String arg0) - { - super(arg0); - } + public PackageFormatException(String arg0) + { + super(arg0); + } - public PackageFormatException(Throwable arg0) - { - super(arg0); - } + public PackageFormatException(Throwable arg0) + { + super(arg0); + } -} \ No newline at end of file +} diff --git a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackagerException.java b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackagerException.java index 7544f49dee..3d0fba0516 100644 --- a/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackagerException.java +++ b/dspace-xmlui/src/main/java/org/dspace/sword/client/exceptions/PackagerException.java @@ -17,24 +17,24 @@ package org.dspace.sword.client.exceptions; public class PackagerException extends Exception { - public PackagerException() - { - super(); - } + public PackagerException() + { + super(); + } - public PackagerException(String arg0, Throwable arg1) - { - super(arg0, arg1); - } + public PackagerException(String arg0, Throwable arg1) + { + super(arg0, arg1); + } - public PackagerException(String arg0) - { - super(arg0); - } + public PackagerException(String arg0) + { + super(arg0); + } - public PackagerException(Throwable arg0) - { - super(arg0); - } + public PackagerException(Throwable arg0) + { + super(arg0); + } -} \ No newline at end of file +} diff --git a/dspace/config/crosswalks/oai/metadataFormats/didl.xsl b/dspace/config/crosswalks/oai/metadataFormats/didl.xsl index f824970099..51d24d2757 100644 --- a/dspace/config/crosswalks/oai/metadataFormats/didl.xsl +++ b/dspace/config/crosswalks/oai/metadataFormats/didl.xsl @@ -7,7 +7,7 @@ tree and available online at http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) > http://www.openarchives.org/OAI/2.0/oai_dc.xsd diff --git a/dspace/config/crosswalks/oai/metadataFormats/dim.xsl b/dspace/config/crosswalks/oai/metadataFormats/dim.xsl index 9ab34bcab9..dcc96de482 100644 --- a/dspace/config/crosswalks/oai/metadataFormats/dim.xsl +++ b/dspace/config/crosswalks/oai/metadataFormats/dim.xsl @@ -5,7 +5,7 @@ in the LICENSE and NOTICE files at the root of the source tree and available online at http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> + Developed by DSpace @ Lyncode (dspace at lyncode dot com) > http://www.loc.gov/marc/bibliographic/ecbdlist.html diff --git a/dspace/config/crosswalks/oai/metadataFormats/mets.xsl b/dspace/config/crosswalks/oai/metadataFormats/mets.xsl index 64606ccaee..a8cce3dfd8 100644 --- a/dspace/config/crosswalks/oai/metadataFormats/mets.xsl +++ b/dspace/config/crosswalks/oai/metadataFormats/mets.xsl @@ -8,7 +8,7 @@ http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) > http://www.loc.gov/standards/mets/mets.xsd --> diff --git a/dspace/config/crosswalks/oai/metadataFormats/mods.xsl b/dspace/config/crosswalks/oai/metadataFormats/mods.xsl index 7f6cafce1d..4a503b99b2 100644 --- a/dspace/config/crosswalks/oai/metadataFormats/mods.xsl +++ b/dspace/config/crosswalks/oai/metadataFormats/mods.xsl @@ -7,7 +7,7 @@ tree and available online at http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> + Developed by DSpace @ Lyncode (dspace at lyncode dot com) > http://www.openarchives.org/OAI/2.0/oai_dc.xsd diff --git a/dspace/config/crosswalks/oai/metadataFormats/ore.xsl b/dspace/config/crosswalks/oai/metadataFormats/ore.xsl index 539811d25f..1c8085c96e 100644 --- a/dspace/config/crosswalks/oai/metadataFormats/ore.xsl +++ b/dspace/config/crosswalks/oai/metadataFormats/ore.xsl @@ -7,7 +7,7 @@ tree and available online at http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> + Developed by DSpace @ Lyncode (dspace at lyncode dot com) Following Driver Guidelines 2.0: - http://www.driver-support.eu/managers.html#guidelines diff --git a/dspace/config/crosswalks/oai/transformers/openaire.xsl b/dspace/config/crosswalks/oai/transformers/openaire.xsl index 8897e00170..b2b074aa5f 100644 --- a/dspace/config/crosswalks/oai/transformers/openaire.xsl +++ b/dspace/config/crosswalks/oai/transformers/openaire.xsl @@ -7,7 +7,7 @@ http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) Following OpenAIRE Guidelines 1.1: - http://www.openaire.eu/component/content/article/207 diff --git a/dspace/config/crosswalks/oai/xoai.xml b/dspace/config/crosswalks/oai/xoai.xml index 0fd7a0c4b2..9417ce7462 100644 --- a/dspace/config/crosswalks/oai/xoai.xml +++ b/dspace/config/crosswalks/oai/xoai.xml @@ -7,7 +7,7 @@ http://www.dspace.org/license/ - Developed by DSpace @ Lyncode + Developed by DSpace @ Lyncode (dspace at lyncode dot com) --> org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/jspui/pom.xml b/dspace/modules/jspui/pom.xml index 15b5f447d5..55e7c497e9 100644 --- a/dspace/modules/jspui/pom.xml +++ b/dspace/modules/jspui/pom.xml @@ -12,7 +12,7 @@ org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/oai/pom.xml b/dspace/modules/oai/pom.xml index 14ae709d78..2dc97f96bc 100644 --- a/dspace/modules/oai/pom.xml +++ b/dspace/modules/oai/pom.xml @@ -12,7 +12,7 @@ modules org.dspace - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/pom.xml b/dspace/modules/pom.xml index 8c840c0e56..10d61fadbd 100644 --- a/dspace/modules/pom.xml +++ b/dspace/modules/pom.xml @@ -11,7 +11,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT ../../pom.xml diff --git a/dspace/modules/rdf/pom.xml b/dspace/modules/rdf/pom.xml index be2f04ad0e..5a5ab808bf 100644 --- a/dspace/modules/rdf/pom.xml +++ b/dspace/modules/rdf/pom.xml @@ -11,7 +11,7 @@ modules org.dspace - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/rest/pom.xml b/dspace/modules/rest/pom.xml index 9fb60aaba9..636adc7e18 100644 --- a/dspace/modules/rest/pom.xml +++ b/dspace/modules/rest/pom.xml @@ -12,7 +12,7 @@ org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/solr/pom.xml b/dspace/modules/solr/pom.xml index 5982cf3e2f..d84c1a4a51 100644 --- a/dspace/modules/solr/pom.xml +++ b/dspace/modules/solr/pom.xml @@ -2,7 +2,7 @@ 4.0.0 org.dspace.modules solr - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war DSpace SOLR :: Local Customizations @@ -13,7 +13,7 @@ org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/sword/pom.xml b/dspace/modules/sword/pom.xml index 99e10b7e90..3ed2e4cc10 100644 --- a/dspace/modules/sword/pom.xml +++ b/dspace/modules/sword/pom.xml @@ -16,7 +16,7 @@ org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/swordv2/pom.xml b/dspace/modules/swordv2/pom.xml index e95607a228..63ef48427d 100644 --- a/dspace/modules/swordv2/pom.xml +++ b/dspace/modules/swordv2/pom.xml @@ -16,7 +16,7 @@ org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/xmlui-mirage2/pom.xml b/dspace/modules/xmlui-mirage2/pom.xml index 1ea23b07ed..dbb3281127 100644 --- a/dspace/modules/xmlui-mirage2/pom.xml +++ b/dspace/modules/xmlui-mirage2/pom.xml @@ -12,7 +12,7 @@ org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/dspace/modules/xmlui/pom.xml b/dspace/modules/xmlui/pom.xml index 5578e417e4..c689807b6c 100644 --- a/dspace/modules/xmlui/pom.xml +++ b/dspace/modules/xmlui/pom.xml @@ -12,7 +12,7 @@ org.dspace modules - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. @@ -208,7 +208,7 @@ org.dspace.modules xmlui-mirage2 - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war diff --git a/dspace/pom.xml b/dspace/pom.xml index e29595938d..95fc78afec 100644 --- a/dspace/pom.xml +++ b/dspace/pom.xml @@ -15,7 +15,7 @@ org.dspace dspace-parent - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT .. diff --git a/pom.xml b/pom.xml index 4d5f74ddb5..42eb344b6b 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.dspace dspace-parent pom - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT DSpace Parent Project DSpace open source software is a turnkey institutional repository application. @@ -494,25 +494,6 @@ - - - doclint-java8-disable - - [1.8,) - - - - -Xdoclint:none - - - @@ -803,9 +784,6 @@ aggregate-jar - - ${javadoc.opts} - @@ -842,114 +820,114 @@ org.dspace dspace-api - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT org.dspace.modules additions - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT org.dspace dspace-sword - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT jar classes org.dspace dspace-sword - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war org.dspace dspace-swordv2 - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT jar classes org.dspace dspace-swordv2 - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war org.dspace dspace-jspui - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT jar classes org.dspace dspace-jspui - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war org.dspace dspace-oai - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT jar classes org.dspace dspace-oai - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war org.dspace dspace-xmlui - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT jar classes org.dspace dspace-xmlui - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war org.dspace dspace-services - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT org.dspace dspace-rdf - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war org.dspace dspace-rest - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT jar classes org.dspace dspace-rest - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war org.dspace dspace-solr - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT jar classes org.dspace dspace-solr - 6.0-rc5-SNAPSHOT + 7.0-SNAPSHOT war skinny