Merge remote-tracking branch 'dspace/master' into w2p-68607_add-link-to-parent-community

This commit is contained in:
Raf Ponsaerts
2020-02-25 11:19:25 +01:00
276 changed files with 6635 additions and 7725 deletions

View File

@@ -7,9 +7,9 @@ env:
- MAVEN_OPTS=-Xmx1024M - MAVEN_OPTS=-Xmx1024M
jdk: jdk:
# DS-3384 Oracle JDK 8 has DocLint enabled by default. # DS-3384 Oracle JDK has DocLint enabled by default.
# Let's use this to catch any newly introduced DocLint issues. # Let's use this to catch any newly introduced DocLint issues.
- oraclejdk8 - oraclejdk11
## Should we run into any problems with oraclejdk8 on Travis, we may try the following workaround. ## 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://docs.travis-ci.com/user/languages/java#Testing-Against-Multiple-JDKs
@@ -19,7 +19,6 @@ jdk:
# packages: # packages:
# - oracle-java8-installer # - oracle-java8-installer
# Install prerequisites for building Mirage2 more rapidly
before_install: before_install:
# Remove outdated settings.xml from Travis builds. Workaround for https://github.com/travis-ci/travis-ci/issues/4629 # Remove outdated settings.xml from Travis builds. Workaround for https://github.com/travis-ci/travis-ci/issues/4629
- rm ~/.m2/settings.xml - rm ~/.m2/settings.xml

View File

@@ -1,12 +1,11 @@
# This image will be published as dspace/dspace # This image will be published as dspace/dspace
# See https://dspace-labs.github.io/DSpace-Docker-Images/ for usage details # See https://github.com/DSpace/DSpace/tree/master/dspace/src/main/docker for usage details
# #
# This version is JDK8 compatible # This version is JDK11 compatible
# - tomcat:8-jre8 # - tomcat:8-jdk11
# - ANT 1.10.7 # - ANT 1.10.7
# - maven:3-jdk-8 # - maven:3-jdk-11 (see dspace-dependencies)
# - note: # - note: default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x
# - default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x-jdk8
# Step 1 - Run Maven Build # Step 1 - Run Maven Build
FROM dspace/dspace-dependencies:dspace-7_x as build FROM dspace/dspace-dependencies:dspace-7_x as build
@@ -30,7 +29,7 @@ RUN mvn package && \
mvn clean mvn clean
# Step 2 - Run Ant Deploy # Step 2 - Run Ant Deploy
FROM tomcat:8-jre8 as ant_build FROM tomcat:8-jdk11 as ant_build
ARG TARGET_DIR=dspace-installer ARG TARGET_DIR=dspace-installer
COPY --from=build /install /dspace-src COPY --from=build /install /dspace-src
WORKDIR /dspace-src WORKDIR /dspace-src
@@ -47,7 +46,7 @@ RUN ant init_installation update_configs update_code update_webapps
# Step 3 - Run tomcat # Step 3 - Run tomcat
# Create a new tomcat image that does not retain the the build directory contents # Create a new tomcat image that does not retain the the build directory contents
FROM tomcat:8-jre8 FROM tomcat:8-jdk11
ENV DSPACE_INSTALL=/dspace ENV DSPACE_INSTALL=/dspace
COPY --from=ant_build /dspace $DSPACE_INSTALL COPY --from=ant_build /dspace $DSPACE_INSTALL
EXPOSE 8080 8009 EXPOSE 8080 8009

View File

@@ -1,12 +1,11 @@
# This image will be published as dspace/dspace-cli # This image will be published as dspace/dspace-cli
# See https://dspace-labs.github.io/DSpace-Docker-Images/ for usage details # See https://github.com/DSpace/DSpace/tree/master/dspace/src/main/docker for usage details
# #
# This version is JDK8 compatible # This version is JDK11 compatible
# - openjdk:8-jdk # - openjdk:11
# - ANT 1.10.7 # - ANT 1.10.7
# - maven:3-jdk-8 # - maven:3-jdk-11 (see dspace-dependencies)
# - note: # - note: default tag for branch: dspace/dspace-cli: dspace/dspace-cli:dspace-7_x
# - default tag for branch: dspace/dspace-cli: dspace/dspace-cli:dspace-7_x
# Step 1 - Run Maven Build # Step 1 - Run Maven Build
FROM dspace/dspace-dependencies:dspace-7_x as build FROM dspace/dspace-dependencies:dspace-7_x as build
@@ -30,7 +29,7 @@ RUN mvn package -P'!dspace-rest' && \
mvn clean mvn clean
# Step 2 - Run Ant Deploy # Step 2 - Run Ant Deploy
FROM openjdk:8-jdk as ant_build FROM openjdk:11 as ant_build
ARG TARGET_DIR=dspace-installer ARG TARGET_DIR=dspace-installer
COPY --from=build /install /dspace-src COPY --from=build /install /dspace-src
WORKDIR /dspace-src WORKDIR /dspace-src
@@ -47,7 +46,7 @@ RUN ant init_installation update_configs update_code
# Step 3 - Run jdk # Step 3 - Run jdk
# Create a new tomcat image that does not retain the the build directory contents # Create a new tomcat image that does not retain the the build directory contents
FROM openjdk:8-jdk FROM openjdk:11
ENV DSPACE_INSTALL=/dspace ENV DSPACE_INSTALL=/dspace
COPY --from=ant_build /dspace $DSPACE_INSTALL COPY --from=ant_build /dspace $DSPACE_INSTALL

View File

@@ -1,8 +1,11 @@
# This image will be published as dspace/dspace-dependencies # This image will be published as dspace/dspace-dependencies
# The purpose of this image is to make the build for dspace/dspace run faster # The purpose of this image is to make the build for dspace/dspace run faster
#
# This version is JDK11 compatible
# - maven:3-jdk-11
# Step 1 - Run Maven Build # Step 1 - Run Maven Build
FROM maven:3-jdk-8 as build FROM maven:3-jdk-11 as build
ARG TARGET_DIR=dspace-installer ARG TARGET_DIR=dspace-installer
WORKDIR /app WORKDIR /app
@@ -16,9 +19,9 @@ ADD --chown=dspace . /app/
COPY dspace/src/main/docker/local.cfg /app/local.cfg COPY dspace/src/main/docker/local.cfg /app/local.cfg
# Trigger the installation of all maven dependencies # Trigger the installation of all maven dependencies
# Clean up the built artifacts in the same step to keep the docker image small RUN mvn package
RUN mvn package && mvn clean
# Clear the contents of the /app directory so no artifacts are left when dspace:dspace is built # Clear the contents of the /app directory (including all maven builds), so no artifacts remain.
# This ensures when dspace:dspace is built, it will just the Maven local cache (.m2) for dependencies
USER root USER root
RUN rm -rf /app/* RUN rm -rf /app/*

View File

@@ -1,12 +1,13 @@
# This image will be published as dspace/dspace # This image will be published as dspace/dspace
# See https://dspace-labs.github.io/DSpace-Docker-Images/ for usage details # See https://github.com/DSpace/DSpace/tree/master/dspace/src/main/docker for usage details
# #
# This version is JDK8 compatible # This version is JDK11 compatible
# - tomcat:8-jre8 # - tomcat:8-jdk11
# - ANT 1.10.7 # - ANT 1.10.7
# - maven:3-jdk-8 # - maven:3-jdk-11 (see dspace-dependencies)
# - note: # - note: default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x-test
# - default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x-jdk8-test #
# This image is meant for TESTING/DEVELOPMENT ONLY as it deploys the old v6 REST API under HTTP (not HTTPS)
# Step 1 - Run Maven Build # Step 1 - Run Maven Build
FROM dspace/dspace-dependencies:dspace-7_x as build FROM dspace/dspace-dependencies:dspace-7_x as build
@@ -30,7 +31,7 @@ RUN mvn package && \
mvn clean mvn clean
# Step 2 - Run Ant Deploy # Step 2 - Run Ant Deploy
FROM tomcat:8-jre8 as ant_build FROM tomcat:8-jdk11 as ant_build
ARG TARGET_DIR=dspace-installer ARG TARGET_DIR=dspace-installer
COPY --from=build /install /dspace-src COPY --from=build /install /dspace-src
WORKDIR /dspace-src WORKDIR /dspace-src
@@ -47,7 +48,7 @@ RUN ant init_installation update_configs update_code update_webapps
# Step 3 - Run tomcat # Step 3 - Run tomcat
# Create a new tomcat image that does not retain the the build directory contents # Create a new tomcat image that does not retain the the build directory contents
FROM tomcat:8-jre8 FROM tomcat:8-jdk11
ENV DSPACE_INSTALL=/dspace ENV DSPACE_INSTALL=/dspace
COPY --from=ant_build /dspace $DSPACE_INSTALL COPY --from=ant_build /dspace $DSPACE_INSTALL
EXPOSE 8080 8009 EXPOSE 8080 8009

View File

@@ -6,7 +6,7 @@ services:
container_name: dspace-cli container_name: dspace-cli
build: build:
context: . context: .
dockerfile: Dockerfile.cli.jdk8 dockerfile: Dockerfile.cli
#environment: #environment:
volumes: volumes:
- ./dspace/src/main/docker-compose/local.cfg:/dspace/config/local.cfg - ./dspace/src/main/docker-compose/local.cfg:/dspace/config/local.cfg

View File

@@ -4,10 +4,10 @@ networks:
services: services:
dspace: dspace:
container_name: dspace container_name: dspace
image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-7_x-jdk8-test}" image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-7_x-test}"
build: build:
context: . context: .
dockerfile: Dockerfile.jdk8-test dockerfile: Dockerfile.test
depends_on: depends_on:
- dspacedb - dspacedb
networks: networks:

View File

@@ -50,10 +50,33 @@
<configuration> <configuration>
<debug>true</debug> <debug>true</debug>
<showDeprecation>true</showDeprecation> <showDeprecation>true</showDeprecation>
<compilerArguments> <annotationProcessorPaths>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor> <!-- Enable Hibernate's Metamodel Generator to generate metadata model classes
</compilerArguments> (ending in _ suffix) for more type-safe Criteria queries -->
<path>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
</path>
<!-- Enable JAXB -->
<path>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
</path>
<!-- Enable Commons Annotations -->
<path>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax-annotation.version}</version>
</path>
<!-- Enable http://errorprone.info -->
<path>
<groupId>com.google.errorprone</groupId>
<artifactId>error_prone_core</artifactId>
<version>${errorprone.version}</version>
</path>
</annotationProcessorPaths>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
@@ -93,7 +116,7 @@
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version> <version>3.0.0</version>
<executions> <executions>
<execution> <execution>
<phase>validate</phase> <phase>validate</phase>
@@ -161,7 +184,6 @@
install of DSpace, against which Tests can be run. --> install of DSpace, against which Tests can be run. -->
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/testing</outputDirectory> <outputDirectory>${project.build.directory}/testing</outputDirectory>
<artifactItems> <artifactItems>
@@ -196,7 +218,7 @@
(see: http://gmaven.codehaus.org/Executing+Groovy+Code ) (see: http://gmaven.codehaus.org/Executing+Groovy+Code )
We are generating a OS-agnostic version (agnostic.build.dir) of We are generating a OS-agnostic version (agnostic.build.dir) of
the ${project.build.directory} property (full path of target dir). the ${project.build.directory} property (full path of target dir).
This is needed by the FileWeaver & Surefire plugins (see below) This is needed by the Surefire & Failsafe plugins (see below)
to initialize the Unit Test environment's dspace.cfg file. to initialize the Unit Test environment's dspace.cfg file.
Otherwise, the Unit Test Framework will not work on Windows OS. Otherwise, the Unit Test Framework will not work on Windows OS.
This Groovy code was mostly borrowed from: This Groovy code was mostly borrowed from:
@@ -205,19 +227,17 @@
<plugin> <plugin>
<groupId>org.codehaus.gmaven</groupId> <groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId> <artifactId>groovy-maven-plugin</artifactId>
<version>2.0</version>
<executions> <executions>
<execution> <execution>
<id>setproperty</id> <id>setproperty</id>
<phase>generate-test-resources <phase>initialize</phase>
</phase> <!-- XXX I think this should be 'initialize' - MHW -->
<goals> <goals>
<goal>execute</goal> <goal>execute</goal>
</goals> </goals>
<configuration> <configuration>
<source> <source>
project.properties['agnostic.build.dir'] = project.build.directory.replace(File.separator, '/'); project.properties['agnostic.build.dir'] = project.build.directory.replace(File.separator, '/');
println("Initializing Maven property 'agnostic.build.dir' to: " + project.properties['agnostic.build.dir']); log.info("Initializing Maven property 'agnostic.build.dir' to: {}", project.properties['agnostic.build.dir']);
</source> </source>
</configuration> </configuration>
</execution> </execution>
@@ -230,6 +250,7 @@
<configuration> <configuration>
<systemPropertyVariables> <systemPropertyVariables>
<!-- Specify the dspace.dir to use for test environment --> <!-- Specify the dspace.dir to use for test environment -->
<!-- ${agnostic.build.dir} is set dynamically by groovy-maven-plugin above -->
<!-- This system property is loaded by AbstractDSpaceTest to initialize the test environment --> <!-- This system property is loaded by AbstractDSpaceTest to initialize the test environment -->
<dspace.dir>${agnostic.build.dir}/testing/dspace/</dspace.dir> <dspace.dir>${agnostic.build.dir}/testing/dspace/</dspace.dir>
<!-- Turn off any DSpace logging --> <!-- Turn off any DSpace logging -->
@@ -238,51 +259,13 @@
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xml-maven-plugin</artifactId>
<version>1.0.1</version>
<executions>
<execution>
<id>validate-ALL-xml-and-xsl</id>
<phase>process-test-resources</phase>
<goals>
<goal>validate</goal>
</goals>
</execution>
</executions>
<configuration>
<validationSets>
<!-- validate ALL XML and XSL config files in the testing folder -->
<validationSet>
<dir>${agnostic.build.dir}/testing</dir>
<includes>
<include>**/*.xml</include>
<include>**/*.xsl</include>
<include>**/*.xconf</include>
</includes>
</validationSet>
<!-- validate ALL XML and XSL files throughout the project -->
<validationSet>
<dir>${root.basedir}</dir>
<includes>
<include>**/*.xml</include>
<include>**/*.xsl</include>
<include>**/*.xmap</include>
</includes>
</validationSet>
</validationSets>
</configuration>
</plugin>
<!-- Run Integration Testing! This plugin just kicks off the tests (when enabled). --> <!-- Run Integration Testing! This plugin just kicks off the tests (when enabled). -->
<plugin> <plugin>
<artifactId>maven-failsafe-plugin</artifactId> <artifactId>maven-failsafe-plugin</artifactId>
<configuration> <configuration>
<systemPropertyVariables> <systemPropertyVariables>
<!-- Specify the dspace.dir to use for test environment --> <!-- Specify the dspace.dir to use for test environment -->
<!-- ${agnostic.build.dir} is set dynamically by groovy-maven-plugin above -->
<dspace.dir>${agnostic.build.dir}/testing/dspace/</dspace.dir> <dspace.dir>${agnostic.build.dir}/testing/dspace/</dspace.dir>
<!-- Turn off any DSpace logging --> <!-- Turn off any DSpace logging -->
<dspace.log.init.disable>true</dspace.log.init.disable> <dspace.log.init.disable>true</dspace.log.init.disable>
@@ -456,11 +439,6 @@
<groupId>org.dspace</groupId> <groupId>org.dspace</groupId>
<artifactId>dspace-services</artifactId> <artifactId>dspace-services</artifactId>
</dependency> </dependency>
<dependency> <!-- Keep jmockit before junit -->
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
@@ -481,7 +459,11 @@
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.rometools</groupId> <groupId>org.rometools</groupId>
<artifactId>rome-modules</artifactId> <artifactId>rome-modules</artifactId>
@@ -609,19 +591,44 @@
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<!-- JAXB API and implementation (no longer bundled as of Java 11) -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<!-- Apache Axiom -->
<dependency> <dependency>
<groupId>org.apache.ws.commons.axiom</groupId> <groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId> <artifactId>axiom-impl</artifactId>
<!-- NOTE: SWORDv2 needs 1.2.14, required by Abdera: https://abdera.apache.org/ --> <version>${axiom.version}</version>
<version>1.2.14</version> <exclusions>
<!-- Exclude Geronimo as it is NOT necessary when using javax.activation (which we use)
See: https://ws.apache.org/axiom/userguide/ch04.html#d0e732 -->
<exclusion>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.ws.commons.axiom</groupId> <groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId> <artifactId>axiom-api</artifactId>
<!-- NOTE: SWORDv2 needs 1.2.14, required by Abdera: https://abdera.apache.org/ --> <version>${axiom.version}</version>
<version>1.2.14</version> <exclusions>
<!-- Exclude Geronimo as it is NOT necessary when using javax.activation (which we use)
See: https://ws.apache.org/axiom/userguide/ch04.html#d0e732 -->
<exclusion>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.core</groupId> <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId> <artifactId>jersey-client</artifactId>
@@ -664,7 +671,7 @@
<dependency> <dependency>
<groupId>org.xmlunit</groupId> <groupId>org.xmlunit</groupId>
<artifactId>xmlunit-matchers</artifactId> <artifactId>xmlunit-matchers</artifactId>
<version>2.6.2</version> <version>2.6.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
@@ -674,6 +681,12 @@
<version>1.0.0.Final</version> <version>1.0.0.Final</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.bcel</groupId>
<artifactId>bcel</artifactId>
<version>6.4.0</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@@ -212,6 +212,8 @@ public class StructBuilder {
} }
importStructure(context, inputStream, outputStream); importStructure(context, inputStream, outputStream);
// save changes from import
context.complete();
} }
System.exit(0); System.exit(0);
} }
@@ -304,8 +306,6 @@ public class StructBuilder {
output, e.getMessage()); output, e.getMessage());
System.exit(1); System.exit(1);
} }
context.complete();
} }
/** /**

View File

@@ -929,7 +929,7 @@ public class ItemExportServiceImpl implements ItemExportService {
Locale supportedLocale = I18nUtil.getEPersonLocale(eperson); Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success")); Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_success"));
email.addRecipient(eperson.getEmail()); email.addRecipient(eperson.getEmail());
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/exportdownload/" + fileName); email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/exportdownload/" + fileName);
email.addArgument(ConfigurationManager.getProperty("org.dspace.app.itemexport.life.span.hours")); email.addArgument(ConfigurationManager.getProperty("org.dspace.app.itemexport.life.span.hours"));
email.send(); email.send();
@@ -947,7 +947,7 @@ public class ItemExportServiceImpl implements ItemExportService {
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error")); Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "export_error"));
email.addRecipient(eperson.getEmail()); email.addRecipient(eperson.getEmail());
email.addArgument(error); email.addArgument(error);
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/feedback"); email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/feedback");
email.send(); email.send();
} catch (Exception e) { } catch (Exception e) {

View File

@@ -1797,7 +1797,7 @@ public class ItemImportServiceImpl implements ItemImportService, InitializingBea
Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "bte_batch_import_error")); Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "bte_batch_import_error"));
email.addRecipient(eperson.getEmail()); email.addRecipient(eperson.getEmail());
email.addArgument(error); email.addArgument(error);
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/feedback"); email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/feedback");
email.send(); email.send();
} catch (Exception e) { } catch (Exception e) {

View File

@@ -152,11 +152,11 @@ public class GenerateSitemaps {
*/ */
public static void generateSitemaps(boolean makeHTMLMap, public static void generateSitemaps(boolean makeHTMLMap,
boolean makeSitemapOrg) throws SQLException, IOException { boolean makeSitemapOrg) throws SQLException, IOException {
String sitemapStem = configurationService.getProperty("dspace.url") String sitemapStem = configurationService.getProperty("dspace.ui.url")
+ "/sitemap"; + "/sitemap";
String htmlMapStem = configurationService.getProperty("dspace.url") String htmlMapStem = configurationService.getProperty("dspace.ui.url")
+ "/htmlmap"; + "/htmlmap";
String handleURLStem = configurationService.getProperty("dspace.url") String handleURLStem = configurationService.getProperty("dspace.ui.url")
+ "/handle/"; + "/handle/";
File outputDir = new File(configurationService.getProperty("sitemap.dir")); File outputDir = new File(configurationService.getProperty("sitemap.dir"));
@@ -293,7 +293,7 @@ public class GenerateSitemaps {
.getProperty("http.proxy.port")); .getProperty("http.proxy.port"));
} }
String sitemapURL = configurationService.getProperty("dspace.url") String sitemapURL = configurationService.getProperty("dspace.ui.url")
+ "/sitemap"; + "/sitemap";
URL url = new URL(engineURL + URLEncoder.encode(sitemapURL, "UTF-8")); URL url = new URL(engineURL + URLEncoder.encode(sitemapURL, "UTF-8"));

View File

@@ -33,6 +33,7 @@ import org.apache.commons.lang3.StringUtils;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
import org.dspace.core.Utils;
import org.dspace.discovery.DiscoverQuery; import org.dspace.discovery.DiscoverQuery;
import org.dspace.discovery.SearchServiceException; import org.dspace.discovery.SearchServiceException;
import org.dspace.discovery.SearchUtils; import org.dspace.discovery.SearchUtils;
@@ -581,9 +582,9 @@ public class LogAnalyser {
} }
// now do the host name and url lookup // now do the host name and url lookup
hostName = ConfigurationManager.getProperty("dspace.hostname").trim(); hostName = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url"));
name = ConfigurationManager.getProperty("dspace.name").trim(); name = ConfigurationManager.getProperty("dspace.name").trim();
url = ConfigurationManager.getProperty("dspace.url").trim(); url = ConfigurationManager.getProperty("dspace.ui.url").trim();
if ((url != null) && (!url.endsWith("/"))) { if ((url != null) && (!url.endsWith("/"))) {
url = url + "/"; url = url + "/";
} }

View File

@@ -15,7 +15,7 @@ package org.dspace.app.statistics;
* *
* @author Richard Jones * @author Richard Jones
*/ */
public class Stat implements Comparable { public class Stat implements Comparable<Stat> {
// FIXME: this class is functional but a bit messy, and should be neatened // FIXME: this class is functional but a bit messy, and should be neatened
// up and completed // up and completed
@@ -132,17 +132,17 @@ public class Stat implements Comparable {
/** /**
* compare the current object to the given object returning -1 if o is less * Compare the current Stat to the given Stat returning -1 if o is less
* than the current object, 0 if they are the same, and +1 if o is greater * than the current Stat, 0 if they are the same, and +1 if o is greater
* than the current object. * than the current Stat.
* *
* @param o the object to compare to the current one * @param stat the Stat object to compare to the current one
* @return +1, 0, -1 if o is less than, equal to, or greater than the * @return +1, 0, -1 if o is less than, equal to, or greater than the
* current object value. * current object value.
*/ */
@Override @Override
public int compareTo(Object o) { public int compareTo(Stat stat) {
int objectValue = ((Stat) o).getValue(); int objectValue = stat.getValue();
if (objectValue < this.getValue()) { if (objectValue < this.getValue()) {
return -1; return -1;

View File

@@ -50,16 +50,16 @@ abstract public class AbstractDSpaceWebapp
/** /**
* Construct a particular kind of DSpace application. * Construct a particular kind of DSpace application.
* *
* @param kind what kind of application is this? (XMLUI, JSPUI, etc.) * @param kind what kind of application is this?
*/ */
public AbstractDSpaceWebapp(String kind) { public AbstractDSpaceWebapp(String kind) {
this.kind = kind; this.kind = kind;
started = new Date(); started = new Date();
url = ConfigurationManager.getProperty("dspace.url"); url = ConfigurationManager.getProperty("dspace.ui.url");
if (null == url) { if (null == url) {
throw new IllegalStateException("dspace.url is undefined"); throw new IllegalStateException("dspace.ui.url is undefined");
} }
} }

View File

@@ -34,12 +34,6 @@ import org.dspace.core.Context;
*/ */
public class AuthorizeUtil { public class AuthorizeUtil {
private static final AuthorizeService authorizeService =
AuthorizeServiceFactory.getInstance().getAuthorizeService();
private static final ItemService itemService = ContentServiceFactory.getInstance().getItemService();
private static final CollectionService collectionService =
ContentServiceFactory.getInstance().getCollectionService();
/** /**
* Default constructor * Default constructor
*/ */
@@ -95,8 +89,9 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageItemPolicy(Context context, Item item) public static void authorizeManageItemPolicy(Context context, Item item)
throws AuthorizeException, SQLException { throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canItemAdminManagePolicies()) { if (AuthorizeConfiguration.canItemAdminManagePolicies()) {
authorizeService.authorizeAction(context, item, Constants.ADMIN); AuthorizeServiceFactory.getInstance().getAuthorizeService().authorizeAction(context, item, Constants.ADMIN);
} else if (AuthorizeConfiguration.canCollectionAdminManageItemPolicies()) { } else if (AuthorizeConfiguration.canCollectionAdminManageItemPolicies()) {
authorizeService.authorizeAction(context, item authorizeService.authorizeAction(context, item
.getOwningCollection(), Constants.ADMIN); .getOwningCollection(), Constants.ADMIN);
@@ -124,6 +119,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageCollectionPolicy(Context context, public static void authorizeManageCollectionPolicy(Context context,
Collection collection) throws AuthorizeException, SQLException { Collection collection) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canCollectionAdminManagePolicies()) { if (AuthorizeConfiguration.canCollectionAdminManagePolicies()) {
authorizeService.authorizeAction(context, collection, authorizeService.authorizeAction(context, collection,
Constants.ADMIN); Constants.ADMIN);
@@ -151,6 +147,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageCommunityPolicy(Context context, public static void authorizeManageCommunityPolicy(Context context,
Community community) throws AuthorizeException, SQLException { Community community) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canCommunityAdminManagePolicies()) { if (AuthorizeConfiguration.canCommunityAdminManagePolicies()) {
authorizeService.authorizeAction(context, community, authorizeService.authorizeAction(context, community,
Constants.ADMIN); Constants.ADMIN);
@@ -171,6 +168,7 @@ public class AuthorizeUtil {
*/ */
public static void requireAdminRole(Context context) public static void requireAdminRole(Context context)
throws AuthorizeException, SQLException { throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (!authorizeService.isAdmin(context)) { if (!authorizeService.isAdmin(context)) {
throw new AuthorizeException( throw new AuthorizeException(
"Only system admin are allowed to perform this action"); "Only system admin are allowed to perform this action");
@@ -191,6 +189,8 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageCCLicense(Context context, Item item) public static void authorizeManageCCLicense(Context context, Item item)
throws AuthorizeException, SQLException { throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
ItemService itemService = ContentServiceFactory.getInstance().getItemService();
try { try {
authorizeService.authorizeAction(context, item, Constants.ADD); authorizeService.authorizeAction(context, item, Constants.ADD);
authorizeService.authorizeAction(context, item, Constants.REMOVE); authorizeService.authorizeAction(context, item, Constants.REMOVE);
@@ -224,6 +224,8 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageTemplateItem(Context context, public static void authorizeManageTemplateItem(Context context,
Collection collection) throws AuthorizeException, SQLException { Collection collection) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
boolean isAuthorized = collectionService.canEditBoolean(context, collection, false); boolean isAuthorized = collectionService.canEditBoolean(context, collection, false);
if (!isAuthorized if (!isAuthorized
@@ -258,6 +260,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageSubmittersGroup(Context context, public static void authorizeManageSubmittersGroup(Context context,
Collection collection) throws AuthorizeException, SQLException { Collection collection) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canCollectionAdminManageSubmitters()) { if (AuthorizeConfiguration.canCollectionAdminManageSubmitters()) {
authorizeService.authorizeAction(context, collection, authorizeService.authorizeAction(context, collection,
Constants.ADMIN); Constants.ADMIN);
@@ -285,6 +288,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageWorkflowsGroup(Context context, public static void authorizeManageWorkflowsGroup(Context context,
Collection collection) throws AuthorizeException, SQLException { Collection collection) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canCollectionAdminManageWorkflows()) { if (AuthorizeConfiguration.canCollectionAdminManageWorkflows()) {
authorizeService.authorizeAction(context, collection, authorizeService.authorizeAction(context, collection,
Constants.ADMIN); Constants.ADMIN);
@@ -313,6 +317,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageAdminGroup(Context context, public static void authorizeManageAdminGroup(Context context,
Collection collection) throws AuthorizeException, SQLException { Collection collection) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canCollectionAdminManageAdminGroup()) { if (AuthorizeConfiguration.canCollectionAdminManageAdminGroup()) {
authorizeService.authorizeAction(context, collection, authorizeService.authorizeAction(context, collection,
Constants.ADMIN); Constants.ADMIN);
@@ -341,6 +346,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeRemoveAdminGroup(Context context, public static void authorizeRemoveAdminGroup(Context context,
Collection collection) throws AuthorizeException, SQLException { Collection collection) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
List<Community> parentCommunities = collection.getCommunities(); List<Community> parentCommunities = collection.getCommunities();
if (AuthorizeConfiguration if (AuthorizeConfiguration
.canCommunityAdminManageCollectionAdminGroup() .canCommunityAdminManageCollectionAdminGroup()
@@ -368,6 +374,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeManageAdminGroup(Context context, public static void authorizeManageAdminGroup(Context context,
Community community) throws AuthorizeException, SQLException { Community community) throws AuthorizeException, SQLException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canCommunityAdminManageAdminGroup()) { if (AuthorizeConfiguration.canCommunityAdminManageAdminGroup()) {
authorizeService.authorizeAction(context, community, authorizeService.authorizeAction(context, community,
Constants.ADMIN); Constants.ADMIN);
@@ -392,6 +399,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeRemoveAdminGroup(Context context, public static void authorizeRemoveAdminGroup(Context context,
Community community) throws SQLException, AuthorizeException { Community community) throws SQLException, AuthorizeException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
List<Community> parentCommunities = community.getParentCommunities(); List<Community> parentCommunities = community.getParentCommunities();
Community parentCommunity = null; Community parentCommunity = null;
if (0 < parentCommunities.size()) { if (0 < parentCommunities.size()) {
@@ -458,6 +466,7 @@ public class AuthorizeUtil {
public static void authorizeWithdrawItem(Context context, Item item) public static void authorizeWithdrawItem(Context context, Item item)
throws SQLException, AuthorizeException { throws SQLException, AuthorizeException {
boolean authorized = false; boolean authorized = false;
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
if (AuthorizeConfiguration.canCollectionAdminPerformItemWithdrawn()) { if (AuthorizeConfiguration.canCollectionAdminPerformItemWithdrawn()) {
authorized = authorizeService.authorizeActionBoolean(context, item authorized = authorizeService.authorizeActionBoolean(context, item
.getOwningCollection(), Constants.ADMIN); .getOwningCollection(), Constants.ADMIN);
@@ -492,6 +501,7 @@ public class AuthorizeUtil {
*/ */
public static void authorizeReinstateItem(Context context, Item item) public static void authorizeReinstateItem(Context context, Item item)
throws SQLException, AuthorizeException { throws SQLException, AuthorizeException {
AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
List<Collection> colls = item.getCollections(); List<Collection> colls = item.getCollections();
for (Collection coll : colls) { for (Collection coll : colls) {

View File

@@ -889,7 +889,7 @@ public class GoogleMetadata {
Bitstream bitstream = findLinkableFulltext(item); Bitstream bitstream = findLinkableFulltext(item);
if (bitstream != null) { if (bitstream != null) {
StringBuilder path = new StringBuilder(); StringBuilder path = new StringBuilder();
path.append(ConfigurationManager.getProperty("dspace.url")); path.append(ConfigurationManager.getProperty("dspace.ui.url"));
if (item.getHandle() != null) { if (item.getHandle() != null) {
path.append("/bitstream/"); path.append("/bitstream/");

View File

@@ -89,7 +89,7 @@ public class OpenSearchServiceImpl implements OpenSearchService {
* Get base search service URL (websvc.opensearch.svccontext) * Get base search service URL (websvc.opensearch.svccontext)
*/ */
protected String getBaseSearchServiceURL() { protected String getBaseSearchServiceURL() {
return configurationService.getProperty("dspace.url") + "/" + return configurationService.getProperty("dspace.server.url") + "/" +
configurationService.getProperty("websvc.opensearch.svccontext"); configurationService.getProperty("websvc.opensearch.svccontext");
} }
@@ -97,7 +97,7 @@ public class OpenSearchServiceImpl implements OpenSearchService {
* Get base search UI URL (websvc.opensearch.uicontext) * Get base search UI URL (websvc.opensearch.uicontext)
*/ */
protected String getBaseSearchUIURL() { protected String getBaseSearchUIURL() {
return configurationService.getProperty("dspace.url") + "/" + return configurationService.getProperty("dspace.server.url") + "/" +
configurationService.getProperty("websvc.opensearch.uicontext"); configurationService.getProperty("websvc.opensearch.uicontext");
} }

View File

@@ -531,11 +531,9 @@ public class SyndicationFeed {
if (dso == null) { if (dso == null) {
if (baseURL == null) { if (baseURL == null) {
if (request == null) { if (request == null) {
baseURL = ConfigurationManager.getProperty("dspace.url"); baseURL = ConfigurationManager.getProperty("dspace.ui.url");
} else { } else {
baseURL = (request.isSecure()) ? "https://" : "http://"; baseURL = ConfigurationManager.getProperty("dspace.ui.url");
baseURL += ConfigurationManager.getProperty("dspace.hostname");
baseURL += ":" + request.getServerPort();
baseURL += request.getContextPath(); baseURL += request.getContextPath();
} }
} }

View File

@@ -360,9 +360,13 @@ public class Util {
InputStream cis = null; InputStream cis = null;
try { try {
cis = Util.class.getResourceAsStream("/META-INF/maven/org.dspace/dspace-api/pom.properties"); cis = Util.class.getResourceAsStream("/META-INF/maven/org.dspace/dspace-api/pom.properties");
if (cis == null) {
// pom.properties will not exist when running tests
return "unknown";
}
constants.load(cis); constants.load(cis);
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); log.error("Could not open dspace-api's pom.properties", e);
} finally { } finally {
if (cis != null) { if (cis != null) {
try { try {

View File

@@ -11,8 +11,8 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
@@ -140,8 +140,8 @@ public class PersonAuthorityValue extends AuthorityValue {
@Override @Override
public void setValues(SolrDocument document) { public void setValues(SolrDocument document) {
super.setValues(document); super.setValues(document);
this.firstName = ObjectUtils.toString(document.getFieldValue("first_name")); this.firstName = Objects.toString(document.getFieldValue("first_name"), "");
this.lastName = ObjectUtils.toString(document.getFieldValue("last_name")); this.lastName = Objects.toString(document.getFieldValue("last_name"), "");
nameVariants = new ArrayList<String>(); nameVariants = new ArrayList<String>();
Collection<Object> document_name_variant = document.getFieldValues("name_variant"); Collection<Object> document_name_variant = document.getFieldValues("name_variant");
if (document_name_variant != null) { if (document_name_variant != null) {

View File

@@ -8,6 +8,7 @@
package org.dspace.authorize; package org.dspace.authorize;
import java.util.Date; import java.util.Date;
import java.util.Objects;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@@ -23,7 +24,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import org.apache.commons.lang3.ObjectUtils;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.ReloadableEntity; import org.dspace.core.ReloadableEntity;
@@ -123,16 +123,16 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
if (getAction() != other.getAction()) { if (getAction() != other.getAction()) {
return false; return false;
} }
if (!ObjectUtils.equals(getEPerson(), other.getEPerson())) { if (!Objects.equals(getEPerson(), other.getEPerson())) {
return false; return false;
} }
if (!ObjectUtils.equals(getGroup(), other.getGroup())) { if (!Objects.equals(getGroup(), other.getGroup())) {
return false; return false;
} }
if (!ObjectUtils.equals(getStartDate(), other.getStartDate())) { if (!Objects.equals(getStartDate(), other.getStartDate())) {
return false; return false;
} }
if (!ObjectUtils.equals(getEndDate(), other.getEndDate())) { if (!Objects.equals(getEndDate(), other.getEndDate())) {
return false; return false;
} }
return true; return true;
@@ -185,7 +185,7 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
/** /**
* set the action this policy authorizes * set the action this policy authorizes
* *
* @param myid action ID from {@link org.dspace.core.Constants#Constants Constants} * @param myid action ID from {@link org.dspace.core.Constants Constants}
*/ */
public void setAction(int myid) { public void setAction(int myid) {
this.actionId = myid; this.actionId = myid;

View File

@@ -27,6 +27,7 @@ import org.dspace.checker.service.SimpleReporterService;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Email; import org.dspace.core.Email;
import org.dspace.core.Utils;
/** /**
* <p> * <p>
@@ -62,7 +63,7 @@ public class DailyReportEmailer {
public void sendReport(File attachment, int numberOfBitstreams) public void sendReport(File attachment, int numberOfBitstreams)
throws IOException, javax.mail.MessagingException { throws IOException, javax.mail.MessagingException {
if (numberOfBitstreams > 0) { if (numberOfBitstreams > 0) {
String hostname = ConfigurationManager.getProperty("dspace.hostname"); String hostname = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url"));
Email email = new Email(); Email email = new Email();
email.setSubject( email.setSubject(
"Checksum checker Report - " + numberOfBitstreams + " Bitstreams found with POSSIBLE issues on " + "Checksum checker Report - " + numberOfBitstreams + " Bitstreams found with POSSIBLE issues on " +

View File

@@ -694,9 +694,11 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
List<MetadataValue> list = getMetadata(dso, schema, element, qualifier); List<MetadataValue> list = getMetadata(dso, schema, element, qualifier);
if (from >= list.size()) { if (from >= list.size() || to >= list.size() || to < 0 || from < 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"The \"from\" location MUST exist for the operation to be successful. Idx:" + from); "The \"from\" and \"to\" locations MUST exist for the operation to be successful." +
"\n To and from indices must be between 0 and " + (list.size() - 1) +
"\n Idx from:" + from + " Idx to: " + to);
} }
clearMetadata(context, dso, schema, element, qualifier, Item.ANY); clearMetadata(context, dso, schema, element, qualifier, Item.ANY);
@@ -757,4 +759,9 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
} }
} }
@Override
public void setMetadataModified(T dso) {
dso.setMetadataModified();
}
} }

View File

@@ -12,11 +12,13 @@ import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService; import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.dao.MetadataFieldDAO; import org.dspace.content.dao.MetadataFieldDAO;
import org.dspace.content.service.MetadataFieldService; import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService;
import org.dspace.content.service.MetadataValueService; import org.dspace.content.service.MetadataValueService;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.LogManager; import org.dspace.core.LogManager;
@@ -42,6 +44,8 @@ public class MetadataFieldServiceImpl implements MetadataFieldService {
protected AuthorizeService authorizeService; protected AuthorizeService authorizeService;
@Autowired(required = true) @Autowired(required = true)
protected MetadataValueService metadataValueService; protected MetadataValueService metadataValueService;
@Autowired(required = true)
protected MetadataSchemaService metadataSchemaService;
protected MetadataFieldServiceImpl() { protected MetadataFieldServiceImpl() {
@@ -87,13 +91,25 @@ public class MetadataFieldServiceImpl implements MetadataFieldService {
return metadataFieldDAO.findByElement(context, metadataSchema, element, qualifier); return metadataFieldDAO.findByElement(context, metadataSchema, element, qualifier);
} }
@Override @Override
public MetadataField findByElement(Context context, String metadataSchemaName, String element, String qualifier) public MetadataField findByElement(Context context, String metadataSchemaName, String element, String qualifier)
throws SQLException { throws SQLException {
return metadataFieldDAO.findByElement(context, metadataSchemaName, element, qualifier); return metadataFieldDAO.findByElement(context, metadataSchemaName, element, qualifier);
} }
@Override
public MetadataField findByString(Context context, String mdString, char separator) throws SQLException {
String[] seq = StringUtils.split(mdString, separator);
String schema = seq.length > 1 ? seq[0] : null;
String element = seq.length > 1 ? seq[1] : null;
String qualifier = seq.length == 3 ? seq[2] : null;
if (schema == null || element == null) {
return null;
} else {
return this.findByElement(context, schema, element, qualifier);
}
}
@Override @Override
public List<MetadataField> findFieldsByElementNameUnqualified(Context context, String metadataSchemaName, public List<MetadataField> findFieldsByElementNameUnqualified(Context context, String metadataSchemaName,
String element) throws SQLException { String element) throws SQLException {

View File

@@ -56,7 +56,7 @@ public class Site extends DSpaceObject {
} }
public String getURL() { public String getURL() {
return ConfigurationManager.getProperty("dspace.url"); return ConfigurationManager.getProperty("dspace.ui.url");
} }
private SiteService getSiteService() { private SiteService getSiteService() {

View File

@@ -92,7 +92,7 @@ public class OREDisseminationCrosswalk
private Element disseminateItem(Context context, Item item) private Element disseminateItem(Context context, Item item)
throws CrosswalkException, IOException, SQLException, AuthorizeException { throws CrosswalkException, IOException, SQLException, AuthorizeException {
String oaiUrl = null; String oaiUrl = null;
String dsUrl = configurationService.getProperty("dspace.url"); String dsUrl = configurationService.getProperty("dspace.ui.url");
String remSource = configurationService.getProperty("oai.ore.authoritative.source"); String remSource = configurationService.getProperty("oai.ore.authoritative.source");
if (remSource == null || remSource.equalsIgnoreCase("oai")) { if (remSource == null || remSource.equalsIgnoreCase("oai")) {
@@ -265,7 +265,8 @@ public class OREDisseminationCrosswalk
Element pmhMeta = new Element("entry",ATOM_NS); Element pmhMeta = new Element("entry",ATOM_NS);
pUri = new Element("id",ATOM_NS); pUri = new Element("id",ATOM_NS);
String oaiId = new String("oai:" + ConfigurationManager.getProperty("dspace.hostname") + ":" + item.getHandle String hostname = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url"));
String oaiId = new String("oai:" + hostname + ":" + item.getHandle
()); ());
pUri.addContent(oaiId + "#oai_dc"); pUri.addContent(oaiId + "#oai_dc");
pmhMeta.addContent(pUri); pmhMeta.addContent(pUri);

View File

@@ -219,7 +219,7 @@ public class PREMISCrosswalk
// b. name of bitstream, if any // b. name of bitstream, if any
// c. made-up name based on sequence ID and extension. // c. made-up name based on sequence ID and extension.
String sid = String.valueOf(bitstream.getSequenceID()); String sid = String.valueOf(bitstream.getSequenceID());
String baseUrl = ConfigurationManager.getProperty("dspace.url"); String baseUrl = ConfigurationManager.getProperty("dspace.ui.url");
String handle = null; String handle = null;
// get handle of parent Item of this bitstream, if there is one: // get handle of parent Item of this bitstream, if there is one:
List<Bundle> bn = bitstream.getBundles(); List<Bundle> bn = bitstream.getBundles();

View File

@@ -1400,7 +1400,7 @@ public abstract class AbstractMETSDisseminator
} }
if (handle != null) { if (handle != null) {
return configurationService return configurationService
.getProperty("dspace.url") .getProperty("dspace.ui.url")
+ "/bitstream/" + "/bitstream/"
+ handle + handle
+ "/" + "/"
@@ -1410,7 +1410,7 @@ public abstract class AbstractMETSDisseminator
} else { //no Handle assigned, so persistent(-ish) URI for bitstream is } else { //no Handle assigned, so persistent(-ish) URI for bitstream is
// Format: {site-base-url}/retrieve/{bitstream-internal-id} // Format: {site-base-url}/retrieve/{bitstream-internal-id}
return configurationService return configurationService
.getProperty("dspace.url") .getProperty("dspace.ui.url")
+ "/retrieve/" + "/retrieve/"
+ String.valueOf(bitstream.getID()); + String.valueOf(bitstream.getID());
} }

View File

@@ -182,7 +182,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/** /**
* Add metadata fields. These are appended to existing values. * Add metadata fields. These are appended to existing values.
* Use <code>clearDC</code> to remove values. The ordering of values * Use <code>clearMetadata</code> to remove values. The ordering of values
* passed in is maintained. * passed in is maintained.
* <p> * <p>
* If metadata authority control is available, try to get authority * If metadata authority control is available, try to get authority
@@ -207,7 +207,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/** /**
* Add metadata fields. These are appended to existing values. * Add metadata fields. These are appended to existing values.
* Use <code>clearDC</code> to remove values. The ordering of values * Use <code>clearMetadata</code> to remove values. The ordering of values
* passed in is maintained. * passed in is maintained.
* *
* @param context DSpace context * @param context DSpace context
@@ -231,7 +231,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/** /**
* Add metadata fields. These are appended to existing values. * Add metadata fields. These are appended to existing values.
* Use <code>clearDC</code> to remove values. The ordering of values * Use <code>clearMetadata</code> to remove values. The ordering of values
* passed in is maintained. * passed in is maintained.
* *
* @param context DSpace context * @param context DSpace context
@@ -272,7 +272,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/** /**
* Add a single metadata field. This is appended to existing * Add a single metadata field. This is appended to existing
* values. Use <code>clearDC</code> to remove values. * values. Use <code>clearMetadata</code> to remove values.
* *
* @param context DSpace context * @param context DSpace context
* @param dso DSpaceObject * @param dso DSpaceObject
@@ -292,7 +292,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/** /**
* Add a single metadata field. This is appended to existing * Add a single metadata field. This is appended to existing
* values. Use <code>clearDC</code> to remove values. * values. Use <code>clearMetadata</code> to remove values.
* *
* @param context DSpace context * @param context DSpace context
* @param dso DSpaceObject * @param dso DSpaceObject
@@ -314,10 +314,10 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/** /**
* Clear metadata values. As with <code>getDC</code> above, * Clear metadata values. As with <code>getDC</code> above,
* passing in <code>null</code> only matches fields where the qualifier or * passing in <code>null</code> only matches fields where the qualifier orr
* language is actually <code>null</code>.<code>Item.ANY</code> will * language is actually <code>null</code>.<code>Item.ANY</code> will
* match any element, qualifier or language, including <code>null</code>. * match any element, qualifier or language, including <code>null</code>.
* Thus, <code>dspaceobject.clearDC(Item.ANY, Item.ANY, Item.ANY)</code> will * Thus, <code>dspaceobject.clearMetadata(Item.ANY, Item.ANY, Item.ANY)</code> will
* remove all Dublin Core metadata associated with an DSpaceObject. * remove all Dublin Core metadata associated with an DSpaceObject.
* *
* @param context DSpace context * @param context DSpace context
@@ -370,6 +370,26 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
public void delete(Context context, T dso) throws SQLException, AuthorizeException, IOException; public void delete(Context context, T dso) throws SQLException, AuthorizeException, IOException;
/**
* Add a single metadata field. Whether it's appended or prepended depends on index parameter.
* Use <code>clearMetadata</code> to remove values.
*
* @param context DSpace context
* @param dso DSpaceObject
* @param schema the schema for the metadata field. <em>Must</em> match
* the <code>name</code> of an existing metadata schema.
* @param element the metadata element name
* @param qualifier the metadata qualifier, or <code>null</code> for
* unqualified
* @param lang the ISO639 language code, optionally followed by an underscore
* and the ISO3166 country code. <code>null</code> means the
* value has no language (for example, a date).
* @param value the value to add.
* @param authority the external authority key for this value (or null)
* @param confidence the authority confidence (default 0)
* @param index the index at which this metadata is added (0: first place, -1 for last)
* @throws SQLException if database error
*/
void addAndShiftRightMetadata(Context context, T dso, String schema, String element, String qualifier, String lang, void addAndShiftRightMetadata(Context context, T dso, String schema, String element, String qualifier, String lang,
String value, String authority, int confidence, int index) throws SQLException; String value, String authority, int confidence, int index) throws SQLException;
@@ -385,4 +405,10 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
* @return a org.dspace.core.Constants that represents a IndexableObject type * @return a org.dspace.core.Constants that represents a IndexableObject type
*/ */
public int getSupportsTypeConstant(); public int getSupportsTypeConstant();
/**
* Trigger the modifiedMetadata variable in DSpaceObject
* @param dso DSpaceObject whose metadata has been modified
*/
public void setMetadataModified(T dso);
} }

View File

@@ -71,6 +71,16 @@ public interface MetadataFieldService {
public MetadataField findByElement(Context context, String metadataSchemaName, String element, String qualifier) public MetadataField findByElement(Context context, String metadataSchemaName, String element, String qualifier)
throws SQLException; throws SQLException;
/**
* Separates an mdString in schema, element and qualifier parts, separated by a given separator
* And returns it's matching metadataField if found
* @param context dspace context
* @param mdString String being separated to find corresponding mdField (ex dc.contributor)
* @param separator Separator being used to separate the mdString
* @return Corresponding MetadataField if found
*/
public MetadataField findByString(Context context, String mdString, char separator) throws SQLException;
public List<MetadataField> findFieldsByElementNameUnqualified(Context context, String metadataSchema, public List<MetadataField> findFieldsByElementNameUnqualified(Context context, String metadataSchema,
String element) String element)
throws SQLException; throws SQLException;

View File

@@ -361,20 +361,18 @@ public class Context implements AutoCloseable {
// If Context is no longer open/valid, just note that it has already been closed // If Context is no longer open/valid, just note that it has already been closed
if (!isValid()) { if (!isValid()) {
log.info("complete() was called on a closed Context object. No changes to commit."); log.info("complete() was called on a closed Context object. No changes to commit.");
return;
} }
try { try {
// As long as we have a valid, writeable database connection, // As long as we have a valid, writeable database connection,
// rollback any changes if we are in read-only mode, // commit changes. Otherwise, we'll just close the DB connection (see below)
// otherwise, commit any changes made as part of the transaction if (!isReadOnly()) {
if (isReadOnly()) {
abort();
} else {
commit(); commit();
} }
} finally { } finally {
if (dbConnection != null) { if (dbConnection != null) {
// Free the DB connection // Free the DB connection and invalidate the Context
dbConnection.closeDBConnection(); dbConnection.closeDBConnection();
dbConnection = null; dbConnection = null;
} }
@@ -395,29 +393,24 @@ public class Context implements AutoCloseable {
// If Context is no longer open/valid, just note that it has already been closed // If Context is no longer open/valid, just note that it has already been closed
if (!isValid()) { if (!isValid()) {
log.info("commit() was called on a closed Context object. No changes to commit."); log.info("commit() was called on a closed Context object. No changes to commit.");
return;
} }
if (isReadOnly()) { if (isReadOnly()) {
throw new UnsupportedOperationException("You cannot commit a read-only context"); throw new UnsupportedOperationException("You cannot commit a read-only context");
} }
// Our DB Connection (Hibernate) will decide if an actual commit is required or not
try { try {
// As long as we have a valid, writeable database connection,
// commit any changes made as part of the transaction
if (isValid()) {
// Dispatch events before committing changes to the database, // Dispatch events before committing changes to the database,
// as the consumers may change something too // as the consumers may change something too
dispatchEvents(); dispatchEvents();
}
} finally { } finally {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Cache size on commit is " + getCacheSize()); log.debug("Cache size on commit is " + getCacheSize());
} }
if (dbConnection != null) { if (dbConnection != null) {
//Commit our changes // Commit our changes (this closes the transaction but leaves database connection open)
dbConnection.commit(); dbConnection.commit();
reloadContextBoundEntities(); reloadContextBoundEntities();
} }
@@ -425,8 +418,12 @@ public class Context implements AutoCloseable {
} }
/**
* Dispatch any events (cached in current Context) to configured EventListeners (consumers)
* in the EventService. This should be called prior to any commit as some consumers may add
* to the current transaction. Once events are dispatched, the Context's event cache is cleared.
*/
public void dispatchEvents() { public void dispatchEvents() {
// Commit any changes made as part of the transaction
Dispatcher dispatcher = null; Dispatcher dispatcher = null;
try { try {
@@ -462,6 +459,7 @@ public class Context implements AutoCloseable {
/** /**
* Add an event to be dispatched when this context is committed. * Add an event to be dispatched when this context is committed.
* NOTE: Read-only Contexts cannot add events, as they cannot modify objects.
* *
* @param event event to be dispatched * @param event event to be dispatched
*/ */
@@ -490,6 +488,10 @@ public class Context implements AutoCloseable {
return events; return events;
} }
/**
* Whether or not the context has events cached.
* @return true or false
*/
public boolean hasEvents() { public boolean hasEvents() {
return !CollectionUtils.isEmpty(events); return !CollectionUtils.isEmpty(events);
} }
@@ -521,22 +523,25 @@ public class Context implements AutoCloseable {
// If Context is no longer open/valid, just note that it has already been closed // If Context is no longer open/valid, just note that it has already been closed
if (!isValid()) { if (!isValid()) {
log.info("abort() was called on a closed Context object. No changes to abort."); log.info("abort() was called on a closed Context object. No changes to abort.");
return;
} }
try { try {
// Rollback ONLY if we have a database connection, and it is NOT Read Only // Rollback ONLY if we have a database transaction, and it is NOT Read Only
if (isValid() && !isReadOnly()) { if (!isReadOnly() && isTransactionAlive()) {
dbConnection.rollback(); dbConnection.rollback();
} }
} catch (SQLException se) { } catch (SQLException se) {
log.error(se.getMessage(), se); log.error("Error rolling back transaction during an abort()", se);
} finally { } finally {
try { try {
if (!dbConnection.isSessionAlive()) { if (dbConnection != null) {
// Free the DB connection & invalidate the Context
dbConnection.closeDBConnection(); dbConnection.closeDBConnection();
dbConnection = null;
} }
} catch (Exception ex) { } catch (Exception ex) {
log.error("Exception aborting context", ex); log.error("Error closing the database connection", ex);
} }
events = null; events = null;
} }
@@ -558,7 +563,22 @@ public class Context implements AutoCloseable {
*/ */
public boolean isValid() { public boolean isValid() {
// Only return true if our DB connection is live // Only return true if our DB connection is live
return dbConnection != null && dbConnection.isTransActionAlive(); // NOTE: A transaction need not exist for our Context to be valid, as a Context may use multiple transactions.
return dbConnection != null && dbConnection.isSessionAlive();
}
/**
* Find out whether our context includes an open database transaction.
* Returns <code>true</code> if there is an open transaction. Returns
* <code>false</code> if the context is invalid (e.g. abort() or complete())
* was called OR no current transaction exists (e.g. commit() was just called
* and no new transaction has begun)
*
* @return
*/
protected boolean isTransactionAlive() {
// Only return true if both Context is valid *and* transaction is alive
return isValid() && dbConnection.isTransActionAlive();
} }
/** /**
@@ -571,21 +591,22 @@ public class Context implements AutoCloseable {
return mode != null && mode == Mode.READ_ONLY; return mode != null && mode == Mode.READ_ONLY;
} }
/**
* Add a group's UUID to the list of special groups cached in Context
* @param groupID UUID of group
*/
public void setSpecialGroup(UUID groupID) { public void setSpecialGroup(UUID groupID) {
specialGroups.add(groupID); specialGroups.add(groupID);
// System.out.println("Added " + groupID);
} }
/** /**
* test if member of special group * Test if a group is a special group
* *
* @param groupID ID of special group to test * @param groupID ID of special group to test
* @return true if member * @return true if member
*/ */
public boolean inSpecialGroup(UUID groupID) { public boolean inSpecialGroup(UUID groupID) {
if (specialGroups.contains(groupID)) { if (specialGroups.contains(groupID)) {
// System.out.println("Contains " + groupID);
return true; return true;
} }
@@ -593,10 +614,9 @@ public class Context implements AutoCloseable {
} }
/** /**
* Get an array of all of the special groups that current user is a member * Get an array of all of the special groups that current user is a member of.
* of.
* *
* @return list of groups * @return list of special groups
* @throws SQLException if database error * @throws SQLException if database error
*/ */
public List<Group> getSpecialGroups() throws SQLException { public List<Group> getSpecialGroups() throws SQLException {
@@ -608,6 +628,10 @@ public class Context implements AutoCloseable {
return myGroups; return myGroups;
} }
/**
* Close the context, aborting any open transactions (if any).
* @throws Throwable
*/
@Override @Override
protected void finalize() throws Throwable { protected void finalize() throws Throwable {
/* /*

View File

@@ -497,7 +497,7 @@ public class Email {
String to = config.getProperty("mail.admin"); String to = config.getProperty("mail.admin");
String subject = "DSpace test email"; String subject = "DSpace test email";
String server = config.getProperty("mail.server"); String server = config.getProperty("mail.server");
String url = config.getProperty("dspace.url"); String url = config.getProperty("dspace.ui.url");
Email message; Email message;
try { try {
if (args.length <= 0) { if (args.length <= 0) {

View File

@@ -35,6 +35,23 @@ import org.springframework.orm.hibernate5.SessionFactoryUtils;
/** /**
* Hibernate implementation of the DBConnection. * Hibernate implementation of the DBConnection.
* <P>
* NOTE: This class does NOT represent a single Hibernate database connection. Instead, it wraps
* Hibernate's Session object to obtain access to a database connection in order to execute one or more
* transactions.
* <P>
* Per DSpace's current Hibernate configuration ([dspace]/config/core-hibernate.xml), we use the one-session-per-thread
* approach (ThreadLocalSessionContext). This means that Hibernate creates a single Session per thread (request), at the
* time when getCurrentSession() is first called.
* <P>
* This Session may be reused for multiple Transactions, but if commit() is called, any objects (Entities) in
* the Session become disconnected and MUST be reloaded into the Session (see reloadEntity() method below).
* <P>
* If an Error occurs, the Session itself is invalidated. No further Transactions can be run on that Session.
* <P>
* DSpace generally follows the "Session-per-request" transactional pattern described here:
* https://docs.jboss.org/hibernate/orm/5.0/userguide/en-US/html/ch06.html#session-per-request
*
* *
* @author kevinvandevelde at atmire.com * @author kevinvandevelde at atmire.com
*/ */
@@ -47,32 +64,61 @@ public class HibernateDBConnection implements DBConnection<Session> {
private boolean batchModeEnabled = false; private boolean batchModeEnabled = false;
private boolean readOnlyEnabled = false; private boolean readOnlyEnabled = false;
/**
* Retrieves the current Session from Hibernate (per our settings, Hibernate is configured to create one Session
* per thread). If Session doesn't yet exist, it is created. A Transaction is also initialized (or reinintialized)
* in the Session if one doesn't exist, or was previously closed (e.g. if commit() was previously called)
* @return Hibernate current Session object
* @throws SQLException
*/
@Override @Override
public Session getSession() throws SQLException { public Session getSession() throws SQLException {
// If we don't yet have a live transaction, start a new one
// NOTE: a Session cannot be used until a Transaction is started.
if (!isTransActionAlive()) { if (!isTransActionAlive()) {
sessionFactory.getCurrentSession().beginTransaction(); sessionFactory.getCurrentSession().beginTransaction();
configureDatabaseMode(); configureDatabaseMode();
} }
// Return the current Hibernate Session object (Hibernate will create one if it doesn't yet exist)
return sessionFactory.getCurrentSession(); return sessionFactory.getCurrentSession();
} }
/**
* Check if the connection has a currently active Transaction. A Transaction is active if it has not yet been
* either committed or rolled back.
* @return
*/
@Override @Override
public boolean isTransActionAlive() { public boolean isTransActionAlive() {
Transaction transaction = getTransaction(); Transaction transaction = getTransaction();
return transaction != null && transaction.isActive(); return transaction != null && transaction.isActive();
} }
/**
* Retrieve the current Hibernate Transaction object from our Hibernate Session.
* @return current Transaction (may be active or inactive) or null
*/
protected Transaction getTransaction() { protected Transaction getTransaction() {
return sessionFactory.getCurrentSession().getTransaction(); return sessionFactory.getCurrentSession().getTransaction();
} }
/**
* Check if Hibernate Session is still "alive" / open. An open Session may or may not have an open Transaction
* (so isTransactionAlive() may return false even if isSessionAlive() returns true). A Session may be reused for
* multiple transactions (e.g. if commit() is called, the Session remains alive while the Transaction is closed)
*
* @return true if Session is alive, false otherwise
*/
@Override @Override
public boolean isSessionAlive() { public boolean isSessionAlive() {
return sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession() return sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession().isOpen();
.getTransaction() != null && sessionFactory
.getCurrentSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE);
} }
/**
* Rollback any changes applied to the current Transaction. This also closes the Transaction. A new Transaction
* may be opened the next time getSession() is called.
* @throws SQLException
*/
@Override @Override
public void rollback() throws SQLException { public void rollback() throws SQLException {
if (isTransActionAlive()) { if (isTransActionAlive()) {
@@ -80,6 +126,14 @@ public class HibernateDBConnection implements DBConnection<Session> {
} }
} }
/**
* Close our current Database connection. This also closes & unbinds the Hibernate Session from our thread.
* <P>
* NOTE: Because DSpace configures Hibernate to automatically create a Session per thread, a Session may still
* exist after this method is called (as Hibernate may automatically create a new Session for the current thread).
* However, Hibernate will automatically clean up any existing Session when the thread closes.
* @throws SQLException
*/
@Override @Override
public void closeDBConnection() throws SQLException { public void closeDBConnection() throws SQLException {
if (sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession().isOpen()) { if (sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession().isOpen()) {
@@ -87,11 +141,23 @@ public class HibernateDBConnection implements DBConnection<Session> {
} }
} }
/**
* Commits any current changes cached in the Hibernate Session to the database & closes the Transaction.
* To open a new Transaction, you may call getSession().
* <P>
* WARNING: When commit() is called, while the Session is still "alive", all previously loaded objects (entities)
* become disconnected from the Session. Therefore, if you continue to use the Session, you MUST reload any needed
* objects (entities) using reloadEntity() method.
*
* @throws SQLException
*/
@Override @Override
public void commit() throws SQLException { public void commit() throws SQLException {
if (isTransActionAlive() && !getTransaction().getStatus().isOneOf(TransactionStatus.MARKED_ROLLBACK, if (isTransActionAlive() && !getTransaction().getStatus().isOneOf(TransactionStatus.MARKED_ROLLBACK,
TransactionStatus.ROLLING_BACK)) { TransactionStatus.ROLLING_BACK)) {
// Flush synchronizes the database with in-memory objects in Session (and frees up that memory)
getSession().flush(); getSession().flush();
// Commit those results to the database & ends the Transaction
getTransaction().commit(); getTransaction().commit();
} }
} }
@@ -132,6 +198,16 @@ public class HibernateDBConnection implements DBConnection<Session> {
return getSession().getStatistics().getEntityCount(); return getSession().getStatistics().getEntityCount();
} }
/**
* Reload an entity into the Hibernate cache. This can be called after a call to commit() to re-cache an object
* in the Hibernate Session (see commit()). Failing to reload objects into the cache may result in a Hibernate
* throwing a "LazyInitializationException" if you attempt to use an object that has been disconnected from the
* Session cache.
* @param entity The DSpace object to reload
* @param <E> The class of the entity. The entity must implement the {@link ReloadableEntity} interface.
* @return the newly cached object.
* @throws SQLException
*/
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <E extends ReloadableEntity> E reloadEntity(final E entity) throws SQLException { public <E extends ReloadableEntity> E reloadEntity(final E entity) throws SQLException {
@@ -167,10 +243,13 @@ public class HibernateDBConnection implements DBConnection<Session> {
} }
/** /**
* Evict an entity from the hibernate cache. This is necessary when batch processing a large number of items. * Evict an entity from the hibernate cache.
* <P>
* When an entity is evicted, it frees up the memory used by that entity in the cache. This is often
* necessary when batch processing a large number of objects (to avoid out-of-memory exceptions).
* *
* @param entity The entity to reload * @param entity The entity to evict
* @param <E> The class of the enity. The entity must implement the {@link ReloadableEntity} interface. * @param <E> The class of the entity. The entity must implement the {@link ReloadableEntity} interface.
* @throws SQLException When reloading the entity from the database fails. * @throws SQLException When reloading the entity from the database fails.
*/ */
@Override @Override

View File

@@ -13,6 +13,8 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.rmi.dgc.VMID; import java.rmi.dgc.VMID;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@@ -30,7 +32,10 @@ import java.util.regex.Pattern;
import com.coverity.security.Escape; import com.coverity.security.Escape;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Utility functions for DSpace. * Utility functions for DSpace.
@@ -408,4 +413,38 @@ public final class Utils {
return schema + separator + element + separator + qualifier; return schema + separator + element + separator + qualifier;
} }
} }
/**
* Retrieve the hostname from a given URI string
* @param uriString URI string
* @return hostname (without any www.) or null (if URI was invalid)
*/
public static String getHostName(String uriString) {
try {
URI uri = new URI(uriString);
String hostname = uri.getHost();
// remove the "www." from hostname, if it exists
if (hostname != null) {
return hostname.startsWith("www.") ? hostname.substring(4) : hostname;
}
return hostname;
} catch (URISyntaxException e) {
return null;
}
}
/**
* Replaces configuration placeholders within a String with the corresponding value
* from DSpace's Configuration Service.
* <P>
* For example, given a String like "My DSpace is installed at ${dspace.dir}", this
* method will replace "${dspace.dir}" with the configured value of that property.
* @param string source string
* @return string with any placeholders replaced with configured values.
*/
public static String interpolateConfigsInString(String string) {
ConfigurationService config = DSpaceServicesFactory.getInstance().getConfigurationService();
return StringSubstitutor.replace(string, config.getProperties());
}
} }

View File

@@ -465,7 +465,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
Locale.getDefault(), "internal_error")); Locale.getDefault(), "internal_error"));
email.addRecipient(recipient); email.addRecipient(recipient);
email.addArgument(ConfigurationManager email.addArgument(ConfigurationManager
.getProperty("dspace.url")); .getProperty("dspace.ui.url"));
email.addArgument(new Date()); email.addArgument(new Date());
String stackTrace; String stackTrace;

View File

@@ -7,6 +7,7 @@
*/ */
package org.dspace.discovery.configuration; package org.dspace.discovery.configuration;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.annotation.Required;
/** /**
@@ -46,4 +47,11 @@ public class DiscoverySortFieldConfiguration {
return false; return false;
} }
@Override
public int hashCode() {
return new HashCodeBuilder(3, 19)
.append(this.getMetadataField())
.append(this.getType())
.toHashCode();
}
} }

View File

@@ -228,7 +228,7 @@ public class AccountServiceImpl implements AccountService {
*/ */
protected void sendEmail(Context context, String email, boolean isRegister, RegistrationData rd) protected void sendEmail(Context context, String email, boolean isRegister, RegistrationData rd)
throws MessagingException, IOException, SQLException { throws MessagingException, IOException, SQLException {
String base = ConfigurationManager.getProperty("dspace.url"); String base = ConfigurationManager.getProperty("dspace.ui.url");
// Note change from "key=" to "token=" // Note change from "key=" to "token="
String specialLink = new StringBuffer().append(base).append( String specialLink = new StringBuffer().append(base).append(

View File

@@ -83,7 +83,7 @@ public class EPersonConsumer implements Consumer {
adminEmail.addRecipient(notifyRecipient); adminEmail.addRecipient(notifyRecipient);
adminEmail.addArgument(ConfigurationManager.getProperty("dspace.name")); adminEmail.addArgument(ConfigurationManager.getProperty("dspace.name"));
adminEmail.addArgument(ConfigurationManager.getProperty("dspace.url")); adminEmail.addArgument(ConfigurationManager.getProperty("dspace.ui.url"));
adminEmail.addArgument(eperson.getFirstName() + " " + eperson.getLastName()); // Name adminEmail.addArgument(eperson.getFirstName() + " " + eperson.getLastName()); // Name
adminEmail.addArgument(eperson.getEmail()); adminEmail.addArgument(eperson.getEmail());
adminEmail.addArgument(new Date()); adminEmail.addArgument(new Date());

View File

@@ -72,7 +72,7 @@ public class HandleServiceImpl implements HandleService {
return null; return null;
} }
String url = configurationService.getProperty("dspace.url") String url = configurationService.getProperty("dspace.ui.url")
+ "/handle/" + handle; + "/handle/" + handle;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@@ -85,7 +85,7 @@ public class HandleServiceImpl implements HandleService {
@Override @Override
public String resolveUrlToHandle(Context context, String url) public String resolveUrlToHandle(Context context, String url)
throws SQLException { throws SQLException {
String dspaceUrl = configurationService.getProperty("dspace.url") String dspaceUrl = configurationService.getProperty("dspace.ui.url")
+ "/handle/"; + "/handle/";
String handleResolver = configurationService.getProperty("handle.canonical.prefix"); String handleResolver = configurationService.getProperty("handle.canonical.prefix");

View File

@@ -38,7 +38,7 @@ public class InfoCheck extends Check {
).append("\n"); ).append("\n");
sb.append("Url: ").append( sb.append("Url: ").append(
ConfigurationManager.getProperty("dspace.url") ConfigurationManager.getProperty("dspace.ui.url")
).append("\n"); ).append("\n");
sb.append("\n"); sb.append("\n");

View File

@@ -583,7 +583,7 @@ public class EZIDIdentifierProvider
log.warn("{} #{} has no handle -- location not set.", log.warn("{} #{} has no handle -- location not set.",
contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso), dso.getID()); contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso), dso.getID());
} else { } else {
String url = configurationService.getProperty("dspace.url") String url = configurationService.getProperty("dspace.ui.url")
+ "/handle/" + item.getHandle(); + "/handle/" + item.getHandle();
log.info("Supplying location: {}", url); log.info("Supplying location: {}", url);
mapped.put("_target", url); mapped.put("_target", url);

View File

@@ -473,7 +473,7 @@ public class SimpleDSORelationsConverterPlugin
// we currently ignore those // we currently ignore those
return null; return null;
} }
String dspaceURL = configurationService.getProperty("dspace.url"); String dspaceURL = configurationService.getProperty("dspace.ui.url");
String link = ""; String link = "";
try { try {
// this currently (DSpace 4.1) works with xmlui and jspui. // this currently (DSpace 4.1) works with xmlui and jspui.

View File

@@ -249,7 +249,7 @@ public class Negotiator {
// if html is requested we have to forward to the repositories webui. // if html is requested we have to forward to the repositories webui.
if ("html".equals(lang)) { if ("html".equals(lang)) {
urlBuilder.append(DSpaceServicesFactory.getInstance() urlBuilder.append(DSpaceServicesFactory.getInstance()
.getConfigurationService().getProperty("dspace.url")); .getConfigurationService().getProperty("dspace.ui.url"));
if (!handle.equals(DSpaceServicesFactory.getInstance() if (!handle.equals(DSpaceServicesFactory.getInstance()
.getConfigurationService().getProperty("handle.prefix") + "/0")) { .getConfigurationService().getProperty("handle.prefix") + "/0")) {
urlBuilder.append("/handle/"); urlBuilder.append("/handle/");

View File

@@ -11,6 +11,7 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/** /**
* This class serves as a representation of a command line parameter by holding a String name and a String value * This class serves as a representation of a command line parameter by holding a String name and a String value
@@ -95,6 +96,7 @@ public class DSpaceCommandLineParameter {
* @param other The other object * @param other The other object
* @return A boolean indicating equality * @return A boolean indicating equality
*/ */
@Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (other == null) { if (other == null) {
return false; return false;
@@ -105,4 +107,12 @@ public class DSpaceCommandLineParameter {
return StringUtils.equals(this.getName(), ((DSpaceCommandLineParameter) other).getName()) && StringUtils return StringUtils.equals(this.getName(), ((DSpaceCommandLineParameter) other).getName()) && StringUtils
.equals(this.getValue(), ((DSpaceCommandLineParameter) other).getValue()); .equals(this.getValue(), ((DSpaceCommandLineParameter) other).getValue());
} }
@Override
public int hashCode() {
return new HashCodeBuilder(5, 17)
.append(this.getName())
.append(this.getValue())
.toHashCode();
}
} }

View File

@@ -650,7 +650,7 @@ public class StatisticsDataVisits extends StatisticsData {
} }
String url = ConfigurationManager.getProperty("dspace.url") + "/bitstream/" + identifier + "/"; String url = ConfigurationManager.getProperty("dspace.ui.url") + "/bitstream/" + identifier + "/";
// If we can put the pretty name of the bitstream on the end of the URL // If we can put the pretty name of the bitstream on the end of the URL
try { try {

View File

@@ -92,7 +92,9 @@ public class S3BitStoreService implements BitStoreService {
// bucket name // bucket name
if (StringUtils.isEmpty(bucketName)) { if (StringUtils.isEmpty(bucketName)) {
bucketName = "dspace-asset-" + ConfigurationManager.getProperty("dspace.hostname"); // get hostname of DSpace UI to use to name bucket
String hostname = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url"));
bucketName = "dspace-asset-" + hostname;
log.warn("S3 BucketName is not configured, setting default: " + bucketName); log.warn("S3 BucketName is not configured, setting default: " + bucketName);
} }
@@ -342,8 +344,10 @@ public class S3BitStoreService implements BitStoreService {
Region usEast1 = Region.getRegion(Regions.US_EAST_1); Region usEast1 = Region.getRegion(Regions.US_EAST_1);
store.s3Service.setRegion(usEast1); store.s3Service.setRegion(usEast1);
// get hostname of DSpace UI to use to name bucket
String hostname = Utils.getHostName(ConfigurationManager.getProperty("dspace.ui.url"));
//Bucketname should be lowercase //Bucketname should be lowercase
store.bucketName = "dspace-asset-" + ConfigurationManager.getProperty("dspace.hostname") + ".s3test"; store.bucketName = "dspace-asset-" + hostname + ".s3test";
store.s3Service.createBucket(store.bucketName); store.s3Service.createBucket(store.bucketName);
/* Broken in DSpace 6 TODO Refactor /* Broken in DSpace 6 TODO Refactor
// time everything, todo, swtich to caliper // time everything, todo, swtich to caliper

View File

@@ -1041,7 +1041,7 @@ public class BasicWorkflowServiceImpl implements BasicWorkflowService {
@Override @Override
public String getMyDSpaceLink() { public String getMyDSpaceLink() {
return configurationService.getProperty("dspace.url") + "/mydspace"; return configurationService.getProperty("dspace.ui.url") + "/mydspace";
} }
protected void notifyOfReject(Context context, BasicWorkflowItem workflowItem, EPerson e, protected void notifyOfReject(Context context, BasicWorkflowItem workflowItem, EPerson e,

View File

@@ -161,7 +161,7 @@ public class WorkflowUtils extends Util {
email.addRecipient(recipient); email.addRecipient(recipient);
email.addArgument(ConfigurationManager email.addArgument(ConfigurationManager
.getProperty("dspace.url")); .getProperty("dspace.ui.url"));
email.addArgument(new Date()); email.addArgument(new Date());
email.addArgument(request.getSession().getId()); email.addArgument(request.getSession().getId());
email.addArgument(logInfo); email.addArgument(logInfo);

View File

@@ -1049,7 +1049,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
email.addArgument(coll.getName()); email.addArgument(coll.getName());
email.addArgument(rejector); email.addArgument(rejector);
email.addArgument(reason); email.addArgument(reason);
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/mydspace"); email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/mydspace");
email.send(); email.send();
} catch (Exception ex) { } catch (Exception ex) {
@@ -1063,7 +1063,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
@Override @Override
public String getMyDSpaceLink() { public String getMyDSpaceLink() {
return ConfigurationManager.getProperty("dspace.url") + "/mydspace"; return ConfigurationManager.getProperty("dspace.ui.url") + "/mydspace";
} }
protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException { protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException {

View File

@@ -1,32 +0,0 @@
# Configure authority control for Unit Testing (in DSpaceControlledVocabularyTest)
# (This overrides default, commented out settings in dspace.cfg)
plugin.selfnamed.org.dspace.content.authority.ChoiceAuthority = \
org.dspace.content.authority.DCInputAuthority, \
org.dspace.content.authority.DSpaceControlledVocabulary
# Configure some more Plugins for PluginTest class
# NOTE: Plugins are just *interfaces*. So, here we are defining some plugins
# based on java.util.List interface and giving them names.
# (These are used by PluginTest)
plugin.named.java.util.List = \
java.util.ArrayList = MyArrayList, \
java.util.LinkedList = MyLinkedList, \
java.util.AttributeList = MyAttributeList
# Define a single Map plugin (used by PluginTest)
plugin.single.java.util.Map = java.util.HashMap
# Define a sequence of Collection plugins (used by PluginTest)
plugin.sequence.java.util.Collection = \
java.util.ArrayList, \
java.util.LinkedList, \
java.util.Stack, \
java.util.TreeSet
# Enable a test authority control on dc.language.iso field
choices.plugin.dc.language.iso = common_iso_languages
choices.presentation.dc.language.iso = select
authority.controlled.dc.language.iso = true
# use the testing assetstore.dir
assetstore.dir = ${dspace.dir}/assetstore

View File

@@ -25,8 +25,8 @@
# SERVER CONFIGURATION # # SERVER CONFIGURATION #
########################## ##########################
# Spring boot test by default mock the server on the localhost (80) # Spring boot test: by default mock the server on the localhost (80)
dspace.baseUrl = http://localhost dspace.server.url = http://localhost
# DSpace installation directory. # DSpace installation directory.
# This is the location where you want to install DSpace. # This is the location where you want to install DSpace.

View File

@@ -21,92 +21,18 @@
autowire="byType" autowire="byType"
scope="singleton"/> scope="singleton"/>
<!-- provider for using the versioned handle identifier instead of the default one. -->
<!--<bean id="org.dspace.identifier.HandleIdentifierProvider" class="org.dspace.identifier.VersionedHandleIdentifierProvider"-->
<!--scope="singleton">-->
<!--<property name="configurationService" ref="org.dspace.services.ConfigurationService"/>-->
<!--</bean>-->
<!-- provider to mint and register DOIs with DSpace. <!-- provider to mint and register DOIs with DSpace.
To mint DOIs you need a registration agency. The DOIIdentifierProvider To mint DOIs you need a registration agency. The DOIIdentifierProvider
maintains the doi database table and handling of DSpaceObject. It uses maintains the doi database table and handling of DSpaceObject. It uses
a DOIConnector that handles all API calls to your DOI registration a DOIConnector that handles all API calls to your DOI registration
agency. Please configure a DOIConnector as well! --> agency. Please configure a DOIConnector as well! -->
<!-- In order to mint DOIs with DSpace, get an agreement with a DOI registration
agency, take a look into dspace.cfg, and uncomment this.
-->
<bean id="org.dspace.identifier.DOIIdentifierProvider" <bean id="org.dspace.identifier.DOIIdentifierProvider"
class="org.dspace.identifier.DOIIdentifierProvider" class="org.dspace.identifier.DOIIdentifierProvider"
scope="singleton"> scope="singleton">
<property name="configurationService" <property name="configurationService"
ref="org.dspace.services.ConfigurationService"/> ref="org.dspace.services.ConfigurationService"/>
<property name="DOIConnector" <!-- NOTE: A DOIConnector is not configured here because it is mocked in the tests themselves -->
ref="org.dspace.identifier.doi.DOIConnector"/> <!--<property name="DOIConnector"
ref="org.dspace.identifier.doi.DOIConnector"/>-->
</bean> </bean>
<!-- The DOIConnector will handle the API calls to your DOI registration
agency for the DOIIdentifierProvider. If your registration agency
tells you to use the DataCite API directly, you can use the
DataCiteConnector. If your registration agency is not part of DataCite
or provides their own API, you have to implement a DOIConnector.
e.g. EZID is part of DataCite but provides their own APIs. The following
DataCiteConnector won't work if EZID is your registration agency.
-->
<!-- Uncomment this to use the DataCite API directly as DOIConnector.
<bean id="org.dspace.identifier.doi.DOIConnector"
class="org.dspace.identifier.doi.DataCiteConnector"
scope="singleton">
<property name='DATACITE_SCHEME' value='https'/>
<property name='DATACITE_HOST' value='test.datacite.org'/>
<property name='DATACITE_DOI_PATH' value='/mds/doi/' />
<property name='DATACITE_METADATA_PATH' value='/mds/metadata/' />
<property name='disseminationCrosswalkName' value="DataCite" />
</bean>
-->
<bean id="org.dspace.identifier.doi.DOIConnector" class="org.dspace.identifier.MockDOIConnector"/>
<!-- Provider to mint and register DOIs using EZID as the registrar.
-->
<!--
Set generateDataciteXML to true to send metadata in DataCite xml schema for EZID DOI mint requests.
When generateDataciteXML is enabled, EZIDIdentifierProvider uses
dspace.cfg:crosswalk.dissemination.DataCite.stylesheet XSL configuration for metadata mapping
-->
<!-- Uncomment to enable DOI using EZID
<bean id="org.dspace.identifier.EZIDIdentifierProvider"
class="org.dspace.identifier.EZIDIdentifierProvider"
scope='singleton'>
<description>Uses the EZID service to provide DOI identifiers from DataCite</description>
<property name="configurationService"
ref="org.dspace.services.ConfigurationService"/>
<property name='requestFactory'>
<bean class='org.dspace.identifier.ezid.EZIDRequestFactory'>
<property name='EZID_SCHEME' value='https'/>
<property name='EZID_HOST' value='ezid.cdlib.org'/>
<property name='EZID_PATH' value=''/>
</bean>
</property>
<property name='crosswalk'>
<map>
<entry key='datacite.creator' value='dc.contributor.author'/>
<entry key='datacite.title' value='dc.title'/>
<entry key='datacite.publisher' value='dc.publisher'/>
<entry key='datacite.publicationyear' value='dc.date.issued'/>
</map>
</property>
<property name='crosswalkTransform'>
<description>How to compute the crosswalked value from the original. Default is plain copy.</description>
<map>
<entry key='datacite.publicationyear'>
<bean class='org.dspace.identifier.ezid.DateToYear'/>
</entry>
</map>
</property>
<property name='generateDataciteXML' value='false'/>
<property name='disseminationCrosswalkName' value='DataCite'/>
</bean>
-->
</beans> </beans>

View File

@@ -1,2 +0,0 @@
<?xml version='1.0'?>
<solr/>

View File

@@ -15,15 +15,14 @@ import java.sql.SQLException;
import java.util.Properties; import java.util.Properties;
import java.util.TimeZone; import java.util.TimeZone;
import mockit.integration.junit4.JMockit;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.util.MockUtil;
import org.dspace.servicemanager.DSpaceKernelImpl; import org.dspace.servicemanager.DSpaceKernelImpl;
import org.dspace.servicemanager.DSpaceKernelInit; import org.dspace.servicemanager.DSpaceKernelInit;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
/** /**
* DSpace Unit Tests need to initialize the DSpace Kernel / Service Mgr * DSpace Unit Tests need to initialize the DSpace Kernel / Service Mgr
@@ -39,7 +38,7 @@ import org.junit.runner.RunWith;
* @see AbstractIntegrationTest * @see AbstractIntegrationTest
*/ */
@Ignore @Ignore
@RunWith(JMockit.class) @RunWith(MockitoJUnitRunner.class)
public class AbstractDSpaceTest { public class AbstractDSpaceTest {
/** /**
@@ -86,11 +85,9 @@ public class AbstractDSpaceTest {
kernelImpl = DSpaceKernelInit.getKernel(null); kernelImpl = DSpaceKernelInit.getKernel(null);
if (!kernelImpl.isRunning()) { if (!kernelImpl.isRunning()) {
// NOTE: the "dspace.dir" system property MUST be specified via Maven // NOTE: the "dspace.dir" system property MUST be specified via Maven
// For example: by using <systemPropertyVariables> of maven-surefire-plugin or maven-failsafe-plugin
kernelImpl.start(getDspaceDir()); // init the kernel kernelImpl.start(getDspaceDir()); // init the kernel
} }
// Initialize mock Util class (allows Util.getSourceVersion() to work in Unit tests)
new MockUtil();
} catch (IOException ex) { } catch (IOException ex) {
log.error("Error initializing tests", ex); log.error("Error initializing tests", ex);
fail("Error initializing tests: " + ex.getMessage()); fail("Error initializing tests: " + ex.getMessage());

View File

@@ -11,16 +11,18 @@ import static org.junit.Assert.fail;
import java.sql.SQLException; import java.sql.SQLException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.factory.AuthorizeServiceFactory; import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService; import org.dspace.authorize.service.AuthorizeService;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.I18nUtil; import org.dspace.core.I18nUtil;
import org.dspace.discovery.MockIndexEventConsumer;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.storage.rdbms.DatabaseUtils; import org.dspace.storage.rdbms.DatabaseUtils;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@@ -86,9 +88,6 @@ public class AbstractUnitTest extends AbstractDSpaceTest {
fail("Error initializing database: " + se.getMessage() fail("Error initializing database: " + se.getMessage()
+ (se.getCause() == null ? "" : ": " + se.getCause().getMessage())); + (se.getCause() == null ? "" : ": " + se.getCause().getMessage()));
} }
// Initialize mock indexer (which does nothing, since Solr isn't running)
new MockIndexEventConsumer();
} }
/** /**
@@ -127,6 +126,10 @@ public class AbstractUnitTest extends AbstractDSpaceTest {
EPersonServiceFactory.getInstance().getGroupService().initDefaultGroupNames(context); EPersonServiceFactory.getInstance().getGroupService().initDefaultGroupNames(context);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
// Ensure all tests run with Solr indexing disabled
disableSolrIndexing();
} catch (AuthorizeException ex) { } catch (AuthorizeException ex) {
log.error("Error creating initial eperson or default groups", ex); log.error("Error creating initial eperson or default groups", ex);
fail("Error creating initial eperson or default groups in AbstractUnitTest init()"); fail("Error creating initial eperson or default groups in AbstractUnitTest init()");
@@ -160,7 +163,7 @@ public class AbstractUnitTest extends AbstractDSpaceTest {
protected void cleanupContext(Context c) throws SQLException { protected void cleanupContext(Context c) throws SQLException {
// If context still valid, abort it // If context still valid, abort it
if (c != null && c.isValid()) { if (c != null && c.isValid()) {
c.complete(); c.abort();
} }
// Cleanup Context object by setting it to null // Cleanup Context object by setting it to null
@@ -168,4 +171,23 @@ public class AbstractUnitTest extends AbstractDSpaceTest {
c = null; c = null;
} }
} }
/**
* Utility method which ensures Solr indexing is DISABLED in all Tests. We turn this off because
* Solr is NOT used in the dspace-api test framework. Instead, Solr/Discovery indexing is
* exercised in the dspace-server Integration Tests (which use an embedded Solr).
*/
protected static void disableSolrIndexing() {
// Get our currently configured list of event consumers
ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
String[] consumers = configurationService.getArrayProperty("event.dispatcher.default.consumers");
// Remove "discovery" from the configured consumers (if it exists).
// This turns off Discovery/Solr indexing after any object changes.
if (ArrayUtils.contains(consumers, "discovery")) {
consumers = ArrayUtils.removeElement(consumers, "discovery");
configurationService.setProperty("event.dispatcher.default.consumers", consumers);
}
}
} }

View File

@@ -15,9 +15,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
@@ -47,7 +45,6 @@ import org.xmlunit.diff.ComparisonFormatter;
import org.xmlunit.diff.DefaultComparisonFormatter; import org.xmlunit.diff.DefaultComparisonFormatter;
import org.xmlunit.diff.Diff; import org.xmlunit.diff.Diff;
import org.xmlunit.diff.Difference; import org.xmlunit.diff.Difference;
import org.xmlunit.util.Predicate;
/** /**
* Tests of {@link StructBuilder}. * Tests of {@link StructBuilder}.
@@ -314,9 +311,9 @@ public class StructBuilderIT
} }
/** /**
* Reject uninteresting nodes. * Reject uninteresting nodes. (currently commented out of tests above)
*/ */
private static class MyNodeFilter implements Predicate<Node> { /*private static class MyNodeFilter implements Predicate<Node> {
private static final List<String> dontCare = Arrays.asList( private static final List<String> dontCare = Arrays.asList(
"description", "description",
"intro", "intro",
@@ -330,5 +327,5 @@ public class StructBuilderIT
String type = node.getLocalName(); String type = node.getLocalName();
return ! dontCare.contains(type); return ! dontCare.contains(type);
} }
} }*/
} }

View File

@@ -8,7 +8,7 @@
package org.dspace.app.util; package org.dspace.app.util;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
@@ -24,12 +24,8 @@ import org.dspace.core.Context;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class GoogleBitstreamComparatorTest extends AbstractUnitTest { public class GoogleBitstreamComparatorTest extends AbstractUnitTest {
@Mock @Mock

View File

@@ -14,7 +14,9 @@ import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List;
import com.google.common.base.Splitter;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
@@ -85,7 +87,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
log.error("SQL Error in init", ex); log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error("IO Error in init", e);
fail("IO Error in init: " + e.getMessage());
} }
} }
@@ -119,8 +122,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
context.commit(); context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it); GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/"); List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("Pdf", urlSplitted[urlSplitted.length - 1]); assertEquals("Pdf", urlSplitted.get(urlSplitted.size() - 1));
} }
/** /**
@@ -154,8 +157,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
context.commit(); context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it); GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/"); List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("size9", urlSplitted[urlSplitted.length - 1]); assertEquals("size9", urlSplitted.get(urlSplitted.size() - 1));
} }
/** /**
@@ -189,8 +192,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
context.commit(); context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it); GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/"); List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("first", urlSplitted[urlSplitted.length - 1]); assertEquals("first", urlSplitted.get(urlSplitted.size() - 1));
} }
/** /**
@@ -225,8 +228,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
context.commit(); context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it); GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/"); List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("primary", urlSplitted[urlSplitted.length - 1]); assertEquals("primary", urlSplitted.get(urlSplitted.size() - 1));
} }
/** /**
@@ -261,8 +264,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
context.commit(); context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it); GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/"); List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("large", urlSplitted[urlSplitted.length - 1]); assertEquals("large", urlSplitted.get(urlSplitted.size() - 1));
} }
@@ -285,7 +288,7 @@ public class GoogleMetadataTest extends AbstractUnitTest {
@Test @Test
public void testGetPDFURLWithNoBitstreams() throws Exception { public void testGetPDFURLWithNoBitstreams() throws Exception {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
Bundle bundle = ContentServiceFactory.getInstance().getBundleService().create(context, it, "ORIGINAL"); ContentServiceFactory.getInstance().getBundleService().create(context, it, "ORIGINAL");
context.restoreAuthSystemState(); context.restoreAuthSystemState();
context.commit(); context.commit();
@@ -319,8 +322,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
context.commit(); context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it); GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/"); List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("small", urlSplitted[urlSplitted.length - 1]); assertEquals("small", urlSplitted.get(urlSplitted.size() - 1));
} }
@After @After
@@ -334,12 +337,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
community = context.reloadEntity(community); community = context.reloadEntity(community);
ContentServiceFactory.getInstance().getCommunityService().delete(context, community); ContentServiceFactory.getInstance().getCommunityService().delete(context, community);
community = null; community = null;
} catch (SQLException e) { } catch (Exception e) {
e.printStackTrace(); throw new AssertionError("Error occurred in destroy()", e);
} catch (AuthorizeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
it = null; it = null;
super.destroy(); super.destroy();

View File

@@ -1,34 +0,0 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.util;
import mockit.Mock;
import mockit.MockUp;
/**
* Mocks the "Util" class, as the getSourceVersion() method in this class
* is not usable in Unit Testing (since the final JAR is not yet created)
*
* @author Tim Donohue
*/
public class MockUtil extends MockUp<Util> {
/**
* Override/Mock the default "getSourceVersion()" method. This method
* relies on the "pom.properties" file which is generated by Maven ONLY
* when building the final dspace-api.jar. During Unit Testing, this
* "pom.properties" file does NOT exist, which causes a NPE to be thrown.
* <P>
* This mocked method simply returns the version as "unit-testing".
*
* @return "unit-testing" since this is only used during Unit Tests
*/
@Mock
public static String getSourceVersion() {
return "unit-testing";
}
}

View File

@@ -264,8 +264,8 @@ public class IPMatcherTest {
assertFalse(ipMatcher.match("192.1.2.2")); assertFalse(ipMatcher.match("192.1.2.2"));
} }
// Commented out as this is currently not used in tests
private ArrayList<String> getAllIp4Except(ArrayList<String> exceptions) { /*private ArrayList<String> getAllIp4Except(ArrayList<String> exceptions) {
int d1 = 0; int d1 = 0;
int d2 = 0; int d2 = 0;
int d3 = 0; int d3 = 0;
@@ -284,7 +284,7 @@ public class IPMatcherTest {
} }
} }
return ips; return ips;
} }*/
private void verifyAllIp4Except(ArrayList<String> exceptions, boolean asserted, IPMatcher ipMatcher) private void verifyAllIp4Except(ArrayList<String> exceptions, boolean asserted, IPMatcher ipMatcher)
throws IPMatcherException { throws IPMatcherException {

View File

@@ -90,8 +90,7 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
@Test @Test
public void testauthorizeMethodRespectSpecialGroups() { public void testauthorizeMethodRespectSpecialGroups() {
EPerson eperson1; EPerson eperson;
EPerson eperson2;
Group group1; Group group1;
Community dso; Community dso;
@@ -99,7 +98,7 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
// create an eperson and a group // create an eperson and a group
eperson1 = ePersonService.create(context); eperson = ePersonService.create(context);
group1 = groupService.create(context); group1 = groupService.create(context);
// A group has to have a name, otherwise there are queries that break // A group has to have a name, otherwise there are queries that break
groupService.setName(group1, "My test group 2"); groupService.setName(group1, "My test group 2");
@@ -111,19 +110,19 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
// special group to the user. Then test if the action on the DSO // special group to the user. Then test if the action on the DSO
// is allowed for the user // is allowed for the user
authorizeService.addPolicy(context, dso, Constants.ADD, group1); authorizeService.addPolicy(context, dso, Constants.ADD, group1);
context.setCurrentUser(eperson1); context.setCurrentUser(eperson);
context.setSpecialGroup(group1.getID()); context.setSpecialGroup(group1.getID());
context.commit(); context.commit();
} catch (SQLException | AuthorizeException ex) { } catch (SQLException | AuthorizeException ex) {
throw new RuntimeException(ex); throw new AssertionError(ex);
} finally { } finally {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
} }
try { try {
Assert.assertTrue(authorizeService.authorizeActionBoolean(context, eperson1, dso, Constants.ADD, true)); Assert.assertTrue(authorizeService.authorizeActionBoolean(context, eperson, dso, Constants.ADD, true));
} catch (SQLException ex) { } catch (SQLException ex) {
throw new RuntimeException(ex); throw new AssertionError(ex);
} }
} }
} }

View File

@@ -15,23 +15,24 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeServiceImpl; import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.dspace.core.Context;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* This class tests BitstreamFormat. Due to it being tighly coupled with the * This class tests BitstreamFormat. Due to it being tighly coupled with the
@@ -60,6 +61,11 @@ public class BitstreamFormatTest extends AbstractUnitTest {
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance() protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance()
.getBitstreamFormatService(); .getBitstreamFormatService();
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
@@ -75,6 +81,13 @@ public class BitstreamFormatTest extends AbstractUnitTest {
try { try {
bf = bitstreamFormatService.find(context, 5); bf = bitstreamFormatService.find(context, 5);
bunknown = bitstreamFormatService.findUnknown(context); bunknown = bitstreamFormatService.findUnknown(context);
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded bitstreamFormatService
// (To ensure it uses the spy instead of the real service)
ReflectionTestUtils.setField(bitstreamFormatService, "authorizeService", authorizeServiceSpy);
} catch (SQLException ex) { } catch (SQLException ex) {
log.error("SQL Error in init", ex); log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
@@ -199,11 +212,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testCreateAdmin() throws SQLException, AuthorizeException { public void testCreateAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full Admin perms // Allow full Admin perms
authorizeService.isAdmin((Context) any); when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
result = true;
}};
BitstreamFormat found = bitstreamFormatService.create(context); BitstreamFormat found = bitstreamFormatService.create(context);
assertThat("testCreate 0", found, notNullValue()); assertThat("testCreate 0", found, notNullValue());
@@ -219,13 +229,10 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateNotAdmin() throws SQLException, AuthorizeException { public void testCreateNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Disalow full Admin perms
// Disallow full Admin perms when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
authorizeService.isAdmin((Context) any);
result = false;
}};
BitstreamFormat found = bitstreamFormatService.create(context); bitstreamFormatService.create(context);
fail("Exception should have been thrown"); fail("Exception should have been thrown");
} }
@@ -442,11 +449,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testUpdateNotAdmin() throws SQLException, AuthorizeException { public void testUpdateNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full Admin perms // Disallow full Admin perms
authorizeService.isAdmin((Context) any); when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
result = false;
}};
bitstreamFormatService.update(context, bf); bitstreamFormatService.update(context, bf);
fail("Exception should have been thrown"); fail("Exception should have been thrown");
@@ -457,11 +461,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testUpdateAdmin() throws SQLException, AuthorizeException { public void testUpdateAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full Admin perms // Allow full Admin perms
authorizeService.isAdmin((Context) any); when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
result = true;
}};
String desc = "Test description"; String desc = "Test description";
String oldDescription = bf.getDescription(); String oldDescription = bf.getDescription();
@@ -478,11 +479,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testDeleteNotAdmin() throws SQLException, AuthorizeException { public void testDeleteNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full Admin perms // Disallow full Admin perms
authorizeService.isAdmin((Context) any); when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
result = false;
}};
bitstreamFormatService.delete(context, bf); bitstreamFormatService.delete(context, bf);
fail("Exception should have been thrown"); fail("Exception should have been thrown");
@@ -493,11 +491,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testDeleteAdmin() throws SQLException, AuthorizeException { public void testDeleteAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full Admin perms // Allow full Admin perms
authorizeService.isAdmin((Context) any); when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
result = true;
}};
BitstreamFormat bitstreamFormat = bitstreamFormatService.create(context); BitstreamFormat bitstreamFormat = bitstreamFormatService.create(context);
int toDeleteIdentifier = bitstreamFormat.getID(); int toDeleteIdentifier = bitstreamFormat.getID();
@@ -511,11 +506,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/ */
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testDeleteUnknown() throws SQLException, AuthorizeException { public void testDeleteUnknown() throws SQLException, AuthorizeException {
new NonStrictExpectations(AuthorizeServiceImpl.class) {{
// Allow full Admin perms // Allow full Admin perms
authorizeService.isAdmin((Context) any); when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
result = true;
}};
bitstreamFormatService.delete(context, bunknown); bitstreamFormatService.delete(context, bunknown);
fail("Exception should have been thrown"); fail("Exception should have been thrown");

View File

@@ -15,6 +15,11 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -23,9 +28,9 @@ import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.dspace.core.Constants; import org.dspace.core.Constants;
@@ -33,6 +38,7 @@ import org.dspace.core.Context;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Unit Tests for class Bitstream * Unit Tests for class Bitstream
@@ -54,6 +60,12 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/ */
private Bitstream bs; private Bitstream bs;
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
* initialize resources required for the tests. * initialize resources required for the tests.
@@ -67,10 +79,18 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
super.init(); super.init();
try { try {
//we have to create a new bitstream in the database //we have to create a new bitstream in the database
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
this.bs = bitstreamService.create(context, new FileInputStream(f)); this.bs = bitstreamService.create(context, new FileInputStream(f));
this.dspaceObject = bs; this.dspaceObject = bs;
//we need to commit the changes so we don't block the table for testing context.restoreAuthSystemState();
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded bitstreamService
// (To ensure it uses the spy instead of the real service)
ReflectionTestUtils.setField(bitstreamService, "authorizeService", authorizeServiceSpy);
} catch (IOException ex) { } catch (IOException ex) {
log.error("IO Error in init", ex); log.error("IO Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
@@ -146,11 +166,10 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testRegister() throws IOException, SQLException, AuthorizeException { public void testRegister() throws IOException, SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow general Bitstream WRITE permissions
authorizeService.authorizeAction((Context) any, (Bitstream) any, doNothing().when(authorizeServiceSpy).authorizeAction(any(Context.class), any(Bitstream.class),
Constants.WRITE); eq(Constants.WRITE));
result = null;
}};
int assetstore = 0; int assetstore = 0;
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream registered = bitstreamService.register(context, assetstore, f.getName()); Bitstream registered = bitstreamService.register(context, assetstore, f.getName());
@@ -366,13 +385,9 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testUpdateNotAdmin() throws SQLException, AuthorizeException { public void testUpdateNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Disallow Bitstream WRITE permissions
// Disallow Bitstream WRITE perms doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, bs, Constants.WRITE);
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = new AuthorizeException();
}};
//TODO: we need to verify the update, how? //TODO: we need to verify the update, how?
bitstreamService.update(context, bs); bitstreamService.update(context, bs);
} }
@@ -382,13 +397,8 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testUpdateAdmin() throws SQLException, AuthorizeException { public void testUpdateAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Bitstream WRITE permissions
// Allow Bitstream WRITE perms doNothing().when(authorizeServiceSpy).authorizeAction(context, bs, Constants.WRITE);
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
//TODO: we need to verify the update, how? //TODO: we need to verify the update, how?
bitstreamService.update(context, bs); bitstreamService.update(context, bs);
@@ -399,21 +409,18 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testDeleteAndExpunge() throws IOException, SQLException, AuthorizeException { public void testDeleteAndExpunge() throws IOException, SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bitstream WRITE perms
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.DELETE);
result = null;
}};
// Create a new bitstream, which we can delete. As ordering of these // Create a new bitstream, which we can delete. As ordering of these
// tests is unpredictable we don't want to delete the global bitstream // tests is unpredictable we don't want to delete the global bitstream
context.ignoreAuthorization();
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream delBS = bitstreamService.create(context, new FileInputStream(f)); Bitstream delBS = bitstreamService.create(context, new FileInputStream(f));
UUID bitstreamId = delBS.getID(); UUID bitstreamId = delBS.getID();
context.restoreAuthSystemState();
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, delBS, Constants.WRITE);
// Allow Bitstream DELETE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, delBS, Constants.DELETE);
// Test that delete will flag the bitstream as deleted // Test that delete will flag the bitstream as deleted
assertFalse("testIsDeleted 0", delBS.isDeleted()); assertFalse("testIsDeleted 0", delBS.isDeleted());
@@ -431,12 +438,8 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
@Test @Test
public void testRetrieveCanRead() throws IOException, SQLException, public void testRetrieveCanRead() throws IOException, SQLException,
AuthorizeException { AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Bitstream READ permissions
// Allow Bitstream READ perms doNothing().when(authorizeServiceSpy).authorizeAction(context, bs, Constants.READ);
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.READ);
result = null;
}};
assertThat("testRetrieveCanRead 0", bitstreamService.retrieve(context, bs), notNullValue()); assertThat("testRetrieveCanRead 0", bitstreamService.retrieve(context, bs), notNullValue());
} }
@@ -447,12 +450,8 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testRetrieveNoRead() throws IOException, SQLException, public void testRetrieveNoRead() throws IOException, SQLException,
AuthorizeException { AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Disallow Bitstream READ permissions
// Disallow Bitstream READ perms doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, bs, Constants.READ);
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.READ);
result = new AuthorizeException();
}};
assertThat("testRetrieveNoRead 0", bitstreamService.retrieve(context, bs), notNullValue()); assertThat("testRetrieveNoRead 0", bitstreamService.retrieve(context, bs), notNullValue());
} }

View File

@@ -15,6 +15,11 @@ import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -26,16 +31,17 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import mockit.NonStrictExpectations;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy; import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Units tests for class Bundle * Units tests for class Bundle
@@ -56,6 +62,11 @@ public class BundleTest extends AbstractDSpaceObjectTest {
private Collection collection; private Collection collection;
private Community owningCommunity; private Community owningCommunity;
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
@@ -79,6 +90,15 @@ public class BundleTest extends AbstractDSpaceObjectTest {
//we need to commit the changes so we don't block the table for testing //we need to commit the changes so we don't block the table for testing
context.restoreAuthSystemState(); context.restoreAuthSystemState();
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded itemService, bundleService & bitstreamService
// (To ensure it uses the spy instead of the real service)
ReflectionTestUtils.setField(itemService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(bundleService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(bitstreamService, "authorizeService", authorizeServiceSpy);
} catch (SQLException | AuthorizeException ex) { } catch (SQLException | AuthorizeException ex) {
log.error("SQL Error in init", ex); log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
@@ -155,14 +175,9 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCreate() throws SQLException, AuthorizeException { public void testCreate() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) { // Allow Item ADD permissions
{ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.ADD);
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
}
};
Bundle created = bundleService.create(context, item, "testCreateBundle"); Bundle created = bundleService.create(context, item, "testCreateBundle");
//the item created by default has no name nor type set //the item created by default has no name nor type set
assertThat("testCreate 0", created, notNullValue()); assertThat("testCreate 0", created, notNullValue());
@@ -221,16 +236,14 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testSetPrimaryBitstreamID() throws SQLException, AuthorizeException, IOException { public void testSetPrimaryBitstreamID() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) { // Allow Item WRITE permissions
{ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD perms // Allow Bundle ADD permissions
authorizeService.authorizeAction((Context) any, (Bundle) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
Constants.ADD); // Allow Bitstream WRITE permissions
authorizeService.authorizeAction((Context) any, (Bitstream) any, doNothing().when(authorizeServiceSpy)
Constants.WRITE); .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
result = null;
}
};
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bundleService.addBitstream(context, b, bs); bundleService.addBitstream(context, b, bs);
@@ -243,16 +256,14 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testUnsetPrimaryBitstreamID() throws IOException, SQLException, AuthorizeException { public void testUnsetPrimaryBitstreamID() throws IOException, SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) { // Allow Item WRITE permissions
{ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD perms // Allow Bundle ADD permissions
authorizeService.authorizeAction((Context) any, (Bundle) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
Constants.ADD); // Allow Bitstream WRITE permissions
authorizeService.authorizeAction((Context) any, (Bitstream) any, doNothing().when(authorizeServiceSpy)
Constants.WRITE); .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
result = null;
}
};
//set a value different than default //set a value different than default
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
@@ -279,27 +290,25 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testGetBitstreamByName() throws FileNotFoundException, SQLException, IOException, AuthorizeException { public void testGetBitstreamByName() throws FileNotFoundException, SQLException, IOException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Bundle ADD permissions
// Allow Bundle ADD perms doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bitstream WRITE permissions
Constants.ADD); doNothing().when(authorizeServiceSpy)
result = null; .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
String name = "name"; String name = "name";
//by default there is no bitstream //by default there is no bitstream
assertThat("testGetHandle 0", bundleService.getBitstreamByName(b, name), nullValue()); assertThat("testGetHandle 0", bundleService.getBitstreamByName(b, name), nullValue());
//let's add a bitstream //let's add a bitstream
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, name); bs.setName(context, name);
bundleService.addBitstream(context, b, bs); bundleService.addBitstream(context, b, bs);
bundleService.update(context, b); bundleService.update(context, b);
context.restoreAuthSystemState();
assertThat("testGetHandle 1", bundleService.getBitstreamByName(b, name), notNullValue()); assertThat("testGetHandle 1", bundleService.getBitstreamByName(b, name), notNullValue());
assertThat("testGetHandle 2", bundleService.getBitstreamByName(b, name), equalTo(bs)); assertThat("testGetHandle 2", bundleService.getBitstreamByName(b, name), equalTo(bs));
assertThat("testGetHandle 3", bundleService.getBitstreamByName(b, name).getName(), equalTo(name)); assertThat("testGetHandle 3", bundleService.getBitstreamByName(b, name).getName(), equalTo(name));
@@ -310,27 +319,25 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testGetBitstreams() throws FileNotFoundException, SQLException, IOException, AuthorizeException { public void testGetBitstreams() throws FileNotFoundException, SQLException, IOException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Bundle ADD permissions
// Allow Bundle ADD perms doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bitstream WRITE permissions
Constants.ADD); doNothing().when(authorizeServiceSpy)
result = null; .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
//default bundle has no bitstreams //default bundle has no bitstreams
assertThat("testGetBitstreams 0", b.getBitstreams(), notNullValue()); assertThat("testGetBitstreams 0", b.getBitstreams(), notNullValue());
assertThat("testGetBitstreams 1", b.getBitstreams().size(), equalTo(0)); assertThat("testGetBitstreams 1", b.getBitstreams().size(), equalTo(0));
//let's add a bitstream //let's add a bitstream
context.turnOffAuthorisationSystem();
String name = "name"; String name = "name";
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, name); bs.setName(context, name);
bundleService.addBitstream(context, b, bs); bundleService.addBitstream(context, b, bs);
context.restoreAuthSystemState();
assertThat("testGetBitstreams 2", b.getBitstreams(), notNullValue()); assertThat("testGetBitstreams 2", b.getBitstreams(), notNullValue());
assertThat("testGetBitstreams 3", b.getBitstreams().size(), equalTo(1)); assertThat("testGetBitstreams 3", b.getBitstreams().size(), equalTo(1));
assertThat("testGetBitstreams 4", b.getBitstreams().get(0).getName(), equalTo(name)); assertThat("testGetBitstreams 4", b.getBitstreams().get(0).getName(), equalTo(name));
@@ -352,16 +359,11 @@ public class BundleTest extends AbstractDSpaceObjectTest {
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateBitstreamNoAuth() public void testCreateBitstreamNoAuth()
throws FileNotFoundException, AuthorizeException, SQLException, IOException { throws FileNotFoundException, AuthorizeException, SQLException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Disallow Bundle ADD permissions
// Disallow Bundle ADD perms doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = new AuthorizeException();
}};
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, b, new FileInputStream(f)); bitstreamService.create(context, b, new FileInputStream(f));
fail("Exception should be thrown"); fail("Exception should be thrown");
} }
@@ -370,16 +372,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCreateBitstreamAuth() throws FileNotFoundException, AuthorizeException, SQLException, IOException { public void testCreateBitstreamAuth() throws FileNotFoundException, AuthorizeException, SQLException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Item WRITE permissions
// Allow Bundle ADD perms doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bundle ADD permissions
Constants.ADD); doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
result = null; // Allow Bitstream WRITE permissions
authorizeService.authorizeAction((Context) any, (Bitstream) any, doNothing().when(authorizeServiceSpy)
Constants.WRITE); .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
result = null;
}};
String name = "name"; String name = "name";
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
@@ -395,17 +394,12 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testRegisterBitstreamNoAuth() throws AuthorizeException, IOException, SQLException { public void testRegisterBitstreamNoAuth() throws AuthorizeException, IOException, SQLException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Disallow Bundle ADD permissions
// Disallow Bundle ADD perms doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = new AuthorizeException();
}};
int assetstore = 0; //default assetstore int assetstore = 0; //default assetstore
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.register(context, b, assetstore, f.getAbsolutePath()); bitstreamService.register(context, b, assetstore, f.getAbsolutePath());
fail("Exception should be thrown"); fail("Exception should be thrown");
} }
@@ -414,16 +408,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testRegisterBitstreamAuth() throws AuthorizeException, IOException, SQLException { public void testRegisterBitstreamAuth() throws AuthorizeException, IOException, SQLException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Item WRITE permissions
// Allow Bundle ADD perms doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bundle ADD permissions
Constants.ADD); doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
result = null; // Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
authorizeService.authorizeAction((Context) any, (Bitstream) any, .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
Constants.WRITE);
result = null;
}};
int assetstore = 0; //default assetstore int assetstore = 0; //default assetstore
String name = "name bitstream"; String name = "name bitstream";
@@ -440,13 +431,8 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testAddBitstreamNoAuth() throws SQLException, AuthorizeException, IOException { public void testAddBitstreamNoAuth() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Disallow Bundle ADD permissions
// Disallow Bundle ADD perms doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = new AuthorizeException();
}};
// create a new Bitstream to add to Bundle // create a new Bitstream to add to Bundle
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
@@ -461,16 +447,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testAddBitstreamAuth() throws SQLException, AuthorizeException, FileNotFoundException, IOException { public void testAddBitstreamAuth() throws SQLException, AuthorizeException, FileNotFoundException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Item WRITE permissions
// Allow Bundle ADD perms doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bundle ADD permissions
Constants.ADD); doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
result = null; // Allow Bitstream WRITE permissions
authorizeService.authorizeAction((Context) any, (Bitstream) any, doNothing().when(authorizeServiceSpy)
Constants.WRITE); .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
result = null;
}};
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
@@ -487,17 +470,15 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testRemoveBitstreamNoAuth() throws SQLException, AuthorizeException, IOException { public void testRemoveBitstreamNoAuth() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Disallow Bundle ADD permissions
// Disallow Bundle REMOVE perms doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.REMOVE);
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.REMOVE);
result = new AuthorizeException();
}};
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
context.turnOffAuthorisationSystem();
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, "name"); bs.setName(context, "name");
context.restoreAuthSystemState();
bundleService.removeBitstream(context, b, bs); bundleService.removeBitstream(context, b, bs);
fail("Exception should have been thrown"); fail("Exception should have been thrown");
} }
@@ -507,28 +488,26 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testRemoveBitstreamAuth() throws SQLException, AuthorizeException, IOException { public void testRemoveBitstreamAuth() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Item WRITE permissions (to create a new bitstream)
// Allow Bundle ADD perms (to create a new Bitstream and add it) doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bundle ADD permissions (to create a new bitstream)
Constants.ADD); doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
result = null; // Allow Bundle REMOVE permissions
// Allow Bundle REMOVE perms (to test remove) doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.REMOVE);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bitstream WRITE permissions
Constants.REMOVE); doNothing().when(authorizeServiceSpy)
result = null; .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
authorizeService.authorizeAction((Context) any, (Bitstream) any, // Allow Bitstream DELETE permissions
Constants.WRITE); doNothing().when(authorizeServiceSpy)
result = null; .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.DELETE));
authorizeService.authorizeAction(context, (Bitstream) any,
Constants.DELETE);
result = null;
}};
// Create a new Bitstream to test with // Create a new Bitstream to test with
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bundleService.addBitstream(context, b, bs); bundleService.addBitstream(context, b, bs);
context.restoreAuthSystemState();
bundleService.removeBitstream(context, b, bs); bundleService.removeBitstream(context, b, bs);
assertThat("testRemoveBitstreamAuth 0", bundleService.getBitstreamByName(b, bs.getName()), nullValue()); assertThat("testRemoveBitstreamAuth 0", bundleService.getBitstreamByName(b, bs.getName()), nullValue());
} }
@@ -549,19 +528,10 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testDelete() throws SQLException, AuthorizeException, IOException { public void testDelete() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Item REMOVE permissions
// Allow Bundle ADD perms (to create a new Bitstream and add it) doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.REMOVE);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bundle DELETE permissions
Constants.ADD); doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.DELETE);
result = null;
// Allow Bundle REMOVE perms (to test remove)
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.REMOVE);
result = null;
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.DELETE);
result = null;
}};
UUID id = b.getID(); UUID id = b.getID();
itemService.removeBundle(context, item, b); itemService.removeBundle(context, item, b);
@@ -676,17 +646,18 @@ public class BundleTest extends AbstractDSpaceObjectTest {
@Test @Test
public void testSetOrder() throws SQLException, AuthorizeException, FileNotFoundException, IOException { public void testSetOrder() throws SQLException, AuthorizeException, FileNotFoundException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Item WRITE permissions
// Allow Bundle ADD perms doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
authorizeService.authorizeAction((Context) any, (Bundle) any, // Allow Bundle ADD permissions
Constants.ADD); doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
result = null; // Allow Bundle WRITE permissions
authorizeService.authorizeAction((Context) any, (Bitstream) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.WRITE);
Constants.WRITE); // Allow Bitstream WRITE permissions
result = null; doNothing().when(authorizeServiceSpy)
}}; .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
// Create three Bitstreams to test ordering with. Give them different names // Create three Bitstreams to test ordering with. Give them different names
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, "bitstream1"); bs.setName(context, "bitstream1");
@@ -697,6 +668,7 @@ public class BundleTest extends AbstractDSpaceObjectTest {
Bitstream bs3 = bitstreamService.create(context, new FileInputStream(f)); Bitstream bs3 = bitstreamService.create(context, new FileInputStream(f));
bs3.setName(context, "bitstream3"); bs3.setName(context, "bitstream3");
bundleService.addBitstream(context, b, bs3); bundleService.addBitstream(context, b, bs3);
context.restoreAuthSystemState();
// Assert Bitstreams are in the order added // Assert Bitstreams are in the order added
Bitstream[] bitstreams = b.getBitstreams().toArray(new Bitstream[b.getBitstreams().size()]); Bitstream[] bitstreams = b.getBitstreams().toArray(new Bitstream[b.getBitstreams().size()]);

File diff suppressed because it is too large Load Diff

View File

@@ -19,7 +19,6 @@ import java.util.Locale;
import java.util.TimeZone; import java.util.TimeZone;
import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.Logger;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -28,11 +27,6 @@ import org.junit.Test;
* @author pvillega * @author pvillega
*/ */
public class DCDateTest { public class DCDateTest {
/**
* log4j category
*/
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(DCDateTest.class);
/** /**
* Object to use in the tests * Object to use in the tests
*/ */

View File

@@ -8,16 +8,14 @@
package org.dspace.content; package org.dspace.content;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.dspace.content.dao.RelationshipTypeDAO;
import org.dspace.content.service.EntityTypeService; import org.dspace.content.service.EntityTypeService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.RelationshipService; import org.dspace.content.service.RelationshipService;
@@ -27,7 +25,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class EntityServiceImplTest { public class EntityServiceImplTest {
@@ -60,10 +58,8 @@ public class EntityServiceImplTest {
public void testfindByItemId() throws Exception { public void testfindByItemId() throws Exception {
// Declare objects utilized in unit test // Declare objects utilized in unit test
Item item = mock(Item.class); Item item = mock(Item.class);
List<Relationship> relationshipList = new ArrayList<>();
Relationship relationship = mock(Relationship.class); Relationship relationship = mock(Relationship.class);
relationship.setId(9); relationship.setId(9);
relationshipList.add(relationship);
// Mock the state of objects utilized in findByItemId() to meet the success criteria of an invocation // Mock the state of objects utilized in findByItemId() to meet the success criteria of an invocation
when(itemService.find(any(), any())).thenReturn(item); when(itemService.find(any(), any())).thenReturn(item);
@@ -79,10 +75,6 @@ public class EntityServiceImplTest {
// Declare objects utilized in unit test // Declare objects utilized in unit test
Entity entity = mock(Entity.class); Entity entity = mock(Entity.class);
EntityTypeService entityTypeService = mock(EntityTypeService.class); EntityTypeService entityTypeService = mock(EntityTypeService.class);
Item item = mock(Item.class);
List<MetadataValue> list = new ArrayList<>();
MetadataValue metadataValue = mock(MetadataValue.class);
list.add(metadataValue);
EntityType entityType = entityTypeService.findByEntityType(context, "testType"); EntityType entityType = entityTypeService.findByEntityType(context, "testType");
// The returned EntityType should equal our defined entityType case // The returned EntityType should equal our defined entityType case
@@ -151,11 +143,7 @@ public class EntityServiceImplTest {
@Test @Test
public void testGetAllRelationshipTypes() throws Exception { public void testGetAllRelationshipTypes() throws Exception {
// Declare objects utilized for this test // Declare objects utilized for this test
List<MetadataValue> list = new ArrayList<>();
MetadataValue metadataValue = mock(MetadataValue.class);
list.add(metadataValue);
Item item = mock(Item.class); Item item = mock(Item.class);
RelationshipTypeDAO relationshipTypeDAO = mock(RelationshipTypeDAO.class);
Entity entity = mock(Entity.class); Entity entity = mock(Entity.class);
RelationshipType relationshipType = mock(RelationshipType.class); RelationshipType relationshipType = mock(RelationshipType.class);
relationshipType.setLeftType(leftType); relationshipType.setLeftType(leftType);
@@ -185,7 +173,7 @@ public class EntityServiceImplTest {
RelationshipType relationshipType = mock(RelationshipType.class); RelationshipType relationshipType = mock(RelationshipType.class);
// Currently this unit test will only test one case with one relationshipType // Currently this unit test will only test one case with one relationshipType
List<RelationshipType> relationshipTypeList = new LinkedList<>(); List<RelationshipType> relationshipTypeList = new ArrayList<>();
relationshipTypeList.add(relationshipType); relationshipTypeList.add(relationshipType);
List<MetadataValue> metsList = new ArrayList<>(); List<MetadataValue> metsList = new ArrayList<>();
MetadataValue metadataValue = mock(MetadataValue.class); MetadataValue metadataValue = mock(MetadataValue.class);
@@ -213,7 +201,7 @@ public class EntityServiceImplTest {
RelationshipType relationshipType = mock(RelationshipType.class); RelationshipType relationshipType = mock(RelationshipType.class);
// Currently this unit test will only test one case with one relationshipType // Currently this unit test will only test one case with one relationshipType
List<RelationshipType> relationshipTypeList = new LinkedList<>(); List<RelationshipType> relationshipTypeList = new ArrayList<>();
relationshipTypeList.add(relationshipType); relationshipTypeList.add(relationshipType);
List<MetadataValue> metsList = new ArrayList<>(); List<MetadataValue> metsList = new ArrayList<>();
MetadataValue metadataValue = mock(MetadataValue.class); MetadataValue metadataValue = mock(MetadataValue.class);
@@ -236,7 +224,7 @@ public class EntityServiceImplTest {
@Test @Test
public void testGetRelationshipTypesByTypeName() throws Exception { public void testGetRelationshipTypesByTypeName() throws Exception {
// Declare objects utilized in unit test // Declare objects utilized in unit test
List<RelationshipType> list = new LinkedList<>(); List<RelationshipType> list = new ArrayList<>();
RelationshipType relationshipType = mock(RelationshipType.class); RelationshipType relationshipType = mock(RelationshipType.class);
list.add(relationshipType); list.add(relationshipType);

View File

@@ -8,7 +8,7 @@
package org.dspace.content; package org.dspace.content;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@@ -23,7 +23,7 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class EntityTypeServiceImplTest { public class EntityTypeServiceImplTest {

View File

@@ -14,7 +14,6 @@ import static org.junit.Assert.assertThat;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
@@ -30,11 +29,6 @@ import org.junit.Test;
*/ */
public class FormatIdentifierTest extends AbstractUnitTest { public class FormatIdentifierTest extends AbstractUnitTest {
/**
* log4j category
*/
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(FormatIdentifierTest.class);
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService(); protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance() protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance()
.getBitstreamFormatService(); .getBitstreamFormatService();
@@ -71,8 +65,8 @@ public class FormatIdentifierTest extends AbstractUnitTest {
@Test @Test
public void testGuessFormat() throws Exception { public void testGuessFormat() throws Exception {
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = null; Bitstream bs;
BitstreamFormat result = null; BitstreamFormat result;
BitstreamFormat pdf = bitstreamFormatService.findByShortDescription(context, "Adobe PDF"); BitstreamFormat pdf = bitstreamFormatService.findByShortDescription(context, "Adobe PDF");
//test null filename //test null filename

View File

@@ -19,7 +19,6 @@ import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.UUID; import java.util.UUID;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractIntegrationTest; import org.dspace.AbstractIntegrationTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
@@ -48,11 +47,6 @@ import org.junit.Test;
* @author tdonohue * @author tdonohue
*/ */
public class ITCommunityCollection extends AbstractIntegrationTest { public class ITCommunityCollection extends AbstractIntegrationTest {
/**
* log4j category
*/
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ITCommunityCollection.class);
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();
@@ -107,8 +101,8 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
//verify it works as expected //verify it works as expected
assertThat("testCreateTree 0", parent.getParentCommunities().size(), is(0)); assertThat("testCreateTree 0", parent.getParentCommunities().size(), is(0));
assertThat("testCreateTree 1", child1.getParentCommunities().get(0), equalTo(parent)); assertThat("testCreateTree 1", child1.getParentCommunities().get(0), equalTo(parent));
assertThat("testCreateTree 2", (Community) collectionService.getParentObject(context, col1), equalTo(child1)); assertThat("testCreateTree 2", collectionService.getParentObject(context, col1), equalTo(child1));
assertThat("testCreateTree 3", (Community) collectionService.getParentObject(context, col2), equalTo(child1)); assertThat("testCreateTree 3", collectionService.getParentObject(context, col2), equalTo(child1));
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
communityService.delete(context, parent); communityService.delete(context, parent);
@@ -133,8 +127,8 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
//verify it works as expected //verify it works as expected
assertThat("testCreateItems 0", (Collection) itemService.getParentObject(context, item1), equalTo(col1)); assertThat("testCreateItems 0", itemService.getParentObject(context, item1), equalTo(col1));
assertThat("testCreateItems 1", (Collection) itemService.getParentObject(context, item2), equalTo(col2)); assertThat("testCreateItems 1", itemService.getParentObject(context, item2), equalTo(col2));
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
communityService.delete(context, parent); communityService.delete(context, parent);
@@ -158,8 +152,8 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
// Add same number of items to each collection // Add same number of items to each collection
for (int count = 0; count < items_per_collection; count++) { for (int count = 0; count < items_per_collection; count++) {
Item item1 = installItemService.installItem(context, workspaceItemService.create(context, col1, false)); installItemService.installItem(context, workspaceItemService.create(context, col1, false));
Item item2 = installItemService.installItem(context, workspaceItemService.create(context, col2, false)); installItemService.installItem(context, workspaceItemService.create(context, col2, false));
} }
// Finally, let's throw in a small wrench and add a mapped item // Finally, let's throw in a small wrench and add a mapped item
@@ -229,7 +223,6 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
context.setCurrentUser(commAdmin); context.setCurrentUser(commAdmin);
// Test deletion of single Bitstream as a Community Admin (delete just flags as deleted) // Test deletion of single Bitstream as a Community Admin (delete just flags as deleted)
UUID bitstreamId = bitstream.getID();
bitstreamService.delete(context, bitstream); bitstreamService.delete(context, bitstream);
assertTrue("Community Admin unable to flag Bitstream as deleted", assertTrue("Community Admin unable to flag Bitstream as deleted",
bitstream.isDeleted()); bitstream.isDeleted());
@@ -312,7 +305,6 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
context.setCurrentUser(collAdmin); context.setCurrentUser(collAdmin);
// Test deletion of single Bitstream as a Collection Admin (delete just flags as deleted) // Test deletion of single Bitstream as a Collection Admin (delete just flags as deleted)
UUID bitstreamId = bitstream2.getID();
bitstreamService.delete(context, bitstream2); bitstreamService.delete(context, bitstream2);
assertTrue("Collection Admin unable to flag Bitstream as deleted", assertTrue("Collection Admin unable to flag Bitstream as deleted",
bitstream2.isDeleted()); bitstream2.isDeleted());
@@ -327,7 +319,6 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
// Test deletion of single Item as a Collection Admin // Test deletion of single Item as a Collection Admin
UUID itemId = item.getID(); UUID itemId = item.getID();
bundleId = bundle.getID(); bundleId = bundle.getID();
bitstreamId = bitstream.getID();
itemService.delete(context, item); itemService.delete(context, item);
assertThat("Collection Admin unable to delete sub-Item", assertThat("Collection Admin unable to delete sub-Item",
itemService.find(context, itemId), nullValue()); itemService.find(context, itemId), nullValue());

View File

@@ -16,7 +16,6 @@ import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractIntegrationTest; import org.dspace.AbstractIntegrationTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
@@ -37,11 +36,6 @@ import org.junit.Test;
* @author pvillega * @author pvillega
*/ */
public class ITMetadata extends AbstractIntegrationTest { public class ITMetadata extends AbstractIntegrationTest {
/**
* log4j category
*/
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ITMetadata.class);
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService(); protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();

View File

@@ -7,7 +7,6 @@
*/ */
package org.dspace.content; package org.dspace.content;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@@ -23,11 +22,6 @@ import org.junit.Test;
*/ */
public class InProgressSubmissionTest extends AbstractUnitTest { public class InProgressSubmissionTest extends AbstractUnitTest {
/**
* log4j category
*/
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(InProgressSubmissionTest.class);
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
* initialize resources required for the tests. * initialize resources required for the tests.

View File

@@ -11,6 +11,8 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -21,24 +23,22 @@ import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.InstallItemService; import org.dspace.content.service.InstallItemService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Unit Tests for class InstallItem * Unit Tests for class InstallItem
@@ -57,6 +57,12 @@ public class InstallItemTest extends AbstractUnitTest {
private Collection collection; private Collection collection;
private Community owningCommunity; private Community owningCommunity;
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* log4j category * log4j category
*/ */
@@ -78,6 +84,14 @@ public class InstallItemTest extends AbstractUnitTest {
this.owningCommunity = communityService.create(null, context); this.owningCommunity = communityService.create(null, context);
this.collection = collectionService.create(context, owningCommunity); this.collection = collectionService.create(context, owningCommunity);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded workspaceItemService and collectionService
// (To ensure it uses the spy instead of the real service)
ReflectionTestUtils.setField(workspaceItemService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(collectionService, "authorizeService", authorizeServiceSpy);
} catch (SQLException | AuthorizeException ex) { } catch (SQLException | AuthorizeException ex) {
log.error("SQL Error in init", ex); log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
@@ -140,30 +154,22 @@ public class InstallItemTest extends AbstractUnitTest {
/** /**
* Test of installItem method (with an invalid handle), of class InstallItem. * Test of installItem method (with an invalid handle), of class InstallItem.
*/ */
@Test @Test(expected = AuthorizeException.class)
public void testInstallItem_invalidHandle() throws Exception { public void testInstallItem_invalidHandle() throws Exception {
//Default to Full-Admin rights // Allow full Admin rights
new NonStrictExpectations(authorizeService.getClass()) {{ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
// Deny Community ADD perms
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD);
result = false;
// Allow full Admin perms
authorizeService.isAdmin((Context) any);
result = true;
authorizeService.isAdmin((Context) any, (EPerson) any);
result = true;
}};
String handle = "123456789/56789"; // create two items for tests
context.turnOffAuthorisationSystem();
WorkspaceItem is = workspaceItemService.create(context, collection, false); WorkspaceItem is = workspaceItemService.create(context, collection, false);
WorkspaceItem is2 = workspaceItemService.create(context, collection, false); WorkspaceItem is2 = workspaceItemService.create(context, collection, false);
context.restoreAuthSystemState();
//Test assigning the same Handle to two different items //Test assigning the same Handle to two different items
String handle = "123456789/56789";
installItemService.installItem(context, is, handle); installItemService.installItem(context, is, handle);
// Assigning the same handle again should throw a RuntimeException // Assigning the same handle again should throw a RuntimeException
thrown.expect(RuntimeException.class);
installItemService.installItem(context, is2, handle); installItemService.installItem(context, is2, handle);
fail("Exception expected"); fail("Exception expected");
} }

View File

@@ -132,8 +132,8 @@ public class ItemComparatorTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testCompare() throws SQLException { public void testCompare() throws SQLException {
int result = 0; int result;
ItemComparator ic = null; ItemComparator ic;
//one of the tiems has no value //one of the tiems has no value
ic = new ItemComparator("test", "one", Item.ANY, true); ic = new ItemComparator("test", "one", Item.ANY, true);
@@ -246,7 +246,7 @@ public class ItemComparatorTest extends AbstractUnitTest {
@SuppressWarnings( {"ObjectEqualsNull", "IncompatibleEquals"}) @SuppressWarnings( {"ObjectEqualsNull", "IncompatibleEquals"})
public void testEquals() { public void testEquals() {
ItemComparator ic = new ItemComparator("test", "one", Item.ANY, true); ItemComparator ic = new ItemComparator("test", "one", Item.ANY, true);
ItemComparator target = null; ItemComparator target;
assertFalse("testEquals 0", ic.equals(null)); assertFalse("testEquals 0", ic.equals(null));
assertFalse("testEquals 1", ic.equals("test one")); assertFalse("testEquals 1", ic.equals("test one"));

View File

@@ -15,6 +15,11 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -28,15 +33,14 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import mockit.NonStrictExpectations;
import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy; import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService; import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.MetadataFieldService; import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService; import org.dspace.content.service.MetadataSchemaService;
import org.dspace.core.Constants; import org.dspace.core.Constants;
@@ -46,6 +50,7 @@ import org.dspace.eperson.Group;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Unit Tests for class Item * Unit Tests for class Item
@@ -70,11 +75,15 @@ public class ItemTest extends AbstractDSpaceObjectTest {
.getBitstreamFormatService(); .getBitstreamFormatService();
private MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); private MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService();
private CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
private Collection collection; private Collection collection;
private Community owningCommunity; private Community owningCommunity;
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
@@ -92,14 +101,24 @@ public class ItemTest extends AbstractDSpaceObjectTest {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
this.owningCommunity = communityService.create(null, context); this.owningCommunity = communityService.create(null, context);
this.collection = collectionService.create(context, owningCommunity); this.collection = collectionService.create(context, owningCommunity);
WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false); WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, true);
this.it = installItemService.installItem(context, workspaceItem); this.it = installItemService.installItem(context, workspaceItem);
it.setSubmitter(context.getCurrentUser());
itemService.update(context, it);
this.dspaceObject = it; this.dspaceObject = it;
//we need to commit the changes so we don't block the table for testing
context.restoreAuthSystemState(); context.restoreAuthSystemState();
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded object services
// (To ensure these services use the spy instead of the real service)
ReflectionTestUtils.setField(collectionService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(itemService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(workspaceItemService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(bundleService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(bitstreamService, "authorizeService", authorizeServiceSpy);
// Also wire into current AuthorizeServiceFactory, as that is used for some checks (e.g. AuthorizeUtil)
ReflectionTestUtils.setField(AuthorizeServiceFactory.getInstance(), "authorizeService",
authorizeServiceSpy);
} catch (AuthorizeException ex) { } catch (AuthorizeException ex) {
log.error("Authorization Error in init", ex); log.error("Authorization Error in init", ex);
fail("Authorization Error in init: " + ex.getMessage()); fail("Authorization Error in init: " + ex.getMessage());
@@ -169,15 +188,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCreate() throws Exception { public void testCreate() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow Collection WRITE perms
// Allow Item ADD perms (needed to create an Item) doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADD);
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE);
result = null;
}};
Item created = createItem(); Item created = createItem();
assertThat("testCreate 0", created, notNullValue()); assertThat("testCreate 0", created, notNullValue());
assertThat("testCreate 1", created.getName(), nullValue()); assertThat("testCreate 1", created.getName(), nullValue());
@@ -292,6 +305,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
// Test 7: We should not find our item in this list // Test 7: We should not find our item in this list
assertFalse("List should not contain non-discoverable items", added); assertFalse("List should not contain non-discoverable items", added);
} }
/** /**
* Test of findInArchiveOrWithdrawnNonDiscoverableModifiedSince method, of class Item. * Test of findInArchiveOrWithdrawnNonDiscoverableModifiedSince method, of class Item.
*/ */
@@ -787,13 +801,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCreateBundleAuth() throws Exception { public void testCreateBundleAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item ADD perms // Allow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
Constants.ADD);
result = null;
}};
String name = "bundle"; String name = "bundle";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
@@ -808,16 +817,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = SQLException.class) @Test(expected = SQLException.class)
public void testCreateBundleNoName() throws Exception { public void testCreateBundleNoName() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ bundleService.create(context, it, "");
// Allow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
}};
String name = "";
Bundle created = bundleService.create(context, it, name);
fail("Exception expected"); fail("Exception expected");
} }
@@ -825,36 +825,18 @@ public class ItemTest extends AbstractDSpaceObjectTest {
* Test of createBundle method, of class Item. * Test of createBundle method, of class Item.
*/ */
@Test(expected = SQLException.class) @Test(expected = SQLException.class)
public void testCreateBundleNoName2() throws Exception { public void testCreateBundleNullName() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ bundleService.create(context, it, null);
// Allow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
}};
String name = null;
Bundle created = bundleService.create(context, it, name);
fail("Exception expected"); fail("Exception expected");
} }
/** /**
* Test of createBundle method, of class Item. * Test of createBundle method, of class Item.
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateBundleNoAuth() throws Exception { public void testCreateBundleNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = new AuthorizeException();
}};
String name = "bundle"; String name = "bundle";
Bundle created = bundleService.create(context, it, name); bundleService.create(context, it, name);
fail("Exception expected"); fail("Exception expected");
} }
@@ -863,17 +845,13 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testAddBundleAuth() throws Exception { public void testAddBundleAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item ADD perms // Allow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
Constants.ADD);
result = null;
}};
String name = "bundle"; String name = "bundle";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
itemService.addBundle(context, it, created);
assertThat("testAddBundleAuth 0", itemService.getBundles(it, name), notNullValue()); assertThat("testAddBundleAuth 0", itemService.getBundles(it, name), notNullValue());
assertTrue("testAddBundleAuth 1", itemService.getBundles(it, name).size() == 1); assertTrue("testAddBundleAuth 1", itemService.getBundles(it, name).size() == 1);
@@ -885,19 +863,10 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testAddBundleNoAuth() throws Exception { public void testAddBundleNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = new AuthorizeException();
}};
String name = "bundle"; String name = "bundle";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
itemService.addBundle(context, it, created);
it.addBundle(created);
fail("Exception expected"); fail("Exception expected");
} }
@@ -906,23 +875,18 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testRemoveBundleAuth() throws Exception { public void testRemoveBundleAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // First create a bundle for test
// Allow Item ADD and REMOVE perms context.turnOffAuthorisationSystem();
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.DELETE);
result = null;
}};
String name = "bundle"; String name = "bundle";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
itemService.addBundle(context, it, created); itemService.addBundle(context, it, created);
context.restoreAuthSystemState();
// Allow Item REMOVE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.REMOVE);
// Allow Bundle DELETE
doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.DELETE);
itemService.removeBundle(context, it, created); itemService.removeBundle(context, it, created);
assertThat("testRemoveBundleAuth 0", itemService.getBundles(it, name), notNullValue()); assertThat("testRemoveBundleAuth 0", itemService.getBundles(it, name), notNullValue());
@@ -934,21 +898,13 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testRemoveBundleNoAuth() throws Exception { public void testRemoveBundleNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // First create a bundle for test
// Allow Item ADD perms context.turnOffAuthorisationSystem();
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
// Disallow Item REMOVE perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = new AuthorizeException();
}};
String name = "bundle"; String name = "bundle";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
it.addBundle(created); itemService.addBundle(context, it, created);
context.restoreAuthSystemState();
itemService.removeBundle(context, it, created); itemService.removeBundle(context, it, created);
fail("Exception expected"); fail("Exception expected");
@@ -959,15 +915,15 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCreateSingleBitstream_InputStream_StringAuth() throws Exception { public void testCreateSingleBitstream_InputStream_StringAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item ADD perms // Allow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
Constants.ADD); // Allow Item WRITE perms
result = null; doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE, true);
authorizeService.authorizeAction((Context) any, (Item) any, // Allow Bundle ADD perms
Constants.WRITE, true); doNothing().when(authorizeServiceSpy).authorizeAction(any(Context.class), any(Bundle.class), eq(Constants.ADD));
result = null; // Allow Bitstream WRITE perms
}}; doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
String name = "new bundle"; String name = "new bundle";
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
@@ -980,17 +936,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateSingleBitstream_InputStream_StringNoAuth() throws Exception { public void testCreateSingleBitstream_InputStream_StringNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = new AuthorizeException();
}};
String name = "new bundle"; String name = "new bundle";
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, name); itemService.createSingleBitstream(context, new FileInputStream(f), it, name);
fail("Exception expected"); fail("Exception expected");
} }
@@ -999,16 +947,16 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCreateSingleBitstream_InputStreamAuth() throws Exception { public void testCreateSingleBitstream_InputStreamAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item ADD perms // Allow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
Constants.ADD); // Allow Item WRITE perms
result = null; doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE, true);
authorizeService.authorizeAction((Context) any, (Item) any, // Allow Bundle ADD perms
Constants.WRITE, true); doNothing().when(authorizeServiceSpy).authorizeAction(any(Context.class), any(Bundle.class), eq(Constants.ADD));
result = null; // Allow Bitstream WRITE perms
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
}};
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it); Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it);
@@ -1020,16 +968,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateSingleBitstream_InputStreamNoAuth() throws Exception { public void testCreateSingleBitstream_InputStreamNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item ADD perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = new AuthorizeException();
}};
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it); itemService.createSingleBitstream(context, new FileInputStream(f), it);
fail("Expected exception"); fail("Expected exception");
} }
@@ -1047,23 +987,17 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testRemoveDSpaceLicenseAuth() throws Exception { public void testRemoveDSpaceLicenseAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // First create a bundle for test
// Allow Item ADD and REMOVE perms context.turnOffAuthorisationSystem();
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.DELETE);
result = null;
}};
String name = "LICENSE"; String name = "LICENSE";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
// it.addBundle(created); context.restoreAuthSystemState();
// Allow Item REMOVE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.REMOVE);
// Allow Bundle DELETE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.DELETE);
itemService.removeDSpaceLicense(context, it); itemService.removeDSpaceLicense(context, it);
assertThat("testRemoveDSpaceLicenseAuth 0", itemService.getBundles(it, name), notNullValue()); assertThat("testRemoveDSpaceLicenseAuth 0", itemService.getBundles(it, name), notNullValue());
@@ -1075,20 +1009,12 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testRemoveDSpaceLicenseNoAuth() throws Exception { public void testRemoveDSpaceLicenseNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // First create a bundle for test
// Allow Item ADD perms context.turnOffAuthorisationSystem();
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
// Disallow Item REMOVE perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = new AuthorizeException();
}};
String name = "LICENSE"; String name = "LICENSE";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
context.restoreAuthSystemState();
itemService.removeDSpaceLicense(context, it); itemService.removeDSpaceLicense(context, it);
fail("Exception expected"); fail("Exception expected");
@@ -1099,23 +1025,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testRemoveLicensesAuth() throws Exception { public void testRemoveLicensesAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // First create test content
// Allow Item ADD and REMOVE perms context.turnOffAuthorisationSystem();
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
authorizeService.authorizeAction(context, (Bitstream) any,
Constants.DELETE);
result = null;
}};
String name = "LICENSE"; String name = "LICENSE";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
@@ -1125,7 +1036,18 @@ public class ItemTest extends AbstractDSpaceObjectTest {
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, bsname); Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, bsname);
bitstreamService.setFormat(context, result, bitstreamFormatService.findByShortDescription(context, bsname)); bitstreamService.setFormat(context, result, bitstreamFormatService.findByShortDescription(context, bsname));
bundleService.addBitstream(context, created, result); bundleService.addBitstream(context, created, result);
context.restoreAuthSystemState();
// Allow Item REMOVE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.REMOVE);
// Allow Item WRITE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE);
// Allow Bundle REMOVE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.REMOVE);
// Allow Bundle DELETE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.DELETE);
// Allow Bitstream DELETE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, result, Constants.DELETE);
itemService.removeLicenses(context, it); itemService.removeLicenses(context, it);
assertThat("testRemoveLicensesAuth 0", itemService.getBundles(it, name), notNullValue()); assertThat("testRemoveLicensesAuth 0", itemService.getBundles(it, name), notNullValue());
@@ -1137,17 +1059,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testRemoveLicensesNoAuth() throws Exception { public void testRemoveLicensesNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) { // First create test content
{ context.turnOffAuthorisationSystem();
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = new AuthorizeException();
}
};
String name = "LICENSE"; String name = "LICENSE";
Bundle created = bundleService.create(context, it, name); Bundle created = bundleService.create(context, it, name);
created.setName(context, name); created.setName(context, name);
@@ -1157,6 +1070,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, bsname); Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, bsname);
bitstreamService.setFormat(context, result, bitstreamFormatService.findByShortDescription(context, bsname)); bitstreamService.setFormat(context, result, bitstreamFormatService.findByShortDescription(context, bsname));
bundleService.addBitstream(context, created, result); bundleService.addBitstream(context, created, result);
context.restoreAuthSystemState();
itemService.removeLicenses(context, it); itemService.removeLicenses(context, it);
fail("Exception expected"); fail("Exception expected");
@@ -1167,15 +1081,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testUpdateAuth() throws Exception { public void testUpdateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item WRITE perms // Allow Item WRITE perms
authorizeService.authorizeAction((Context) any, (Item) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE);
Constants.WRITE);
result = null;
}};
//TOOD: how to test?
itemService.update(context, it); itemService.update(context, it);
} }
@@ -1184,32 +1092,14 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testUpdateAuth2() throws Exception { public void testUpdateAuth2() throws Exception {
// Test permission inheritence
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = new AuthorizeException();
// Allow parent Community WRITE and ADD perms
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.WRITE, true);
result = true;
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD, true);
result = true;
// Disallow parent Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, true);
result = new AuthorizeException();
}};
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
Collection c = createCollection(); Collection c = createCollection();
it.setOwningCollection(c); it.setOwningCollection(c);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
//TOOD: how to test? // Allow parent Collection WRITE perms (to test inheritance)
doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE, false);
itemService.update(context, it); itemService.update(context, it);
} }
@@ -1218,31 +1108,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception { public void testUpdateNoAuth() throws Exception {
// Test permission inheritence
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = new AuthorizeException();
// Disallow parent Community WRITE or ADD perms
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.WRITE, anyBoolean);
result = false;
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD, anyBoolean);
result = false;
// Disallow parent Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, anyBoolean);
result = new AuthorizeException();
}};
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
Collection c = createCollection(); Collection c = createCollection();
it.setOwningCollection(c); it.setOwningCollection(c);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
//TOOD: how to test?
itemService.update(context, it); itemService.update(context, it);
} }
@@ -1251,18 +1121,10 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testWithdrawAuth() throws Exception { public void testWithdrawAuth() throws Exception {
new NonStrictExpectations(AuthorizeUtil.class) {{ // Allow Item WRITE perms
// Allow Item withdraw permissions doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE);
AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any); // Allow Collection ADMIN perms
result = null; when(authorizeServiceSpy.authorizeActionBoolean(context, collection, Constants.ADMIN)).thenReturn(true);
}};
new NonStrictExpectations(authorizeService.getClass()) {{
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
}};
itemService.withdraw(context, it); itemService.withdraw(context, it);
assertTrue("testWithdrawAuth 0", it.isWithdrawn()); assertTrue("testWithdrawAuth 0", it.isWithdrawn());
@@ -1273,13 +1135,6 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testWithdrawNoAuth() throws Exception { public void testWithdrawNoAuth() throws Exception {
new NonStrictExpectations(AuthorizeUtil.class) {{
// Disallow Item withdraw permissions
AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any);
result = new AuthorizeException();
}};
itemService.withdraw(context, it); itemService.withdraw(context, it);
fail("Exception expected"); fail("Exception expected");
} }
@@ -1289,21 +1144,16 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testReinstateAuth() throws Exception { public void testReinstateAuth() throws Exception {
new NonStrictExpectations(AuthorizeUtil.class) {{ // Allow Item WRITE perms
AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any); doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE);
result = null; // Allow Collection ADD perms (needed to reinstate)
AuthorizeUtil.authorizeReinstateItem((Context) any, (Item) any); doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADD);
result = null;
}};
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item withdraw and reinstate permissions
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
}};
// initialize item as withdrawn
context.turnOffAuthorisationSystem();
itemService.withdraw(context, it); itemService.withdraw(context, it);
context.restoreAuthSystemState();
itemService.reinstate(context, it); itemService.reinstate(context, it);
assertFalse("testReinstate 0", it.isWithdrawn()); assertFalse("testReinstate 0", it.isWithdrawn());
} }
@@ -1313,21 +1163,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testReinstateNoAuth() throws Exception { public void testReinstateNoAuth() throws Exception {
new NonStrictExpectations(AuthorizeUtil.class) {{ // initialize item as withdrawn
// Allow Item withdraw permissions context.turnOffAuthorisationSystem();
AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any);
result = null;
// Disallow Item reinstate permissions
AuthorizeUtil.authorizeReinstateItem((Context) any, (Item) any);
result = new AuthorizeException();
}};
new NonStrictExpectations(authorizeService.getClass()) {{
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
}};
itemService.withdraw(context, it); itemService.withdraw(context, it);
context.restoreAuthSystemState();
itemService.reinstate(context, it); itemService.reinstate(context, it);
fail("Exception expected"); fail("Exception expected");
} }
@@ -1337,21 +1177,20 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testDeleteAuth() throws Exception { public void testDeleteAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // create a new item to delete
// Allow Item REMOVE perms context.turnOffAuthorisationSystem();
authorizeService.authorizeAction((Context) any, (Item) any, Item item = createItem();
Constants.REMOVE, true); context.restoreAuthSystemState();
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.DELETE, true);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
}};
UUID id = it.getID(); // Allow Item REMOVE perms
itemService.delete(context, it); doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.REMOVE, true);
// Allow Item DELETE perms
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.DELETE);
// Allow Item WRITE perms (required to first delete identifiers)
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
UUID id = item.getID();
itemService.delete(context, item);
Item found = itemService.find(context, id); Item found = itemService.find(context, id);
assertThat("testDeleteAuth 0", found, nullValue()); assertThat("testDeleteAuth 0", found, nullValue());
} }
@@ -1361,13 +1200,6 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testDeleteNoAuth() throws Exception { public void testDeleteNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item REMOVE perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = new AuthorizeException();
}};
itemService.delete(context, it); itemService.delete(context, it);
fail("Exception expected"); fail("Exception expected");
} }
@@ -1378,30 +1210,21 @@ public class ItemTest extends AbstractDSpaceObjectTest {
@Test @Test
@SuppressWarnings("ObjectEqualsNull") @SuppressWarnings("ObjectEqualsNull")
public void testEquals() throws SQLException, AuthorizeException, IOException, IllegalAccessException { public void testEquals() throws SQLException, AuthorizeException, IOException, IllegalAccessException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item ADD perms (needed to create an Item)
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.REMOVE);
result = null;
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.DELETE);
result = null;
}};
assertFalse("testEquals 0", it.equals(null)); assertFalse("testEquals 0", it.equals(null));
// create a new item to test against
context.turnOffAuthorisationSystem();
Item item = createItem(); Item item = createItem();
context.restoreAuthSystemState();
try { try {
assertFalse("testEquals 1", it.equals(item)); assertFalse("testEquals 1", it.equals(item));
assertTrue("testEquals 2", it.equals(it)); assertTrue("testEquals 2", it.equals(it));
} finally { } finally {
//delete item we created
context.turnOffAuthorisationSystem();
itemService.delete(context, item); itemService.delete(context, item);
context.restoreAuthSystemState();
} }
} }
@@ -1435,13 +1258,6 @@ public class ItemTest extends AbstractDSpaceObjectTest {
List<ResourcePolicy> newpolicies = new ArrayList<ResourcePolicy>(); List<ResourcePolicy> newpolicies = new ArrayList<ResourcePolicy>();
ResourcePolicy pol1 = resourcePolicyService.create(context); ResourcePolicy pol1 = resourcePolicyService.create(context);
newpolicies.add(pol1); newpolicies.add(pol1);
new NonStrictExpectations(authorizeService.getClass()) {
{
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
}
};
itemService.replaceAllItemPolicies(context, it, newpolicies); itemService.replaceAllItemPolicies(context, it, newpolicies);
List<ResourcePolicy> retrieved = authorizeService.getPolicies(context, it); List<ResourcePolicy> retrieved = authorizeService.getPolicies(context, it);
@@ -1544,13 +1360,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
new NonStrictExpectations(authorizeService.getClass()) { // Allow Item WRITE perms
{ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE, true);
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE, true);
result = null;
}
};
itemService.inheritCollectionDefaultPolicies(context, it, c); itemService.inheritCollectionDefaultPolicies(context, it, c);
@@ -1630,24 +1441,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCanEditBooleanAuth() throws Exception { public void testCanEditBooleanAuth() throws Exception {
// Test Inheritance of permissions
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item WRITE perms // Allow Item WRITE perms
authorizeService.authorizeActionBoolean((Context) any, (Item) any, when(authorizeServiceSpy.authorizeActionBoolean(context, it, Constants.WRITE)).thenReturn(true);
Constants.WRITE);
result = true;
// Allow parent Community WRITE and ADD perms
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.WRITE, true);
result = true;
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD, true);
result = true;
// Allow parent Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, true);
result = null;
}};
assertTrue("testCanEditBooleanAuth 0", itemService.canEdit(context, it)); assertTrue("testCanEditBooleanAuth 0", itemService.canEdit(context, it));
} }
@@ -1657,24 +1452,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCanEditBooleanAuth2() throws Exception { public void testCanEditBooleanAuth2() throws Exception {
// Test Inheritance of permissions // Allow parent Community WRITE perms (test inheritance from community)
new NonStrictExpectations(authorizeService.getClass()) {{ when(authorizeServiceSpy.authorizeActionBoolean(context, owningCommunity, Constants.WRITE, false))
// Disallow Item WRITE perms .thenReturn(true);
authorizeService.authorizeActionBoolean((Context) any, (Item) any,
Constants.WRITE);
result = false;
// Allow parent Community WRITE and ADD perms
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.WRITE, true);
result = true;
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD, true);
result = true;
// Allow parent Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, false);
result = null;
}};
assertTrue("testCanEditBooleanAuth2 0", itemService.canEdit(context, it)); assertTrue("testCanEditBooleanAuth2 0", itemService.canEdit(context, it));
} }
@@ -1684,107 +1464,24 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCanEditBooleanAuth3() throws Exception { public void testCanEditBooleanAuth3() throws Exception {
// Test Inheritance of permissions for owning collection
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms
authorizeService.authorizeActionBoolean((Context) any, (Item) any,
Constants.WRITE);
result = false;
// Allow parent Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, false);
result = null;
}};
// Create a new Collection and assign it as the owner // Create a new Collection and assign it as the owner
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
Collection c = createCollection(); Collection c = createCollection();
it.setOwningCollection(c); it.setOwningCollection(c);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
// Allow parent Collection WRITE perms (test inheritance from new collection)
doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE, false);
// Ensure person with WRITE perms on the Collection can edit item // Ensure person with WRITE perms on the Collection can edit item
assertTrue("testCanEditBooleanAuth3 0", itemService.canEdit(context, it)); assertTrue("testCanEditBooleanAuth3 0", itemService.canEdit(context, it));
} }
/**
* Test of canEdit method, of class Item.
*/
@Test
public void testCanEditBooleanAuth4() throws Exception {
// Test Inheritance of permissions for Community Admins
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms
authorizeService.authorizeActionBoolean((Context) any, (Item) any,
Constants.WRITE);
result = false;
// Allow parent Community WRITE and ADD perms
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.WRITE, true);
result = true;
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD, false);
result = true;
// Disallow parent Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, true);
result = new AuthorizeException();
}};
// Ensure person with WRITE perms on the Collection can edit item
assertTrue("testCanEditBooleanAuth4 0", itemService.canEdit(context, it));
}
/**
* Test of canEdit method, of class Item.
*/
@Test
public void testCanEditBooleanAuth5() throws Exception {
// Test Inheritance of permissions
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = new AuthorizeException();
// Allow Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, anyBoolean);
result = null;
}};
collectionService.createTemplateItem(context, collection);
collectionService.update(context, collection);
assertTrue("testCanEditBooleanNoAuth5 0", itemService.canEdit(context, collection.getTemplateItem()));
}
/** /**
* Test of canEdit method, of class Item. * Test of canEdit method, of class Item.
*/ */
@Test @Test
public void testCanEditBooleanNoAuth() throws Exception { public void testCanEditBooleanNoAuth() throws Exception {
// Test Inheritance of permissions
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms
authorizeService.authorizeActionBoolean((Context) any, (Item) any,
Constants.WRITE);
result = false;
// Disallow parent Community WRITE and ADD perms
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.WRITE, anyBoolean);
result = false;
authorizeService.authorizeActionBoolean((Context) any, (Community) any,
Constants.ADD, anyBoolean);
result = false;
// Disallow parent Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, anyBoolean);
result = new AuthorizeException();
}};
context.turnOffAuthorisationSystem();
Collection c = createCollection();
it.setOwningCollection(c);
context.restoreAuthSystemState();
assertFalse("testCanEditBooleanNoAuth 0", itemService.canEdit(context, it)); assertFalse("testCanEditBooleanNoAuth 0", itemService.canEdit(context, it));
} }
@@ -1793,17 +1490,16 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/ */
@Test @Test
public void testCanEditBooleanNoAuth2() throws Exception { public void testCanEditBooleanNoAuth2() throws Exception {
// Test that a new Item cannot be edited by default
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
WorkspaceItem wi = workspaceItemService.create(context, collection, true); WorkspaceItem wi = workspaceItemService.create(context, collection, true);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
// Test Inheritance of permissions Item item = wi.getItem();
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms // Disallow Item WRITE perms
authorizeService.authorizeAction((Context) any, (Item) any, when(authorizeServiceSpy.authorizeActionBoolean(context, item, Constants.WRITE)).thenReturn(false);
Constants.WRITE, anyBoolean);
result = new AuthorizeException(); assertFalse("testCanEditBooleanNoAuth2 0", itemService.canEdit(context, item));
}};
assertFalse("testCanEditBooleanNoAuth2 0", itemService.canEdit(context, wi.getItem()));
} }
/** /**
@@ -1880,15 +1576,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
assertThat("testFindByMetadataField 0", result, notNullValue()); assertThat("testFindByMetadataField 0", result, notNullValue());
assertFalse("testFindByMetadataField 1", result.hasNext()); assertFalse("testFindByMetadataField 1", result.hasNext());
// add new metadata to item
context.turnOffAuthorisationSystem();
itemService.addMetadata(context, it, schema, element, qualifier, Item.ANY, value); itemService.addMetadata(context, it, schema, element, qualifier, Item.ANY, value);
new NonStrictExpectations(authorizeService.getClass()) {
{
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
}
};
itemService.update(context, it); itemService.update(context, it);
context.restoreAuthSystemState();
result = itemService.findByMetadataField(context, schema, element, qualifier, value); result = itemService.findByMetadataField(context, schema, element, qualifier, value);
assertThat("testFindByMetadataField 3", result, notNullValue()); assertThat("testFindByMetadataField 3", result, notNullValue());
@@ -1929,7 +1621,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
assertThat("testGetParentObject 1", itemService.getParentObject(context, it), notNullValue()); assertThat("testGetParentObject 1", itemService.getParentObject(context, it), notNullValue());
assertThat("testGetParentObject 2", (Collection) itemService.getParentObject(context, it), equalTo(parent)); assertThat("testGetParentObject 2", (Collection) itemService.getParentObject(context, it), equalTo(parent));
} catch (AuthorizeException ex) { } catch (AuthorizeException ex) {
fail("Authorize exception catched"); throw new AssertionError("Authorize Exception occurred", ex);
} }
} }
@@ -1949,16 +1641,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
assertThat("testFindByAuthorityValue 0", result, notNullValue()); assertThat("testFindByAuthorityValue 0", result, notNullValue());
assertFalse("testFindByAuthorityValue 1", result.hasNext()); assertFalse("testFindByAuthorityValue 1", result.hasNext());
// add new metadata (with authority) to item
context.turnOffAuthorisationSystem();
itemService.addMetadata(context, it, schema, element, qualifier, Item.ANY, value, authority, confidence); itemService.addMetadata(context, it, schema, element, qualifier, Item.ANY, value, authority, confidence);
//Ensure that the current user can update the item
new NonStrictExpectations(authorizeService.getClass()) {
{
authorizeService.authorizeAction((Context) any, (Item) any,
Constants.WRITE);
result = null;
}
};
itemService.update(context, it); itemService.update(context, it);
context.restoreAuthSystemState();
result = itemService.findByAuthorityValue(context, schema, element, qualifier, authority); result = itemService.findByAuthorityValue(context, schema, element, qualifier, authority);
assertThat("testFindByAuthorityValue 3", result, notNullValue()); assertThat("testFindByAuthorityValue 3", result, notNullValue());

View File

@@ -104,11 +104,11 @@ public class LicenseUtilsTest extends AbstractUnitTest {
@Test @Test
public void testGetLicenseText_5args() throws SQLException, AuthorizeException, IOException { public void testGetLicenseText_5args() throws SQLException, AuthorizeException, IOException {
//parameters for the test //parameters for the test
Locale locale = null; Locale locale;
Collection collection = null; Collection collection;
Item item = null; Item item;
EPerson person = null; EPerson person;
Map<String, Object> additionalInfo = null; Map<String, Object> additionalInfo;
// We don't test attribute 4 as this is the date, and the date often differs between when the test // We don't test attribute 4 as this is the date, and the date often differs between when the test
// is executed, and when the LicenceUtils code gets the current date/time which causes the test to fail // is executed, and when the LicenceUtils code gets the current date/time which causes the test to fail
@@ -195,10 +195,10 @@ public class LicenseUtilsTest extends AbstractUnitTest {
@Test @Test
public void testGetLicenseText_4args() throws SQLException, AuthorizeException, IOException { public void testGetLicenseText_4args() throws SQLException, AuthorizeException, IOException {
//parameters for the test //parameters for the test
Locale locale = null; Locale locale;
Collection collection = null; Collection collection;
Item item = null; Item item;
EPerson person = null; EPerson person;
String template = "Template license: %1$s %2$s %3$s %5$s %6$s"; String template = "Template license: %1$s %2$s %3$s %5$s %6$s";
String templateResult = "Template license: first name last name testgetlicensetext_4args@email.com "; String templateResult = "Template license: first name last name testgetlicensetext_4args@email.com ";

View File

@@ -13,20 +13,23 @@ import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.MetadataFieldService; import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService; import org.dspace.content.service.MetadataSchemaService;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Unit Tests for class MetadataFieldTest * Unit Tests for class MetadataFieldTest
@@ -66,6 +69,12 @@ public class MetadataFieldTest extends AbstractUnitTest {
.getMetadataSchemaService(); .getMetadataSchemaService();
protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService(); protected MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService();
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
* initialize resources required for the tests. * initialize resources required for the tests.
@@ -90,6 +99,14 @@ public class MetadataFieldTest extends AbstractUnitTest {
} }
this.mf.setScopeNote(scopeNote); this.mf.setScopeNote(scopeNote);
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded object services
// (To ensure these services use the spy instead of the real service)
ReflectionTestUtils.setField(metadataFieldService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(metadataSchemaService, "authorizeService", authorizeServiceSpy);
} catch (SQLException ex) { } catch (SQLException ex) {
log.error("SQL Error in init", ex); log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
@@ -173,11 +190,9 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testSetSchema() throws NonUniqueMetadataException, SQLException, AuthorizeException { public void testSetSchema() throws NonUniqueMetadataException, SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
MetadataSchema newSchema = metadataSchemaService.create(context, "testSetSchema", "testSetSchemaNS"); MetadataSchema newSchema = metadataSchemaService.create(context, "testSetSchema", "testSetSchemaNS");
mf.setMetadataSchema(newSchema); mf.setMetadataSchema(newSchema);
assertThat("testSetSchemaID 0", mf.getMetadataSchema(), equalTo(newSchema)); assertThat("testSetSchemaID 0", mf.getMetadataSchema(), equalTo(newSchema));
@@ -206,11 +221,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testCreateAuth() throws Exception { public void testCreateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String elem = "elem1"; String elem = "elem1";
String qual = "qual1"; String qual = "qual1";
@@ -225,12 +237,6 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateNoAuth() throws Exception { public void testCreateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String elem = "elem1"; String elem = "elem1";
String qual = "qual1"; String qual = "qual1";
metadataFieldService.create(context, dcSchema, elem, qual, null); metadataFieldService.create(context, dcSchema, elem, qual, null);
@@ -242,11 +248,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test(expected = NonUniqueMetadataException.class) @Test(expected = NonUniqueMetadataException.class)
public void testCreateRepeated() throws Exception { public void testCreateRepeated() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String elem = element; String elem = element;
String qual = qualifier; String qual = qualifier;
@@ -310,11 +313,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testUpdateAuth() throws Exception { public void testUpdateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String elem = "elem2"; String elem = "elem2";
String qual = "qual2"; String qual = "qual2";
@@ -330,12 +330,6 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception { public void testUpdateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String elem = "elem2"; String elem = "elem2";
String qual = "qual2"; String qual = "qual2";
MetadataField m = metadataFieldService.create(context, dcSchema, elem, qual, null); MetadataField m = metadataFieldService.create(context, dcSchema, elem, qual, null);
@@ -348,11 +342,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test(expected = NonUniqueMetadataException.class) @Test(expected = NonUniqueMetadataException.class)
public void testUpdateRepeated() throws Exception { public void testUpdateRepeated() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String elem = element; String elem = element;
String qual = qualifier; String qual = qualifier;
@@ -369,11 +360,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testDeleteAuth() throws Exception { public void testDeleteAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String elem = "elem3"; String elem = "elem3";
String qual = "qual3"; String qual = "qual3";
@@ -390,12 +378,6 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testDeleteNoAuth() throws Exception { public void testDeleteNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String elem = "elem3"; String elem = "elem3";
String qual = "qual3"; String qual = "qual3";
MetadataField m = metadataFieldService.create(context, dcSchema, elem, qual, null); MetadataField m = metadataFieldService.create(context, dcSchema, elem, qual, null);

View File

@@ -14,18 +14,21 @@ import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.MetadataSchemaService; import org.dspace.content.service.MetadataSchemaService;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Unit Tests for class MetadataSchema * Unit Tests for class MetadataSchema
@@ -47,6 +50,12 @@ public class MetadataSchemaTest extends AbstractUnitTest {
protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance() protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance()
.getMetadataSchemaService(); .getMetadataSchemaService();
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
* initialize resources required for the tests. * initialize resources required for the tests.
@@ -60,6 +69,13 @@ public class MetadataSchemaTest extends AbstractUnitTest {
super.init(); super.init();
try { try {
this.ms = metadataSchemaService.find(context, MetadataSchemaEnum.DC.getName()); this.ms = metadataSchemaService.find(context, MetadataSchemaEnum.DC.getName());
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded object services
// (To ensure these services use the spy instead of the real service)
ReflectionTestUtils.setField(metadataSchemaService, "authorizeService", authorizeServiceSpy);
} catch (SQLException ex) { } catch (SQLException ex) {
log.error("SQL Error in init", ex); log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
@@ -130,11 +146,8 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testCreateAuth() throws Exception { public void testCreateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String namespace = "namespace"; String namespace = "namespace";
String name = "name"; String name = "name";
@@ -149,12 +162,6 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateNoAuth() throws Exception { public void testCreateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String namespace = "namespace"; String namespace = "namespace";
String name = "name"; String name = "name";
metadataSchemaService.create(context, name, namespace); metadataSchemaService.create(context, name, namespace);
@@ -166,11 +173,8 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test(expected = NonUniqueMetadataException.class) @Test(expected = NonUniqueMetadataException.class)
public void testCreateRepeated() throws Exception { public void testCreateRepeated() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String namespace = ms.getNamespace(); String namespace = ms.getNamespace();
String name = ms.getName(); String name = ms.getName();
@@ -194,11 +198,8 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testUpdateAuth() throws Exception { public void testUpdateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String namespace = "namespace2"; String namespace = "namespace2";
String name = "name2"; String name = "name2";
@@ -215,12 +216,6 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception { public void testUpdateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
metadataSchemaService.update(context, ms); metadataSchemaService.update(context, ms);
fail("Exception expected"); fail("Exception expected");
} }
@@ -230,11 +225,8 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test(expected = NonUniqueMetadataException.class) @Test(expected = NonUniqueMetadataException.class)
public void testUpdateRepeated() throws Exception { public void testUpdateRepeated() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String namespace = ms.getNamespace(); String namespace = ms.getNamespace();
String name = ms.getName(); String name = ms.getName();
@@ -251,11 +243,8 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testDeleteAuth() throws Exception { public void testDeleteAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow full admin permissions when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin(context);
result = true;
}};
String namespace = "namespace3"; String namespace = "namespace3";
String name = "name3"; String name = "name3";
@@ -272,12 +261,6 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testDeleteNoAuth() throws Exception { public void testDeleteNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String namespace = "namespace3"; String namespace = "namespace3";
String name = "name3"; String name = "name3";
MetadataSchema m = metadataSchemaService.create(context, name, namespace); MetadataSchema m = metadataSchemaService.create(context, name, namespace);

View File

@@ -9,8 +9,6 @@ package org.dspace.content;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test; import org.junit.Test;
/** /**
@@ -21,12 +19,6 @@ import org.junit.Test;
*/ */
public class NonUniqueMetadataExceptionTest { public class NonUniqueMetadataExceptionTest {
/**
* log4j category
*/
private static final Logger log = LogManager
.getLogger(NonUniqueMetadataExceptionTest.class);
/** /**
* Dummy test to avoid initialization errors * Dummy test to avoid initialization errors
*/ */

View File

@@ -463,7 +463,7 @@ public class RelationshipMetadataServiceTest extends AbstractUnitTest {
WorkspaceItem is = workspaceItemService.create(context, col, false); WorkspaceItem is = workspaceItemService.create(context, col, false);
Item secondItem = installItemService.installItem(context, is); Item secondItem = installItemService.installItem(context, is);
itemService.addMetadata(context, secondItem, "relationship", "type", null, null, "Publication"); itemService.addMetadata(context, secondItem, "relationship", "type", null, null, "Publication");
Relationship secondRelationship = relationshipService.create(context, secondItem, rightItem, relationshipService.create(context, secondItem, rightItem,
isAuthorOfPublicationRelationshipType, 0, 0); isAuthorOfPublicationRelationshipType, 0, 0);
context.restoreAuthSystemState(); context.restoreAuthSystemState();
@@ -489,7 +489,7 @@ public class RelationshipMetadataServiceTest extends AbstractUnitTest {
itemService.addMetadata(context, secondAuthor, "relationship", "type", null, null, "Author"); itemService.addMetadata(context, secondAuthor, "relationship", "type", null, null, "Author");
itemService.addMetadata(context, secondAuthor, "person", "familyName", null, null, "familyName"); itemService.addMetadata(context, secondAuthor, "person", "familyName", null, null, "familyName");
itemService.addMetadata(context, secondAuthor, "person", "givenName", null, null, "firstName"); itemService.addMetadata(context, secondAuthor, "person", "givenName", null, null, "firstName");
Relationship secondRelationship = relationshipService.create(context, leftItem, secondAuthor, relationshipService.create(context, leftItem, secondAuthor,
isAuthorOfPublicationRelationshipType, 0, 0); isAuthorOfPublicationRelationshipType, 0, 0);
context.restoreAuthSystemState(); context.restoreAuthSystemState();

View File

@@ -8,12 +8,11 @@
package org.dspace.content; package org.dspace.content;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.dspace.authorize.service.AuthorizeService; import org.dspace.authorize.service.AuthorizeService;
@@ -28,7 +27,7 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class RelationshipServiceImplTest { public class RelationshipServiceImplTest {
@@ -137,7 +136,7 @@ public class RelationshipServiceImplTest {
@Test @Test
public void testFindByItemAndRelationshipType() throws Exception { public void testFindByItemAndRelationshipType() throws Exception {
// Declare objects utilized in unit test // Declare objects utilized in unit test
List<Relationship> relList = new LinkedList<>(); List<Relationship> relList = new ArrayList<>();
Item item = mock(Item.class); Item item = mock(Item.class);
RelationshipType testRel = new RelationshipType(); RelationshipType testRel = new RelationshipType();
@@ -152,7 +151,7 @@ public class RelationshipServiceImplTest {
@Test @Test
public void testFindByRelationshipType() throws Exception { public void testFindByRelationshipType() throws Exception {
// Declare objects utilized in unit test // Declare objects utilized in unit test
List<Relationship> relList = new LinkedList<>(); List<Relationship> relList = new ArrayList<>();
RelationshipType testRel = new RelationshipType(); RelationshipType testRel = new RelationshipType();
// The Relationship(s) reported should match our our relList // The Relationship(s) reported should match our our relList
@@ -231,8 +230,6 @@ public class RelationshipServiceImplTest {
public void testDelete() throws Exception { public void testDelete() throws Exception {
// Declare objects utilized in unit test // Declare objects utilized in unit test
MetadataValue metVal = mock(MetadataValue.class);
List<MetadataValue> metsList = new ArrayList<>();
List<Relationship> leftTypelist = new ArrayList<>(); List<Relationship> leftTypelist = new ArrayList<>();
List<Relationship> rightTypelist = new ArrayList<>(); List<Relationship> rightTypelist = new ArrayList<>();
Item leftItem = mock(Item.class); Item leftItem = mock(Item.class);
@@ -246,7 +243,6 @@ public class RelationshipServiceImplTest {
testRel.setRightwardType("Entitylabel"); testRel.setRightwardType("Entitylabel");
testRel.setLeftMinCardinality(0); testRel.setLeftMinCardinality(0);
testRel.setRightMinCardinality(0); testRel.setRightMinCardinality(0);
metsList.add(metVal);
relationship = getRelationship(leftItem, rightItem, testRel, 0,0); relationship = getRelationship(leftItem, rightItem, testRel, 0,0);
leftTypelist.add(relationship); leftTypelist.add(relationship);
rightTypelist.add(relationship); rightTypelist.add(relationship);

View File

@@ -10,15 +10,14 @@ package org.dspace.content;
import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import org.apache.logging.log4j.Logger;
import org.dspace.content.dao.RelationshipTypeDAO; import org.dspace.content.dao.RelationshipTypeDAO;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.junit.Before; import org.junit.Before;
@@ -26,13 +25,10 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class RelationshipTypeTest { public class RelationshipTypeTest {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(RelationshipTypeTest.class);
@InjectMocks @InjectMocks
private RelationshipTypeServiceImpl relationshipTypeService; private RelationshipTypeServiceImpl relationshipTypeService;
@@ -102,7 +98,7 @@ public class RelationshipTypeTest {
@Test @Test
public void testRelationshipTypeFindAll() throws Exception { public void testRelationshipTypeFindAll() throws Exception {
// Declare objects utilized for this test // Declare objects utilized for this test
List<RelationshipType> mockedList = new LinkedList<>(); List<RelationshipType> mockedList = new ArrayList<>();
mockedList.add(firstRelationshipType); mockedList.add(firstRelationshipType);
mockedList.add(secondRelationshipType); mockedList.add(secondRelationshipType);
@@ -120,7 +116,7 @@ public class RelationshipTypeTest {
@Test @Test
public void testRelationshipTypeFindByLeftOrRightwardType() throws Exception { public void testRelationshipTypeFindByLeftOrRightwardType() throws Exception {
// Declare objects utilized for this test // Declare objects utilized for this test
List<RelationshipType> mockedList = new LinkedList<>(); List<RelationshipType> mockedList = new ArrayList<>();
mockedList.add(firstRelationshipType); mockedList.add(firstRelationshipType);
// Mock DAO to return our mockedList // Mock DAO to return our mockedList
@@ -138,7 +134,7 @@ public class RelationshipTypeTest {
@Test @Test
public void testRelationshipTypefindByEntityType() throws Exception { public void testRelationshipTypefindByEntityType() throws Exception {
// Declare objects utilized for this test // Declare objects utilized for this test
List<RelationshipType> mockedList = new LinkedList<>(); List<RelationshipType> mockedList = new ArrayList<>();
mockedList.add(firstRelationshipType); mockedList.add(firstRelationshipType);
// Mock DAO to return our mockedList // Mock DAO to return our mockedList

View File

@@ -58,7 +58,7 @@ public class SiteTest extends AbstractUnitTest {
try { try {
//we have to create a new community in the database //we have to create a new community in the database
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
this.s = (Site) siteService.findSite(context); this.s = siteService.findSite(context);
//we need to commit the changes so we don't block the table for testing //we need to commit the changes so we don't block the table for testing
context.restoreAuthSystemState(); context.restoreAuthSystemState();
} catch (SQLException ex) { } catch (SQLException ex) {
@@ -120,8 +120,7 @@ public class SiteTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testSiteFind() throws Exception { public void testSiteFind() throws Exception {
int id = 0; Site found = siteService.findSite(context);
Site found = (Site) siteService.findSite(context);
assertThat("testSiteFind 0", found, notNullValue()); assertThat("testSiteFind 0", found, notNullValue());
assertThat("testSiteFind 1", found, equalTo(s)); assertThat("testSiteFind 1", found, equalTo(s));
} }
@@ -141,7 +140,7 @@ public class SiteTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testGetURL() { public void testGetURL() {
assertThat("testGetURL 0", s.getURL(), equalTo(ConfigurationManager.getProperty("dspace.url"))); assertThat("testGetURL 0", s.getURL(), equalTo(ConfigurationManager.getProperty("dspace.ui.url")));
} }
} }

View File

@@ -7,6 +7,7 @@
*/ */
package org.dspace.content; package org.dspace.content;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@@ -48,11 +49,6 @@ public class ThumbnailTest extends AbstractUnitTest {
*/ */
private Bitstream orig; private Bitstream orig;
/**
* Thumbnail instance for the tests, original copy
*/
private Thumbnail t;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
* initialize resources required for the tests. * initialize resources required for the tests.
@@ -69,7 +65,9 @@ public class ThumbnailTest extends AbstractUnitTest {
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
thumb = bitstreamService.create(context, new FileInputStream(f)); thumb = bitstreamService.create(context, new FileInputStream(f));
orig = bitstreamService.create(context, new FileInputStream(f)); orig = bitstreamService.create(context, new FileInputStream(f));
t = new Thumbnail(thumb, orig); Thumbnail t = new Thumbnail(thumb, orig);
assertEquals(orig, t.getOriginal());
assertEquals(thumb, t.getThumb());
} catch (IOException ex) { } catch (IOException ex) {
log.error("IO Error in init", ex); log.error("IO Error in init", ex);
fail("SQL Error in init: " + ex.getMessage()); fail("SQL Error in init: " + ex.getMessage());
@@ -89,9 +87,16 @@ public class ThumbnailTest extends AbstractUnitTest {
@After @After
@Override @Override
public void destroy() { public void destroy() {
try {
context.turnOffAuthorisationSystem();
bitstreamService.delete(context, thumb);
bitstreamService.delete(context, orig);
context.restoreAuthSystemState();
thumb = null; thumb = null;
orig = null; orig = null;
t = null; } catch (Exception e) {
throw new AssertionError("Error in destroy()", e);
}
super.destroy(); super.destroy();
} }

View File

@@ -25,7 +25,6 @@ import org.dspace.content.service.CommunityService;
import org.dspace.content.service.InstallItemService; import org.dspace.content.service.InstallItemService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.versioning.Version; import org.dspace.versioning.Version;
@@ -49,7 +48,6 @@ public class VersioningTest extends AbstractUnitTest {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(VersioningTest.class); private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(VersioningTest.class);
private String originalHandle;
private Item originalItem; private Item originalItem;
private Item versionedItem; private Item versionedItem;
private String summary = "Unit test version"; private String summary = "Unit test version";
@@ -65,7 +63,7 @@ public class VersioningTest extends AbstractUnitTest {
//A regex that can be used to see if a handle contains the format of handle created by the org.dspace.identifier //A regex that can be used to see if a handle contains the format of handle created by the org.dspace.identifier
// .VersionedHandleIdentifierProvider* // .VersionedHandleIdentifierProvider*
protected String versionedHandleRegex = ConfigurationManager.getProperty("handle.prefix") + "\\/[0-9]*\\.[0-9]"; //protected String versionedHandleRegex = ConfigurationManager.getProperty("handle.prefix") + "\\/[0-9]*\\.[0-9]";
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
@@ -86,7 +84,6 @@ public class VersioningTest extends AbstractUnitTest {
WorkspaceItem is = workspaceItemService.create(context, col, false); WorkspaceItem is = workspaceItemService.create(context, col, false);
originalItem = installItemService.installItem(context, is); originalItem = installItemService.installItem(context, is);
originalHandle = originalItem.getHandle();
Version version = versionService.createNewVersion(context, originalItem, summary); Version version = versionService.createNewVersion(context, originalItem, summary);
WorkspaceItem wsi = workspaceItemService.findByItem(context, version.getItem()); WorkspaceItem wsi = workspaceItemService.findByItem(context, version.getItem());

View File

@@ -14,29 +14,32 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService; import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Unit Tests for class WorkspaceItem * Unit Tests for class WorkspaceItem
@@ -63,6 +66,12 @@ public class WorkspaceItemTest extends AbstractUnitTest {
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService(); protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/** /**
* This method will be run before every test as per @Before. It will * This method will be run before every test as per @Before. It will
* initialize resources required for the tests. * initialize resources required for the tests.
@@ -75,13 +84,22 @@ public class WorkspaceItemTest extends AbstractUnitTest {
public void init() { public void init() {
super.init(); super.init();
try { try {
//we have to create a new community in the database //we have to create a new community/collection/workspaceitem in the database
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
this.owningCommunity = communityService.create(null, context); this.owningCommunity = communityService.create(null, context);
this.collection = collectionService.create(context, owningCommunity); this.collection = collectionService.create(context, owningCommunity);
this.wi = workspaceItemService.create(context, collection, true); this.wi = workspaceItemService.create(context, collection, true);
//we need to commit the changes so we don't block the table for testing //we need to commit the changes so we don't block the table for testing
context.restoreAuthSystemState(); context.restoreAuthSystemState();
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded object services
// (To ensure these services use the spy instead of the real service)
ReflectionTestUtils.setField(workspaceItemService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(collectionService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(communityService, "authorizeService", authorizeServiceSpy);
} catch (AuthorizeException ex) { } catch (AuthorizeException ex) {
log.error("Authorization Error in init", ex); log.error("Authorization Error in init", ex);
fail("Authorization Error in init: " + ex.getMessage()); fail("Authorization Error in init: " + ex.getMessage());
@@ -139,15 +157,11 @@ public class WorkspaceItemTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testCreateAuth() throws Exception { public void testCreateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Collection ADD perms // Allow Collection ADD perms
authorizeService.authorizeAction((Context) any, (Collection) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADD);
Constants.ADD);
result = null;
}};
boolean template = false; boolean template;
WorkspaceItem created = null; WorkspaceItem created;
template = false; template = false;
created = workspaceItemService.create(context, collection, template); created = workspaceItemService.create(context, collection, template);
@@ -167,18 +181,7 @@ public class WorkspaceItemTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testCreateNoAuth() throws Exception { public void testCreateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ workspaceItemService.create(context, collection, false);
// Disallow Collection ADD perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.ADD);
result = new AuthorizeException();
}};
boolean template = false;
WorkspaceItem created = null;
template = false;
created = workspaceItemService.create(context, collection, template);
fail("Exception expected"); fail("Exception expected");
} }
@@ -281,18 +284,13 @@ public class WorkspaceItemTest extends AbstractUnitTest {
@Test @Test
public void testUpdateAuth() throws Exception { public void testUpdateAuth() throws Exception {
// no need to mockup the authorization as we are the same user that have // no need to mockup the authorization as we are the same user that have
// created the wi // created the workspaceitem (who has full perms by default)
boolean pBefore = wi.isPublishedBefore(); boolean pBefore = wi.isPublishedBefore();
wi.setPublishedBefore(!pBefore); wi.setPublishedBefore(!pBefore);
workspaceItemService.update(context, wi); workspaceItemService.update(context, wi);
context.commit();
// force to read the data from the database // Reload our WorkspaceItem
context.uncacheEntity(wi);
// read all our test attributes objects from the fresh session
// to avoid duplicate object in session issue
wi = workspaceItemService.find(context, wi.getID()); wi = workspaceItemService.find(context, wi.getID());
collection = wi.getCollection();
owningCommunity = collection.getCommunities().get(0);
assertTrue("testUpdate", pBefore != wi.isPublishedBefore()); assertTrue("testUpdate", pBefore != wi.isPublishedBefore());
} }
@@ -301,18 +299,29 @@ public class WorkspaceItemTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception { public void testUpdateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{ // Create a new Eperson to be the current user
// Remove Item WRITE perms context.turnOffAuthorisationSystem();
authorizeService.authorizeActionBoolean((Context) any, (Item) any, EPerson eperson = ePersonService.create(context);
Constants.WRITE); eperson.setEmail("jane@smith.org");
result = false; eperson.setFirstName(context, "Jane");
authorizeService.authorizeAction((Context) any, (Item) any, eperson.setLastName(context, "Smith");
Constants.WRITE); ePersonService.update(context, eperson);
result = new AuthorizeException();
}}; // Update our session to be logged in as new users
EPerson currentUser = context.getCurrentUser();
context.setCurrentUser(eperson);
context.restoreAuthSystemState();
// Try and update the workspace item. A different EPerson should have no rights
try {
boolean pBefore = wi.isPublishedBefore(); boolean pBefore = wi.isPublishedBefore();
wi.setPublishedBefore(!pBefore); wi.setPublishedBefore(!pBefore);
workspaceItemService.update(context, wi); workspaceItemService.update(context, wi);
} finally {
// Restore the current user
context.setCurrentUser(currentUser);
}
fail("Exception expected"); fail("Exception expected");
} }
@@ -351,12 +360,8 @@ public class WorkspaceItemTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testDeleteWrapperAuth() throws Exception { public void testDeleteWrapperAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Item WRITE perms // Allow Item WRITE perms
authorizeService.authorizeAction((Context) any, (Item) any, doNothing().when(authorizeServiceSpy).authorizeAction(context, wi.getItem(), Constants.WRITE);
Constants.WRITE);
result = null;
}};
UUID itemid = wi.getItem().getID(); UUID itemid = wi.getItem().getID();
int id = wi.getID(); int id = wi.getID();
@@ -372,13 +377,9 @@ public class WorkspaceItemTest extends AbstractUnitTest {
*/ */
@Test(expected = AuthorizeException.class) @Test(expected = AuthorizeException.class)
public void testDeleteWrapperNoAuth() throws Exception { public void testDeleteWrapperNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Item WRITE perms // Disallow Item WRITE perms
authorizeService.authorizeAction((Context) any, (Item) any, doThrow(new AuthorizeException()).when(authorizeServiceSpy)
Constants.WRITE); .authorizeAction(context, wi.getItem(), Constants.WRITE);
result = new AuthorizeException();
}};
workspaceItemService.deleteWrapper(context, wi); workspaceItemService.deleteWrapper(context, wi);
fail("Exception expected"); fail("Exception expected");
} }

View File

@@ -14,7 +14,7 @@ import org.dspace.content.DSpaceObject;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class NameAscendingComparatorTest { public class NameAscendingComparatorTest {

View File

@@ -22,9 +22,9 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import mockit.NonStrictExpectations; import com.google.common.base.Splitter;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractIntegrationTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy; import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.factory.AuthorizeServiceFactory; import org.dspace.authorize.factory.AuthorizeServiceFactory;
@@ -75,7 +75,7 @@ import org.junit.rules.TemporaryFolder;
* *
* @author Tim Donohue * @author Tim Donohue
*/ */
public class ITDSpaceAIP extends AbstractUnitTest { public class ITDSpaceAIP extends AbstractIntegrationTest {
/** /**
* log4j category * log4j category
*/ */
@@ -295,10 +295,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
// Override default value of configured temp directory to point at our // Override default value of configured temp directory to point at our
// JUnit TemporaryFolder. This ensures Crosswalk classes like RoleCrosswalk // JUnit TemporaryFolder. This ensures Crosswalk classes like RoleCrosswalk
// store their temp files in a place where JUnit can clean them up automatically. // store their temp files in a place where JUnit can clean them up automatically.
new NonStrictExpectations(configService.getClass()) {{ configService.setProperty("upload.temp.dir", uploadTempFolder.getRoot().getAbsolutePath());
configService.getProperty("upload.temp.dir");
result = uploadTempFolder.getRoot().getAbsolutePath();
}};
try { try {
context = new Context(); context = new Context();
@@ -322,13 +319,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreCommunityHierarchy() throws Exception { public void testRestoreCommunityHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreCommunityHierarchy() - BEGIN"); log.info("testRestoreCommunityHierarchy() - BEGIN");
// Locate the top level community (from our test data) // Locate the top level community (from our test data)
@@ -378,13 +368,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreRestrictedCommunity() throws Exception { public void testRestoreRestrictedCommunity() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreRestrictedCommunity() - BEGIN"); log.info("testRestoreRestrictedCommunity() - BEGIN");
// Locate the top-level Community (as a parent) // Locate the top-level Community (as a parent)
@@ -457,13 +440,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testReplaceCommunityHierarchy() throws Exception { public void testReplaceCommunityHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testReplaceCommunityHierarchy() - BEGIN"); log.info("testReplaceCommunityHierarchy() - BEGIN");
// Locate the top level community (from our test data) // Locate the top level community (from our test data)
@@ -535,13 +511,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testReplaceCommunityOnly() throws Exception { public void testReplaceCommunityOnly() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Community WRITE perms
authorizeService.authorizeAction((Context) any, (Community) any,
Constants.WRITE, true);
result = null;
}};
log.info("testReplaceCommunityOnly() - BEGIN"); log.info("testReplaceCommunityOnly() - BEGIN");
// Locate the top level community (from our test data) // Locate the top level community (from our test data)
@@ -575,13 +544,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreCollectionHierarchy() throws Exception { public void testRestoreCollectionHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreCollectionHierarchy() - BEGIN"); log.info("testRestoreCollectionHierarchy() - BEGIN");
// Locate the collection (from our test data) // Locate the collection (from our test data)
@@ -620,13 +582,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreRestrictedCollection() throws Exception { public void testRestoreRestrictedCollection() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreRestrictedCollection() - BEGIN"); log.info("testRestoreRestrictedCollection() - BEGIN");
// Locate the top-level Community (as a parent) // Locate the top-level Community (as a parent)
@@ -699,13 +654,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testReplaceCollectionHierarchy() throws Exception { public void testReplaceCollectionHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testReplaceCollectionHierarchy() - BEGIN"); log.info("testReplaceCollectionHierarchy() - BEGIN");
// Locate the collection (from our test data) // Locate the collection (from our test data)
@@ -759,13 +707,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testReplaceCollectionOnly() throws Exception { public void testReplaceCollectionOnly() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, true);
result = null;
}};
log.info("testReplaceCollectionOnly() - BEGIN"); log.info("testReplaceCollectionOnly() - BEGIN");
// Locate the collection (from our test data) // Locate the collection (from our test data)
@@ -801,13 +742,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreItem() throws Exception { public void testRestoreItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreItem() - BEGIN"); log.info("testRestoreItem() - BEGIN");
// Locate the item (from our test data) // Locate the item (from our test data)
@@ -870,13 +804,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreRestrictedItem() throws Exception { public void testRestoreRestrictedItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreRestrictedItem() - BEGIN"); log.info("testRestoreRestrictedItem() - BEGIN");
// Locate the test Collection (as a parent) // Locate the test Collection (as a parent)
@@ -948,13 +875,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreItemNoPolicies() throws Exception { public void testRestoreItemNoPolicies() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreItemNoPolicies() - BEGIN"); log.info("testRestoreItemNoPolicies() - BEGIN");
// Locate the test Collection (as a parent) // Locate the test Collection (as a parent)
@@ -1009,13 +929,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testReplaceItem() throws Exception { public void testReplaceItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testReplaceItem() - BEGIN"); log.info("testReplaceItem() - BEGIN");
// Locate the item (from our test data) // Locate the item (from our test data)
@@ -1049,17 +962,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/ */
@Test @Test
public void testRestoreMappedItem() throws Exception { public void testRestoreMappedItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
authorizeService.authorizeAction(context, (Collection) any, Constants.REMOVE);
result = null;
authorizeService.authorizeAction(context, (Collection) any, Constants.ADD);
result = null;
}};
log.info("testRestoreMappedItem() - BEGIN"); log.info("testRestoreMappedItem() - BEGIN");
// Get a reference to our test mapped Item // Get a reference to our test mapped Item
@@ -1105,7 +1007,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
* to avoid having to rewrite this code into several tests. * to avoid having to rewrite this code into several tests.
* *
* @param dso DSpaceObject to create AIP(s) for * @param dso DSpaceObject to create AIP(s) for
* @param pkParams any special PackageParameters to pass (if any) * @param pkgParams any special PackageParameters to pass (if any)
* @param recursive whether to recursively create AIPs or just a single AIP * @param recursive whether to recursively create AIPs or just a single AIP
* @return exported root AIP file * @return exported root AIP file
*/ */
@@ -1145,7 +1047,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
* *
* @param parent The DSpaceObject which will be the parent object of the newly restored object(s) * @param parent The DSpaceObject which will be the parent object of the newly restored object(s)
* @param aipFile AIP file to start restoration from * @param aipFile AIP file to start restoration from
* @param pkParams any special PackageParameters to pass (if any) * @param pkgParams any special PackageParameters to pass (if any)
* @param recursive whether to recursively restore AIPs or just a single AIP * @param recursive whether to recursively restore AIPs or just a single AIP
*/ */
private void restoreFromAIP(DSpaceObject parent, File aipFile, PackageParameters pkgParams, boolean recursive) private void restoreFromAIP(DSpaceObject parent, File aipFile, PackageParameters pkgParams, boolean recursive)
@@ -1183,7 +1085,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
* *
* @param dso The DSpaceObject to be replaced from AIP * @param dso The DSpaceObject to be replaced from AIP
* @param aipFile AIP file to start replacement from * @param aipFile AIP file to start replacement from
* @param pkParams any special PackageParameters to pass (if any) * @param pkgParams any special PackageParameters to pass (if any)
* @param recursive whether to recursively restore AIPs or just a single AIP * @param recursive whether to recursively restore AIPs or just a single AIP
*/ */
private void replaceFromAIP(DSpaceObject dso, File aipFile, PackageParameters pkgParams, boolean recursive) private void replaceFromAIP(DSpaceObject dso, File aipFile, PackageParameters pkgParams, boolean recursive)
@@ -1293,9 +1195,9 @@ public class ITDSpaceAIP extends AbstractUnitTest {
// Get the typeText & name of this object from the values // Get the typeText & name of this object from the values
String info = infoMap.get(key); String info = infoMap.get(key);
String[] values = info.split(valueseparator); List<String> values = Splitter.on(valueseparator).splitToList(info);
String typeText = values[0]; String typeText = values.get(0);
String name = values[1]; String name = values.get(1);
// Also assert type and name are correct // Also assert type and name are correct
assertEquals("assertObjectsExist object " + key + " type", assertEquals("assertObjectsExist object " + key + " type",

View File

@@ -14,6 +14,7 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.google.common.base.Splitter;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
@@ -22,7 +23,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class CollectedTest { public class CollectedTest {
@@ -85,17 +86,14 @@ public class CollectedTest {
metadataValueList.add(metadataValue); metadataValueList.add(metadataValue);
String s = "dc.title"; String s = "dc.title";
list.add(s); list.add(s);
String[] splittedString = s.split("\\."); List<String> splittedString = Splitter.on('.').splitToList(s);
collected.setFields(list); collected.setFields(list);
valueList.add("TestValue"); valueList.add("TestValue");
// Mock the state of objects utilized in getValues() to meet the success criteria of an invocation // Mock the state of objects utilized in getValues() to meet the success criteria of an invocation
when(itemService.getMetadata(item, splittedString.length > 0 ? splittedString[0] : when(itemService.getMetadata(item, splittedString.size() > 0 ? splittedString.get(0) : null,
null, splittedString.size() > 1 ? splittedString.get(1) : null,
splittedString.length > 1 ? splittedString[1] : splittedString.size() > 2 ? splittedString.get(2) : null,
null,
splittedString.length > 2 ? splittedString[2] :
null,
Item.ANY, false)).thenReturn(metadataValueList); Item.ANY, false)).thenReturn(metadataValueList);
when(metadataValue.getValue()).thenReturn("TestValue"); when(metadataValue.getValue()).thenReturn("TestValue");

View File

@@ -14,6 +14,7 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.google.common.base.Splitter;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
@@ -22,7 +23,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ConcatenateTest { public class ConcatenateTest {
@@ -107,17 +108,14 @@ public class ConcatenateTest {
metadataValueList.add(metadataValue); metadataValueList.add(metadataValue);
String s = "dc.title"; String s = "dc.title";
list.add(s); list.add(s);
String[] splittedString = s.split("\\."); List<String> splittedString = Splitter.on(".").splitToList(s);
concatenate.setFields(list); concatenate.setFields(list);
valueList.add("TestValue"); valueList.add("TestValue");
// Mock the state of objects utilized in getValues() to meet the success criteria of an invocation // Mock the state of objects utilized in getValues() to meet the success criteria of an invocation
when(itemService.getMetadata(item, splittedString.length > 0 ? splittedString[0] : when(itemService.getMetadata(item, splittedString.size() > 0 ? splittedString.get(0) : null,
null, splittedString.size() > 1 ? splittedString.get(1) : null,
splittedString.length > 1 ? splittedString[1] : splittedString.size() > 2 ? splittedString.get(2) : null,
null,
splittedString.length > 2 ? splittedString[2] :
null,
Item.ANY, false)).thenReturn(metadataValueList); Item.ANY, false)).thenReturn(metadataValueList);
when(metadataValue.getValue()).thenReturn("TestValue"); when(metadataValue.getValue()).thenReturn("TestValue");

View File

@@ -16,7 +16,7 @@ import java.util.Map;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class EntityTypeToFilterQueryServiceTest { public class EntityTypeToFilterQueryServiceTest {

View File

@@ -13,7 +13,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -29,7 +28,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class RelatedTest { public class RelatedTest {
@@ -150,8 +149,8 @@ public class RelatedTest {
assertEquals("TestGetValues 1", virtualMetadataConfiguration.getValues(context, item), assertEquals("TestGetValues 1", virtualMetadataConfiguration.getValues(context, item),
related.getValues(context, item)); related.getValues(context, item));
related.setPlace(2); related.setPlace(2);
// No match should return empty LinkedList // No match should return empty List
assertEquals("TestGetValues 2", new LinkedList<>(), related.getValues(context, item)); assertEquals("TestGetValues 2", new ArrayList<>(), related.getValues(context, item));
} }

View File

@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.LinkedList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@@ -21,14 +21,14 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class UUIDValueTest { public class UUIDValueTest {
@InjectMocks @InjectMocks
private UUIDValue UUIDValue; private UUIDValue uuidValue;
@Mock @Mock
private Context context; private Context context;
@@ -36,32 +36,32 @@ public class UUIDValueTest {
@Test @Test
public void testGetValues() throws Exception { public void testGetValues() throws Exception {
// Setup objects utilized in unit test // Setup objects utilized in unit test
List<String> list = new LinkedList<>(); List<String> list = new ArrayList<>();
Item item = mock(Item.class); Item item = mock(Item.class);
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
when(item.getID()).thenReturn(uuid); when(item.getID()).thenReturn(uuid);
list.add(String.valueOf(uuid)); list.add(String.valueOf(uuid));
// The reported value(s) should match our defined list // The reported value(s) should match our defined list
assertEquals("TestGetValues 0", list, UUIDValue.getValues(context, item)); assertEquals("TestGetValues 0", list, uuidValue.getValues(context, item));
} }
@Test @Test
public void testSetUseForPlace() { public void testSetUseForPlace() {
// Setup objects utilized in unit test // Setup objects utilized in unit test
UUIDValue.setUseForPlace(true); uuidValue.setUseForPlace(true);
// The reported boolean should return true // The reported boolean should return true
assertEquals("TestSetUseForPlace 0", true, UUIDValue.getUseForPlace()); assertEquals("TestSetUseForPlace 0", true, uuidValue.getUseForPlace());
} }
@Test @Test
public void testGetUseForPlace() { public void testGetUseForPlace() {
// Setup objects utilized in unit test // Setup objects utilized in unit test
UUIDValue.setUseForPlace(true); uuidValue.setUseForPlace(true);
// The reported boolean should return true // The reported boolean should return true
assertEquals("TestGetUseForPlace 0", true, UUIDValue.getUseForPlace()); assertEquals("TestGetUseForPlace 0", true, uuidValue.getUseForPlace());
} }
} }

View File

@@ -18,7 +18,7 @@ import org.dspace.content.RelationshipType;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class VirtualMetadataPopulatorTest { public class VirtualMetadataPopulatorTest {

View File

@@ -24,7 +24,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
/** /**
* Class to test the read-only Context cache * Class to test the read-only Context cache

View File

@@ -10,24 +10,31 @@ package org.dspace.core;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.UUID; import java.util.UUID;
import mockit.NonStrictExpectations;
import org.dspace.AbstractUnitTest; import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.eperson.EPerson; import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group; import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService; import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService; import org.dspace.eperson.service.GroupService;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/** /**
* Perform some basic unit tests for Context Class * Perform some basic unit tests for Context Class
@@ -38,6 +45,33 @@ public class ContextTest extends AbstractUnitTest {
protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/**
* This method will be run before every test as per @Before. It will
* initialize resources required for the tests.
*
* Other methods can be annotated with @Before here or in subclasses
* but no execution order is guaranteed
*/
@Before
@Override
public void init() {
super.init();
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded object services
// (To ensure these services use the spy instead of the real service)
ReflectionTestUtils.setField(ePersonService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(groupService, "authorizeService", authorizeServiceSpy);
}
/** /**
* Test of getDBConnection method, of class Context. * Test of getDBConnection method, of class Context.
*/ */
@@ -53,12 +87,9 @@ public class ContextTest extends AbstractUnitTest {
* Test of setCurrentUser method, of class Context. * Test of setCurrentUser method, of class Context.
*/ */
@Test @Test
public void testSetCurrentUser() throws SQLException, AuthorizeException { public void testSetCurrentUser() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{ // Allow full Admin perms
// Allow Admin permissions - needed to create a new EPerson when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
authorizeService.isAdmin((Context) any);
result = true;
}};
EPerson oldUser = context.getCurrentUser(); EPerson oldUser = context.getCurrentUser();
@@ -77,6 +108,9 @@ public class ContextTest extends AbstractUnitTest {
// Restore the previous current user // Restore the previous current user
context.setCurrentUser(oldUser); context.setCurrentUser(oldUser);
// Cleanup our new user
ePersonService.delete(context, newUser);
} }
/** /**
@@ -104,7 +138,6 @@ public class ContextTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testSetCurrentLocale() { public void testSetCurrentLocale() {
//Get previous value //Get previous value
Locale oldLocale = context.getCurrentLocale(); Locale oldLocale = context.getCurrentLocale();
@@ -171,6 +204,9 @@ public class ContextTest extends AbstractUnitTest {
assertThat("testSetExtraLogInfo 0", context.getExtraLogInfo(), notNullValue()); assertThat("testSetExtraLogInfo 0", context.getExtraLogInfo(), notNullValue());
assertThat("testSetExtraLogInfo 1", context.getExtraLogInfo(), equalTo(newValue)); assertThat("testSetExtraLogInfo 1", context.getExtraLogInfo(), equalTo(newValue));
//restore old value
context.setExtraLogInfo(oldValue);
} }
/** /**
@@ -225,28 +261,79 @@ public class ContextTest extends AbstractUnitTest {
cleanupContext(instance); cleanupContext(instance);
} }
/**
* Test of commit method, of class Context.
*/
@Test
public void testCommit() throws SQLException, AuthorizeException, IOException {
// To test commit() we need a new Context object
Context instance = new Context();
// By default, we should have a new DB connection, so let's make sure it is there
assertThat("HibernateDBConnection should exist", instance.getDBConnection(), notNullValue());
assertTrue("Context should be valid", instance.isValid());
assertTrue("Transaction should be open", instance.isTransactionAlive());
// Allow full Admin perms (in new context)
when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
// Create a new EPerson (to be committed)
String createdEmail = "myfakeemail@example.com";
EPerson newUser = ePersonService.create(instance);
newUser.setFirstName(instance, "Tim");
newUser.setLastName(instance, "Smith");
newUser.setEmail(createdEmail);
newUser.setCanLogIn(true);
newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage());
// Now, call commit()
instance.commit();
// We expect our DB connection to still exist
assertThat("HibernateDBConnection should still be open", instance.getDBConnection(), notNullValue());
// We expect the Context to be valid
assertTrue("Context should still be valid", instance.isValid());
// However, the transaction should now be closed
assertFalse("DB transaction should be closed", instance.isTransactionAlive());
// ReloadEntity and verify changes saved
// NOTE: reloadEntity() is required, see commit() method Javadocs
newUser = instance.reloadEntity(newUser);
assertEquals("New user should be created", newUser.getEmail(), createdEmail);
// Change the email and commit again (a Context should support multiple commit() calls)
String newEmail = "myrealemail@example.com";
newUser.setEmail(newEmail);
instance.commit();
// Reload entity and new value should be there.
newUser = instance.reloadEntity(newUser);
assertEquals("New email address should be saved", newUser.getEmail(), newEmail);
// Cleanup our new object & context
ePersonService.delete(instance, newUser);
cleanupContext(instance);
}
/** /**
* Test of abort method, of class Context. * Test of abort method, of class Context.
*/ */
@Test @Test
public void testAbort() throws SQLException, AuthorizeException { public void testAbort() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Admin permissions - needed to create a new EPerson
authorizeService.isAdmin((Context) any);
result = true;
}};
// To test abort() we need a new Context object // To test abort() we need a new Context object
Context instance = new Context(); Context instance = new Context();
// Allow full Admin perms (in new context)
when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
// Create a new EPerson (DO NOT COMMIT IT) // Create a new EPerson (DO NOT COMMIT IT)
String createdEmail = "susie@email.com"; String createdEmail = "susie@email.com";
EPerson newUser = ePersonService.create(instance); EPerson newUser = ePersonService.create(instance);
newUser.setFirstName(context, "Susan"); newUser.setFirstName(instance, "Susan");
newUser.setLastName(context, "Doe"); newUser.setLastName(instance, "Doe");
newUser.setEmail(createdEmail); newUser.setEmail(createdEmail);
newUser.setCanLogIn(true); newUser.setCanLogIn(true);
newUser.setLanguage(context, I18nUtil.getDefaultLocale().getLanguage()); newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage());
// Abort our context // Abort our context
instance.abort(); instance.abort();
@@ -268,25 +355,20 @@ public class ContextTest extends AbstractUnitTest {
*/ */
@Test @Test
public void testClose() throws SQLException, AuthorizeException { public void testClose() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Admin permissions - needed to create a new EPerson
authorizeService.isAdmin((Context) any);
result = true;
}};
String createdEmail = "susie@email.com"; String createdEmail = "susie@email.com";
// To test close() we need a new Context object in a try-with-resources block // To test close() we need a new Context object in a try-with-resources block
try (Context instance = new Context()) { try (Context instance = new Context()) {
// Allow full Admin perms (in new context)
when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
// Create a new EPerson (DO NOT COMMIT IT) // Create a new EPerson (DO NOT COMMIT IT)
EPerson newUser = ePersonService.create(instance); EPerson newUser = ePersonService.create(instance);
newUser.setFirstName(context, "Susan"); newUser.setFirstName(instance, "Susan");
newUser.setLastName(context, "Doe"); newUser.setLastName(instance, "Doe");
newUser.setEmail(createdEmail); newUser.setEmail(createdEmail);
newUser.setCanLogIn(true); newUser.setCanLogIn(true);
newUser.setLanguage(context, I18nUtil.getDefaultLocale().getLanguage()); newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage());
} }
// Open a new context, let's make sure that EPerson isn't there // Open a new context, let's make sure that EPerson isn't there
@@ -410,16 +492,13 @@ public class ContextTest extends AbstractUnitTest {
* Test of getSpecialGroups method, of class Context. * Test of getSpecialGroups method, of class Context.
*/ */
@Test @Test
public void testGetSpecialGroups() throws SQLException, AuthorizeException { public void testGetSpecialGroups() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Admin permissions - needed to create a new Group
authorizeService.isAdmin((Context) any);
result = true;
}};
// To test special groups we need a new Context object // To test special groups we need a new Context object
Context instance = new Context(); Context instance = new Context();
// Allow full Admin perms (in new context)
when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
// Create a new group & add it as a special group // Create a new group & add it as a special group
Group group = groupService.create(instance); Group group = groupService.create(instance);
UUID groupID = group.getID(); UUID groupID = group.getID();
@@ -436,7 +515,8 @@ public class ContextTest extends AbstractUnitTest {
assertThat("testGetSpecialGroup 1", specialGroups.get(0), equalTo(group)); assertThat("testGetSpecialGroup 1", specialGroups.get(0), equalTo(group));
assertThat("testGetSpecialGroup 1", specialGroups.get(1), equalTo(adminGroup)); assertThat("testGetSpecialGroup 1", specialGroups.get(1), equalTo(adminGroup));
// Cleanup our context // Cleanup our context & group
groupService.delete(instance, group);
cleanupContext(instance); cleanupContext(instance);
} }

View File

@@ -0,0 +1,229 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.sql.SQLException;
import org.dspace.AbstractUnitTest;
import org.dspace.eperson.EPerson;
import org.dspace.utils.DSpace;
import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;
/**
* Perform some basic unit tests for HibernateDBConnection
*
* @author tdonohue
*/
public class HibernateDBConnectionTest extends AbstractUnitTest {
private HibernateDBConnection connection;
/**
* This method will be run before every test as per @Before. It will
* initialize resources required for the tests.
*
* Other methods can be annotated with @Before here or in subclasses
* but no execution order is guaranteed
*/
@Before
@Override
public void init() {
super.init();
// Get a DB connection to test with
connection = new DSpace().getServiceManager()
.getServiceByName(null, HibernateDBConnection.class);
}
/**
* Test of getSession method
*/
@Test
public void testGetSession() throws SQLException {
assertNotNull("DB connection should not be null", connection);
// Connection should begin with an active transaction
assertTrue("A transaction should be open by default", connection.getTransaction().isActive());
// Rollback current transaction
connection.getTransaction().rollback();
// Transaction should be closed
assertFalse("Transaction should be closed after rollback", connection.getTransaction().isActive());
//Now call getSession(), saving a reference to the session
Session currentSession = connection.getSession();
// New transaction should be initialized
assertTrue("New transaction should be open after getSession() call",
connection.getTransaction().isActive());
// Call getSession again. The same Session should still be returned
assertEquals("Multiple calls to getSession should return same Session", currentSession,
connection.getSession());
}
/**
* Test of isTransactionAlive method
*/
@Test
public void testIsTransactionAlive() {
assertNotNull("DB connection should not be null", connection);
assertNotNull("Transaction should not be null", connection.getTransaction());
// Connection should begin with a transaction
assertTrue("A transaction should be open by default", connection.isTransActionAlive());
// Rollback current transaction
connection.getTransaction().rollback();
// Transaction should be closed
assertFalse("Transaction should be closed after rollback", connection.isTransActionAlive());
}
/**
* Test of isSessionAlive method
*/
@Test
public void testIsSessionAlive() throws SQLException {
assertNotNull("DB connection should not be null", connection);
assertNotNull("Session should not be null", connection.getSession());
assertTrue("A Session should be alive by default", connection.isSessionAlive());
// Rollback current transaction, closing it
connection.getTransaction().rollback();
// Session should still be alive even after transaction closes
assertTrue("A Session should still be alive if transaction closes", connection.isSessionAlive());
// NOTE: Because we configure Hibernate Session objects to be bound to a thread
// (see 'hibernate.current_session_context_class' in hibernate.cfg.xml), a Session is ALWAYS ALIVE until
// the thread closes (at which point Hibernate will clean it up automatically).
// This means that essentially isSessionAlive() will always return true, unless the connection is severed
// in some unexpected way. See also "testCloseDBConnection()"
}
/**
* Test of closeDBConnection method
*/
@Test
public void testCloseDBConnection() throws SQLException {
// Get a reference to the current Session
Session initialSession = connection.getSession();
// Close the DB connection / Session
// NOTE: Because of our Hibernate configuration, Hibernate automatically creates a new Session per thread.
// Even though we "close" the connection, Hibernate will reopen a new one immediately. So, all this actually
// does is create a *new* Session
connection.closeDBConnection();
Session newSession = connection.getSession();
assertNotEquals("New Session expected",initialSession, newSession);
}
/**
* Test of commit method
*/
@Test
public void testCommit() throws SQLException {
// Ensure a transaction exists
connection.getSession();
assertTrue("Transaction should be active", connection.getTransaction().isActive());
connection.commit();
assertFalse("Commit should close transaction", connection.getTransaction().isActive());
// A second commit should be a no-op (no error thrown)
connection.commit();
}
/**
* Test of rollback method
*/
@Test
public void testRollback() throws SQLException {
// Ensure a transaction exists
connection.getSession();
assertTrue("Transaction should be active", connection.getTransaction().isActive());
connection.rollback();
assertFalse("Rollback should close transaction", connection.getTransaction().isActive());
// A second rollback should be a no-op (no error thrown)
connection.rollback();
}
/**
* Test of reloadEntity method
*/
@Test
public void testReloadEntityAfterRollback() throws SQLException {
// Get DBConnection associated with DSpace Context
HibernateDBConnection dbConnection = (HibernateDBConnection) context.getDBConnection();
EPerson person = context.getCurrentUser();
assertTrue("Current user should be cached in session", dbConnection.getSession()
.contains(person));
dbConnection.rollback();
assertFalse("Current user should be gone from cache", dbConnection.getSession()
.contains(person));
person = dbConnection.reloadEntity(person);
assertTrue("Current user should be cached back in session", dbConnection.getSession()
.contains(person));
}
/**
* Test of reloadEntity method
*/
@Test
public void testReloadEntityAfterCommit() throws SQLException {
// Get DBConnection associated with DSpace Context
HibernateDBConnection dbConnection = (HibernateDBConnection) context.getDBConnection();
EPerson person = context.getCurrentUser();
assertTrue("Current user should be cached in session", dbConnection.getSession()
.contains(person));
dbConnection.commit();
assertFalse("Current user should be gone from cache", dbConnection.getSession()
.contains(person));
person = dbConnection.reloadEntity(person);
assertTrue("Current user should be cached back in session", dbConnection.getSession()
.contains(person));
}
/**
* Test of uncacheEntity method
*/
@Test
public void testUncacheEntity() throws SQLException {
// Get DBConnection associated with DSpace Context
HibernateDBConnection dbConnection = (HibernateDBConnection) context.getDBConnection();
EPerson person = context.getCurrentUser();
assertTrue("Current user should be cached in session", dbConnection.getSession()
.contains(person));
dbConnection.uncacheEntity(person);
assertFalse("Current user should be gone from cache", dbConnection.getSession()
.contains(person));
// Test ability to reload an uncached entity
person = dbConnection.reloadEntity(person);
assertTrue("Current user should be cached back in session", dbConnection.getSession()
.contains(person));
}
}

View File

@@ -12,7 +12,6 @@ import static org.junit.Assert.assertEquals;
import java.util.Locale; import java.util.Locale;
import mockit.Expectations;
import org.dspace.AbstractDSpaceTest; import org.dspace.AbstractDSpaceTest;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
@@ -136,10 +135,7 @@ public class I18nUtilTest extends AbstractDSpaceTest {
final ConfigurationService configService = DSpaceServicesFactory.getInstance().getConfigurationService(); final ConfigurationService configService = DSpaceServicesFactory.getInstance().getConfigurationService();
// Override "default.locale" and ensure it is set to US English // Override "default.locale" and ensure it is set to US English
new Expectations(configService.getClass()) {{ configService.setProperty("default.locale", "en_US.UTF-8");
configService.getProperty("default.locale");
result = "en_US.UTF-8";
}};
// Assert our overridden default.locale is set in I18nUtil // Assert our overridden default.locale is set in I18nUtil
assertEquals("Default locale", new Locale("en", "US", "UTF-8"), I18nUtil.getDefaultLocale()); assertEquals("Default locale", new Locale("en", "US", "UTF-8"), I18nUtil.getDefaultLocale());

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