Merge branch 'ITtoProveAccessRestrictedItem-DS-4123' of https://github.com/Micheleboychuk/DSpace into ITforBitstream-DS-4124

This commit is contained in:
Mykhaylo
2020-03-02 15:00:41 +01:00
351 changed files with 9746 additions and 8050 deletions

View File

@@ -2,14 +2,14 @@ language: java
sudo: false
dist: trusty
env:
env:
# Give Maven 1GB of memory to work with
- MAVEN_OPTS=-Xmx1024M
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.
- oraclejdk8
- oraclejdk11
## 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
@@ -19,7 +19,6 @@ jdk:
# packages:
# - oracle-java8-installer
# Install prerequisites for building Mirage2 more rapidly
before_install:
# Remove outdated settings.xml from Travis builds. Workaround for https://github.com/travis-ci/travis-ci/issues/4629
- rm ~/.m2/settings.xml

View File

@@ -1,12 +1,11 @@
# 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
# - tomcat:8-jre8
# This version is JDK11 compatible
# - tomcat:8-jdk11
# - ANT 1.10.7
# - maven:3-jdk-8
# - note:
# - default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x-jdk8
# - maven:3-jdk-11 (see dspace-dependencies)
# - note: default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x
# Step 1 - Run Maven Build
FROM dspace/dspace-dependencies:dspace-7_x as build
@@ -30,7 +29,7 @@ RUN mvn package && \
mvn clean
# Step 2 - Run Ant Deploy
FROM tomcat:8-jre8 as ant_build
FROM tomcat:8-jdk11 as ant_build
ARG TARGET_DIR=dspace-installer
COPY --from=build /install /dspace-src
WORKDIR /dspace-src
@@ -47,7 +46,7 @@ RUN ant init_installation update_configs update_code update_webapps
# Step 3 - Run tomcat
# 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
COPY --from=ant_build /dspace $DSPACE_INSTALL
EXPOSE 8080 8009
@@ -63,4 +62,4 @@ RUN ln -s $DSPACE_INSTALL/webapps/server /usr/local/tomcat/webapps/server &&
# Please note that server webapp should only run on one path at a time.
#RUN mv /usr/local/tomcat/webapps/ROOT /usr/local/tomcat/webapps/ROOT.bk && \
# ln -s $DSPACE_INSTALL/webapps/server /usr/local/tomcat/webapps/ROOT && \
# ln -s $DSPACE_INSTALL/webapps/rest /usr/local/tomcat/webapps/rest
# ln -s $DSPACE_INSTALL/webapps/rest /usr/local/tomcat/webapps/rest

View File

@@ -1,12 +1,11 @@
# 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
# - openjdk:8-jdk
# This version is JDK11 compatible
# - openjdk:11
# - ANT 1.10.7
# - maven:3-jdk-8
# - note:
# - default tag for branch: dspace/dspace-cli: dspace/dspace-cli:dspace-7_x
# - maven:3-jdk-11 (see dspace-dependencies)
# - note: default tag for branch: dspace/dspace-cli: dspace/dspace-cli:dspace-7_x
# Step 1 - Run Maven Build
FROM dspace/dspace-dependencies:dspace-7_x as build
@@ -30,7 +29,7 @@ RUN mvn package -P'!dspace-rest' && \
mvn clean
# Step 2 - Run Ant Deploy
FROM openjdk:8-jdk as ant_build
FROM openjdk:11 as ant_build
ARG TARGET_DIR=dspace-installer
COPY --from=build /install /dspace-src
WORKDIR /dspace-src
@@ -47,7 +46,7 @@ RUN ant init_installation update_configs update_code
# Step 3 - Run jdk
# 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
COPY --from=ant_build /dspace $DSPACE_INSTALL

View File

@@ -1,8 +1,11 @@
# 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
FROM maven:3-jdk-8 as build
FROM maven:3-jdk-11 as build
ARG TARGET_DIR=dspace-installer
WORKDIR /app
@@ -16,9 +19,9 @@ ADD --chown=dspace . /app/
COPY dspace/src/main/docker/local.cfg /app/local.cfg
# 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 && mvn clean
RUN mvn package
# 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
RUN rm -rf /app/*
RUN rm -rf /app/*

View File

@@ -1,12 +1,13 @@
# 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
# - tomcat:8-jre8
# This version is JDK11 compatible
# - tomcat:8-jdk11
# - ANT 1.10.7
# - maven:3-jdk-8
# - note:
# - default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x-jdk8-test
# - maven:3-jdk-11 (see dspace-dependencies)
# - note: default tag for branch: dspace/dspace: dspace/dspace:dspace-7_x-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
FROM dspace/dspace-dependencies:dspace-7_x as build
@@ -30,7 +31,7 @@ RUN mvn package && \
mvn clean
# Step 2 - Run Ant Deploy
FROM tomcat:8-jre8 as ant_build
FROM tomcat:8-jdk11 as ant_build
ARG TARGET_DIR=dspace-installer
COPY --from=build /install /dspace-src
WORKDIR /dspace-src
@@ -47,7 +48,7 @@ RUN ant init_installation update_configs update_code update_webapps
# Step 3 - Run tomcat
# 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
COPY --from=ant_build /dspace $DSPACE_INSTALL
EXPOSE 8080 8009
@@ -67,4 +68,4 @@ RUN ln -s $DSPACE_INSTALL/webapps/server /usr/local/tomcat/webapps/server &&
# Overwrite the v6.x (deprecated) REST API's web.xml, so that we can run it on HTTP (defaults to requiring HTTPS)
COPY dspace/src/main/docker/test/rest_web.xml $DSPACE_INSTALL/webapps/rest/WEB-INF/web.xml
RUN sed -i -e "s|\${dspace.dir}|$DSPACE_INSTALL|" $DSPACE_INSTALL/webapps/rest/WEB-INF/web.xml
RUN sed -i -e "s|\${dspace.dir}|$DSPACE_INSTALL|" $DSPACE_INSTALL/webapps/rest/WEB-INF/web.xml

View File

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

View File

@@ -4,10 +4,10 @@ networks:
services:
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:
context: .
dockerfile: Dockerfile.jdk8-test
dockerfile: Dockerfile.test
depends_on:
- dspacedb
networks:

View File

@@ -50,10 +50,33 @@
<configuration>
<debug>true</debug>
<showDeprecation>true</showDeprecation>
<compilerArguments>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</compilerArguments>
<annotationProcessorPaths>
<!-- Enable Hibernate's Metamodel Generator to generate metadata model classes
(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>
</plugin>
<plugin>
@@ -93,7 +116,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version>
<version>3.0.0</version>
<executions>
<execution>
<phase>validate</phase>
@@ -161,7 +184,6 @@
install of DSpace, against which Tests can be run. -->
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<configuration>
<outputDirectory>${project.build.directory}/testing</outputDirectory>
<artifactItems>
@@ -196,7 +218,7 @@
(see: http://gmaven.codehaus.org/Executing+Groovy+Code )
We are generating a OS-agnostic version (agnostic.build.dir) of
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.
Otherwise, the Unit Test Framework will not work on Windows OS.
This Groovy code was mostly borrowed from:
@@ -205,19 +227,17 @@
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId>
<version>2.0</version>
<executions>
<execution>
<id>setproperty</id>
<phase>generate-test-resources
</phase> <!-- XXX I think this should be 'initialize' - MHW -->
<phase>initialize</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
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>
</configuration>
</execution>
@@ -230,6 +250,7 @@
<configuration>
<systemPropertyVariables>
<!-- 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 -->
<dspace.dir>${agnostic.build.dir}/testing/dspace/</dspace.dir>
<!-- Turn off any DSpace logging -->
@@ -238,51 +259,13 @@
</configuration>
</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). -->
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<!-- 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>
<!-- Turn off any DSpace logging -->
<dspace.log.init.disable>true</dspace.log.init.disable>
@@ -456,11 +439,6 @@
<groupId>org.dspace</groupId>
<artifactId>dspace-services</artifactId>
</dependency>
<dependency> <!-- Keep jmockit before junit -->
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@@ -481,7 +459,11 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.rometools</groupId>
<artifactId>rome-modules</artifactId>
@@ -609,19 +591,44 @@
<type>jar</type>
</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>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
<!-- NOTE: SWORDv2 needs 1.2.14, required by Abdera: https://abdera.apache.org/ -->
<version>1.2.14</version>
<version>${axiom.version}</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>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
<!-- NOTE: SWORDv2 needs 1.2.14, required by Abdera: https://abdera.apache.org/ -->
<version>1.2.14</version>
<version>${axiom.version}</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>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
@@ -664,7 +671,7 @@
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-matchers</artifactId>
<version>2.6.2</version>
<version>2.6.3</version>
<scope>test</scope>
</dependency>
@@ -674,6 +681,12 @@
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.bcel</groupId>
<artifactId>bcel</artifactId>
<version>6.4.0</version>
</dependency>
</dependencies>
</project>

View File

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

View File

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

View File

@@ -152,11 +152,11 @@ public class GenerateSitemaps {
*/
public static void generateSitemaps(boolean makeHTMLMap,
boolean makeSitemapOrg) throws SQLException, IOException {
String sitemapStem = configurationService.getProperty("dspace.url")
String sitemapStem = configurationService.getProperty("dspace.ui.url")
+ "/sitemap";
String htmlMapStem = configurationService.getProperty("dspace.url")
String htmlMapStem = configurationService.getProperty("dspace.ui.url")
+ "/htmlmap";
String handleURLStem = configurationService.getProperty("dspace.url")
String handleURLStem = configurationService.getProperty("dspace.ui.url")
+ "/handle/";
File outputDir = new File(configurationService.getProperty("sitemap.dir"));
@@ -293,7 +293,7 @@ public class GenerateSitemaps {
.getProperty("http.proxy.port"));
}
String sitemapURL = configurationService.getProperty("dspace.url")
String sitemapURL = configurationService.getProperty("dspace.ui.url")
+ "/sitemap";
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.Context;
import org.dspace.core.LogManager;
import org.dspace.core.Utils;
import org.dspace.discovery.DiscoverQuery;
import org.dspace.discovery.SearchServiceException;
import org.dspace.discovery.SearchUtils;
@@ -581,9 +582,9 @@ public class LogAnalyser {
}
// 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();
url = ConfigurationManager.getProperty("dspace.url").trim();
url = ConfigurationManager.getProperty("dspace.ui.url").trim();
if ((url != null) && (!url.endsWith("/"))) {
url = url + "/";
}

View File

@@ -15,7 +15,7 @@ package org.dspace.app.statistics;
*
* @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
// 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
* than the current object, 0 if they are the same, and +1 if o is greater
* than the current object.
* Compare the current Stat to the given Stat returning -1 if o is less
* than the current Stat, 0 if they are the same, and +1 if o is greater
* 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
* current object value.
*/
@Override
public int compareTo(Object o) {
int objectValue = ((Stat) o).getValue();
public int compareTo(Stat stat) {
int objectValue = stat.getValue();
if (objectValue < this.getValue()) {
return -1;

View File

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

View File

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

View File

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

View File

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

View File

@@ -360,9 +360,13 @@ public class Util {
InputStream cis = null;
try {
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);
} catch (Exception e) {
log.error(e.getMessage(), e);
log.error("Could not open dspace-api's pom.properties", e);
} finally {
if (cis != null) {
try {
@@ -475,10 +479,10 @@ public class Util {
/**
* Split a list in an array of i sub-lists uniformly sized
*
*
* @param idsList the list to split
* @param i the number of sublists to return
*
*
* @return an array of sub-lists of fixed size
*/
public static <T> List<T>[] splitList(List<T> idsList, int i) {

View File

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

View File

@@ -8,6 +8,7 @@
package org.dspace.authorize;
import java.util.Date;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -23,7 +24,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.apache.commons.lang3.ObjectUtils;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Context;
import org.dspace.core.ReloadableEntity;
@@ -123,16 +123,16 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
if (getAction() != other.getAction()) {
return false;
}
if (!ObjectUtils.equals(getEPerson(), other.getEPerson())) {
if (!Objects.equals(getEPerson(), other.getEPerson())) {
return false;
}
if (!ObjectUtils.equals(getGroup(), other.getGroup())) {
if (!Objects.equals(getGroup(), other.getGroup())) {
return false;
}
if (!ObjectUtils.equals(getStartDate(), other.getStartDate())) {
if (!Objects.equals(getStartDate(), other.getStartDate())) {
return false;
}
if (!ObjectUtils.equals(getEndDate(), other.getEndDate())) {
if (!Objects.equals(getEndDate(), other.getEndDate())) {
return false;
}
return true;
@@ -185,7 +185,7 @@ public class ResourcePolicy implements ReloadableEntity<Integer> {
/**
* 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) {
this.actionId = myid;

View File

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

View File

@@ -367,7 +367,7 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> i
@Override
public void setWorkflowGroup(Context context, Collection collection, int step, Group group)
throws SQLException, AuthorizeException {
throws SQLException {
Workflow workflow = null;
try {
workflow = workflowFactory.getWorkflow(collection);
@@ -889,4 +889,4 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl<Collection> i
throws SQLException {
return collectionDAO.getCollectionsWithBitstreamSizesTotal(context);
}
}
}

View File

@@ -694,9 +694,11 @@ public abstract class DSpaceObjectServiceImpl<T extends DSpaceObject> implements
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(
"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);
@@ -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 org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.dao.MetadataFieldDAO;
import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService;
import org.dspace.content.service.MetadataValueService;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
@@ -42,6 +44,8 @@ public class MetadataFieldServiceImpl implements MetadataFieldService {
protected AuthorizeService authorizeService;
@Autowired(required = true)
protected MetadataValueService metadataValueService;
@Autowired(required = true)
protected MetadataSchemaService metadataSchemaService;
protected MetadataFieldServiceImpl() {
@@ -87,13 +91,25 @@ public class MetadataFieldServiceImpl implements MetadataFieldService {
return metadataFieldDAO.findByElement(context, metadataSchema, element, qualifier);
}
@Override
public MetadataField findByElement(Context context, String metadataSchemaName, String element, String qualifier)
throws SQLException {
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
public List<MetadataField> findFieldsByElementNameUnqualified(Context context, String metadataSchemaName,
String element) throws SQLException {

View File

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

View File

@@ -92,7 +92,7 @@ public class OREDisseminationCrosswalk
private Element disseminateItem(Context context, Item item)
throws CrosswalkException, IOException, SQLException, AuthorizeException {
String oaiUrl = null;
String dsUrl = configurationService.getProperty("dspace.url");
String dsUrl = configurationService.getProperty("dspace.ui.url");
String remSource = configurationService.getProperty("oai.ore.authoritative.source");
if (remSource == null || remSource.equalsIgnoreCase("oai")) {
@@ -265,7 +265,8 @@ public class OREDisseminationCrosswalk
Element pmhMeta = new Element("entry",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");
pmhMeta.addContent(pUri);

View File

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

View File

@@ -1400,7 +1400,7 @@ public abstract class AbstractMETSDisseminator
}
if (handle != null) {
return configurationService
.getProperty("dspace.url")
.getProperty("dspace.ui.url")
+ "/bitstream/"
+ handle
+ "/"
@@ -1410,7 +1410,7 @@ public abstract class AbstractMETSDisseminator
} else { //no Handle assigned, so persistent(-ish) URI for bitstream is
// Format: {site-base-url}/retrieve/{bitstream-internal-id}
return configurationService
.getProperty("dspace.url")
.getProperty("dspace.ui.url")
+ "/retrieve/"
+ 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.
* 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.
* <p>
* 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.
* 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.
*
* @param context DSpace context
@@ -231,7 +231,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/**
* 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.
*
* @param context DSpace context
@@ -272,7 +272,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/**
* 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 dso DSpaceObject
@@ -292,7 +292,7 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/**
* 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 dso DSpaceObject
@@ -314,10 +314,10 @@ public interface DSpaceObjectService<T extends DSpaceObject> {
/**
* 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
* 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.
*
* @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;
/**
* 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,
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
*/
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)
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,
String element)
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 (!isValid()) {
log.info("complete() was called on a closed Context object. No changes to commit.");
return;
}
try {
// As long as we have a valid, writeable database connection,
// rollback any changes if we are in read-only mode,
// otherwise, commit any changes made as part of the transaction
if (isReadOnly()) {
abort();
} else {
// commit changes. Otherwise, we'll just close the DB connection (see below)
if (!isReadOnly()) {
commit();
}
} finally {
if (dbConnection != null) {
// Free the DB connection
// Free the DB connection and invalidate the Context
dbConnection.closeDBConnection();
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 (!isValid()) {
log.info("commit() was called on a closed Context object. No changes to commit.");
return;
}
if (isReadOnly()) {
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 {
// 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,
// as the consumers may change something too
dispatchEvents();
}
// Dispatch events before committing changes to the database,
// as the consumers may change something too
dispatchEvents();
} finally {
if (log.isDebugEnabled()) {
log.debug("Cache size on commit is " + getCacheSize());
}
if (dbConnection != null) {
//Commit our changes
// Commit our changes (this closes the transaction but leaves database connection open)
dbConnection.commit();
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() {
// Commit any changes made as part of the transaction
Dispatcher dispatcher = null;
try {
@@ -462,6 +459,7 @@ public class Context implements AutoCloseable {
/**
* 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
*/
@@ -490,6 +488,10 @@ public class Context implements AutoCloseable {
return events;
}
/**
* Whether or not the context has events cached.
* @return true or false
*/
public boolean hasEvents() {
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 (!isValid()) {
log.info("abort() was called on a closed Context object. No changes to abort.");
return;
}
try {
// Rollback ONLY if we have a database connection, and it is NOT Read Only
if (isValid() && !isReadOnly()) {
// Rollback ONLY if we have a database transaction, and it is NOT Read Only
if (!isReadOnly() && isTransactionAlive()) {
dbConnection.rollback();
}
} catch (SQLException se) {
log.error(se.getMessage(), se);
log.error("Error rolling back transaction during an abort()", se);
} finally {
try {
if (!dbConnection.isSessionAlive()) {
if (dbConnection != null) {
// Free the DB connection & invalidate the Context
dbConnection.closeDBConnection();
dbConnection = null;
}
} catch (Exception ex) {
log.error("Exception aborting context", ex);
log.error("Error closing the database connection", ex);
}
events = null;
}
@@ -558,7 +563,22 @@ public class Context implements AutoCloseable {
*/
public boolean isValid() {
// 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;
}
/**
* Add a group's UUID to the list of special groups cached in Context
* @param groupID UUID of group
*/
public void setSpecialGroup(UUID 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
* @return true if member
*/
public boolean inSpecialGroup(UUID groupID) {
if (specialGroups.contains(groupID)) {
// System.out.println("Contains " + groupID);
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
* of.
* Get an array of all of the special groups that current user is a member of.
*
* @return list of groups
* @return list of special groups
* @throws SQLException if database error
*/
public List<Group> getSpecialGroups() throws SQLException {
@@ -608,6 +628,10 @@ public class Context implements AutoCloseable {
return myGroups;
}
/**
* Close the context, aborting any open transactions (if any).
* @throws Throwable
*/
@Override
protected void finalize() throws Throwable {
/*

View File

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

View File

@@ -35,6 +35,23 @@ import org.springframework.orm.hibernate5.SessionFactoryUtils;
/**
* 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
*/
@@ -47,32 +64,61 @@ public class HibernateDBConnection implements DBConnection<Session> {
private boolean batchModeEnabled = 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
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()) {
sessionFactory.getCurrentSession().beginTransaction();
configureDatabaseMode();
}
// Return the current Hibernate Session object (Hibernate will create one if it doesn't yet exist)
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
public boolean isTransActionAlive() {
Transaction transaction = getTransaction();
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() {
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
public boolean isSessionAlive() {
return sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession()
.getTransaction() != null && sessionFactory
.getCurrentSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE);
return sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession().isOpen();
}
/**
* 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
public void rollback() throws SQLException {
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
public void closeDBConnection() throws SQLException {
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
public void commit() throws SQLException {
if (isTransActionAlive() && !getTransaction().getStatus().isOneOf(TransactionStatus.MARKED_ROLLBACK,
TransactionStatus.ROLLING_BACK)) {
// Flush synchronizes the database with in-memory objects in Session (and frees up that memory)
getSession().flush();
// Commit those results to the database & ends the Transaction
getTransaction().commit();
}
}
@@ -132,6 +198,16 @@ public class HibernateDBConnection implements DBConnection<Session> {
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
@SuppressWarnings("unchecked")
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 <E> The class of the enity. The entity must implement the {@link ReloadableEntity} interface.
* @param entity The entity to evict
* @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.
*/
@Override

View File

@@ -13,6 +13,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.rmi.dgc.VMID;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -30,7 +32,10 @@ import java.util.regex.Pattern;
import com.coverity.security.Escape;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.apache.logging.log4j.Logger;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/**
* Utility functions for DSpace.
@@ -408,4 +413,38 @@ public final class Utils {
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

@@ -218,7 +218,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
/**
* Unindex a Document in the Lucene index.
*
*
* @param context the dspace context
* @param searchUniqueID the search uniqueID of the document to be deleted
* @throws IOException if IO error
@@ -230,7 +230,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
/**
* Unindex a Document in the Lucene Index.
*
*
* @param context the dspace context
* @param searchUniqueID the search uniqueID of the document to be deleted
* @throws IOException if IO error
@@ -465,7 +465,7 @@ public class SolrServiceImpl implements SearchService, IndexingService {
Locale.getDefault(), "internal_error"));
email.addRecipient(recipient);
email.addArgument(ConfigurationManager
.getProperty("dspace.url"));
.getProperty("dspace.ui.url"));
email.addArgument(new Date());
String stackTrace;

View File

@@ -7,6 +7,7 @@
*/
package org.dspace.discovery.configuration;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.beans.factory.annotation.Required;
/**
@@ -46,4 +47,11 @@ public class DiscoverySortFieldConfiguration {
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)
throws MessagingException, IOException, SQLException {
String base = ConfigurationManager.getProperty("dspace.url");
String base = ConfigurationManager.getProperty("dspace.ui.url");
// Note change from "key=" to "token="
String specialLink = new StringBuffer().append(base).append(

View File

@@ -83,7 +83,7 @@ public class EPersonConsumer implements Consumer {
adminEmail.addRecipient(notifyRecipient);
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.getEmail());
adminEmail.addArgument(new Date());

View File

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

View File

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

View File

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

View File

@@ -473,7 +473,7 @@ public class SimpleDSORelationsConverterPlugin
// we currently ignore those
return null;
}
String dspaceURL = configurationService.getProperty("dspace.url");
String dspaceURL = configurationService.getProperty("dspace.ui.url");
String link = "";
try {
// 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".equals(lang)) {
urlBuilder.append(DSpaceServicesFactory.getInstance()
.getConfigurationService().getProperty("dspace.url"));
.getConfigurationService().getProperty("dspace.ui.url"));
if (!handle.equals(DSpaceServicesFactory.getInstance()
.getConfigurationService().getProperty("handle.prefix") + "/0")) {
urlBuilder.append("/handle/");

View File

@@ -11,6 +11,7 @@ import java.util.List;
import java.util.stream.Collectors;
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
@@ -95,6 +96,7 @@ public class DSpaceCommandLineParameter {
* @param other The other object
* @return A boolean indicating equality
*/
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
@@ -105,4 +107,12 @@ public class DSpaceCommandLineParameter {
return StringUtils.equals(this.getName(), ((DSpaceCommandLineParameter) other).getName()) && StringUtils
.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
try {

View File

@@ -92,7 +92,9 @@ public class S3BitStoreService implements BitStoreService {
// bucket name
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);
}
@@ -342,8 +344,10 @@ public class S3BitStoreService implements BitStoreService {
Region usEast1 = Region.getRegion(Regions.US_EAST_1);
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
store.bucketName = "dspace-asset-" + ConfigurationManager.getProperty("dspace.hostname") + ".s3test";
store.bucketName = "dspace-asset-" + hostname + ".s3test";
store.s3Service.createBucket(store.bucketName);
/* Broken in DSpace 6 TODO Refactor
// time everything, todo, swtich to caliper

View File

@@ -1041,7 +1041,7 @@ public class BasicWorkflowServiceImpl implements BasicWorkflowService {
@Override
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,

View File

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

View File

@@ -7,29 +7,53 @@
*/
package org.dspace.xmlworkflow;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.service.CollectionService;
import org.dspace.core.Context;
import org.dspace.handle.service.HandleService;
import org.dspace.utils.DSpace;
import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.Workflow;
import org.dspace.xmlworkflow.state.actions.WorkflowActionConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
/**
* The workflowfactory is responsible for parsing the
* workflow xml file and is used to retrieve the workflow for
* a certain collection
* The workflowfactory is responsible for parsing the workflow xml file and is used to retrieve info about the workflow:
* - the workflow for a certain collection
* - collections mapped to a certain workflow
* - collections not mapped to any workflow
* - configured workflows and the default workflow
* - workflow action by name
*
* @author Bram De Schouwer (bram.deschouwer at dot com)
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Maria Verdonck (Atmire) on 11/12/2019
*/
public class XmlWorkflowFactoryImpl implements XmlWorkflowFactory {
public static final String LEGACY_WORKFLOW_NAME = "defaultWorkflow";
private Logger log = org.apache.logging.log4j.LogManager.getLogger(XmlWorkflowFactoryImpl.class);
private Map<String, Workflow> workflowMapping;
@Autowired
protected CollectionService collectionService;
@Autowired
protected HandleService handleService;
@Override
public Workflow getWorkflow(Collection collection) throws WorkflowConfigurationException {
// Attempt to retrieve our workflow object
@@ -50,4 +74,93 @@ public class XmlWorkflowFactoryImpl implements XmlWorkflowFactory {
public void setWorkflowMapping(Map<String, Workflow> workflowMapping) {
this.workflowMapping = workflowMapping;
}
}
@Override
public Workflow getWorkflowByName(String workflowName) throws WorkflowConfigurationException {
for (Workflow workflow : workflowMapping.values()) {
if (workflow.getID().equals(workflowName)) {
return workflow;
}
}
throw new WorkflowConfigurationException(
"Error while retrieving workflow by the following name: " + workflowName);
}
@Override
public Workflow getDefaultWorkflow() {
return this.workflowMapping.get(LEGACY_WORKFLOW_NAME);
}
@Override
public List<Workflow> getAllConfiguredWorkflows() {
return new ArrayList<>(this.workflowMapping.values());
}
@Override
public List<Collection> getCollectionHandlesMappedToWorklow(Context context, String workflowName) {
List<Collection> collectionsMapped = new ArrayList<>();
for (String handle : this.workflowMapping.keySet()) {
if (this.workflowMapping.get(handle).getID().equals(workflowName)) {
try {
Collection collection = (Collection) handleService.resolveToObject(context, handle);
if (collection != null) {
collectionsMapped.add(collection);
}
} catch (SQLException e) {
log.error("SQLException in XmlWorkflowFactoryImpl.getCollectionHandlesMappedToWorklow trying to " +
"retrieve collection with handle: " + handle, e);
}
}
}
return collectionsMapped;
}
@Override
public List<Collection> getAllNonMappedCollectionsHandles(Context context) {
List<Collection> nonMappedCollections = new ArrayList<>();
try {
for (Collection collection : this.collectionService.findAll(context)) {
if (workflowMapping.get(collection.getHandle()) == null) {
nonMappedCollections.add(collection);
}
}
} catch (SQLException e) {
log.error("SQLException in XmlWorkflowFactoryImpl.getAllNonMappedCollectionsHandles trying to " +
"retrieve all collections", e);
}
return nonMappedCollections;
}
@Override
public boolean workflowByThisNameExists(String workflowName) {
for (Workflow workflow : this.workflowMapping.values()) {
if (workflow.getID().equals(workflowName)) {
return true;
}
}
return false;
}
@Override
public boolean isDefaultWorkflow(String workflowName) {
if (StringUtils.isNotBlank(workflowName)) {
Workflow defaultWorkflow = this.getDefaultWorkflow();
if (defaultWorkflow != null && StringUtils.isNotBlank(defaultWorkflow.getID())) {
return (defaultWorkflow.getID().equals(workflowName));
}
}
return false;
}
@Override
public WorkflowActionConfig getActionByName(String workflowActionName) {
return new DSpace().getServiceManager().getServiceByName(workflowActionName, WorkflowActionConfig.class);
}
@Override
public Step getStepByName(String workflowStepName) {
return new DSpace().getServiceManager().getServiceByName(workflowStepName, Step.class);
}
}

View File

@@ -1049,7 +1049,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
email.addArgument(coll.getName());
email.addArgument(rejector);
email.addArgument(reason);
email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/mydspace");
email.addArgument(ConfigurationManager.getProperty("dspace.ui.url") + "/mydspace");
email.send();
} catch (Exception ex) {
@@ -1063,7 +1063,7 @@ public class XmlWorkflowServiceImpl implements XmlWorkflowService {
@Override
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 {

View File

@@ -7,23 +7,31 @@
*/
package org.dspace.xmlworkflow.factory;
import java.util.List;
import org.dspace.content.Collection;
import org.dspace.core.Context;
import org.dspace.xmlworkflow.WorkflowConfigurationException;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.Workflow;
import org.dspace.xmlworkflow.state.actions.WorkflowActionConfig;
/**
* The xmlworkflowfactory is responsible for parsing the
* workflow xml file and is used to retrieve the workflow for
* a certain collection
* The workflowfactory is responsible for parsing the workflow xml file and is used to retrieve info about the workflow:
* - the workflow for a certain collection
* - collections mapped to a certain workflow
* - collections not mapped to any workflow
* - configured workflows and the default workflow
* - workflow action by name
*
* @author Bram De Schouwer (bram.deschouwer at dot com)
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
* @author Maria Verdonck (Atmire) on 11/12/2019
*/
public interface XmlWorkflowFactory {
/**
* Retrieve the workflow configuration for a single collection
*
@@ -32,4 +40,74 @@ public interface XmlWorkflowFactory {
* @throws WorkflowConfigurationException occurs if there is a configuration error in the workflow
*/
public Workflow getWorkflow(Collection collection) throws WorkflowConfigurationException;
/**
* Retrieves the workflow configuration by name
*
* @param workflowName the name for which we want our workflow
* @return the workflow configuration
* @throws WorkflowConfigurationException occurs if there is no workflow configured by that name
*/
public Workflow getWorkflowByName(String workflowName) throws WorkflowConfigurationException;
/**
* Creates a list of all configured workflows, or returns the cache of this if it was already created
*
* @return List of all configured workflows
*/
public List<Workflow> getAllConfiguredWorkflows();
/**
* Check to see if there is a workflow configured by the given name
*
* @param workflowName Name of a possible configured workflow
* @return True if there is a workflow configured by this name, false otherwise
*/
public boolean workflowByThisNameExists(String workflowName);
/**
* Check to see if the given workflowName is the workflow configured to be default for collections
*
* @param workflowName Name of workflow to check if default
* @return True if given workflowName is the workflow mapped to default for collections, otherwise false
*/
public boolean isDefaultWorkflow(String workflowName);
/**
* Gets the default workflow, i.e. the workflow that is mapped to collection=default in workflow.xml
*/
public Workflow getDefaultWorkflow();
/**
* Return a list of collections that are mapped to the given workflow in the workflow configuration.
* * Makes use of a cache so it only retrieves the workflowName->List<collectionHandle> if it's not cached
*
* @param context Dspace context
* @param workflowName Name of workflow we want the collections of that are mapped to is
* @return List of collections mapped to the requested workflow
*/
public List<Collection> getCollectionHandlesMappedToWorklow(Context context, String workflowName);
/**
* Returns list of collections that are not mapped to any configured workflow, and thus use the default workflow
*
* @return List of collections not mapped to any workflow
*/
public List<Collection> getAllNonMappedCollectionsHandles(Context context);
/**
* Retrieves a {@link WorkflowActionConfig} object based on its name, should correspond with bean id in workflow-actions.xml
*
* @param workflowActionName Name of workflow action we want to retrieve
* @return Workflow action object corresponding to the given workflowActionName
*/
public WorkflowActionConfig getActionByName(String workflowActionName);
/**
* Retrieves a {@link Step} object based on its name, should correspond with bean id in workflow.xml
*
* @param workflowStepName Name of workflow step we want to retrieve
* @return Workflow step object corresponding to the given workflowStepName
*/
public Step getStepByName(String workflowStepName);
}

View File

@@ -36,8 +36,7 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
public abstract class Action {
private WorkflowActionConfig parent;
private static String ERROR_FIELDS_ATTRIBUTE = "dspace.workflow.error_fields";
private static final String ERROR_FIELDS_ATTRIBUTE = "dspace.workflow.error_fields";
public abstract void activate(Context c, XmlWorkflowItem wf)
throws SQLException, IOException, AuthorizeException, WorkflowException;
@@ -45,6 +44,12 @@ public abstract class Action {
public abstract ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException, WorkflowException;
/**
* Returns a list of options that the user can select at this action which results in the next step in the workflow
* @return A list of options of this action, resulting in the next step of the workflow
*/
public abstract List<String> getOptions();
public WorkflowActionConfig getParent() {
return parent;
}

View File

@@ -7,6 +7,8 @@
*/
package org.dspace.xmlworkflow.state.actions;
import java.util.List;
import org.dspace.xmlworkflow.state.Step;
/**
@@ -59,4 +61,12 @@ public class WorkflowActionConfig {
return step;
}
/**
* Returns a list of options the user has on this action, resulting in the next step of the workflow
* @return A list of options of this action, resulting in the next step of the workflow
*/
public List<String> getOptions() {
return this.processingAction.getOptions();
}
}

View File

@@ -9,6 +9,8 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.authorize.AuthorizeException;
@@ -31,40 +33,49 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
*/
public class AcceptEditRejectAction extends ProcessingAction {
public static final int MAIN_PAGE = 0;
public static final int REJECT_PAGE = 1;
private static final String SUBMIT_APPROVE = "submit_approve";
private static final String SUBMIT_REJECT = "submit_reject";
//TODO: rename to AcceptAndEditMetadataAction
@Override
public void activate(Context c, XmlWorkflowItem wf) throws SQLException {
public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException {
throws SQLException, AuthorizeException, IOException {
if (request.getParameter("submit_approve") != null) {
return processAccept(c, wfi, step, request);
if (request.getParameter(SUBMIT_APPROVE) != null) {
return processAccept(c, wfi);
} else {
if (request.getParameter("submit_reject") != null) {
return processRejectPage(c, wfi, step, request);
if (request.getParameter(SUBMIT_REJECT) != null) {
return processRejectPage(c, wfi, request);
}
}
return new ActionResult(ActionResult.TYPE.TYPE_CANCEL);
}
public ActionResult processAccept(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException {
@Override
public List<String> getOptions() {
List<String> options = new ArrayList<>();
options.add(SUBMIT_APPROVE);
options.add(SUBMIT_REJECT);
options.add(ProcessingAction.SUBMIT_EDIT_METADATA);
return options;
}
public ActionResult processAccept(Context c, XmlWorkflowItem wfi)
throws SQLException, AuthorizeException {
//Delete the tasks
addApprovedProvenance(c, wfi);
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
public ActionResult processRejectPage(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException {
public ActionResult processRejectPage(Context c, XmlWorkflowItem wfi, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException {
String reason = request.getParameter("reason");
if (reason == null || 0 == reason.trim().length()) {
addErrorField(request, "reason");
@@ -85,14 +96,14 @@ public class AcceptEditRejectAction extends ProcessingAction {
// Get user's name + email address
String usersName = XmlWorkflowServiceFactory.getInstance().getXmlWorkflowService()
.getEPersonName(c.getCurrentUser());
.getEPersonName(c.getCurrentUser());
String provDescription = getProvenanceStartId() + " Approved for entry into archive by "
+ usersName + " on " + now + " (GMT) ";
+ usersName + " on " + now + " (GMT) ";
// Add to item as a DC field
itemService.addMetadata(c, wfi.getItem(), MetadataSchemaEnum.DC.getName(), "description", "provenance", "en",
provDescription);
provDescription);
itemService.update(c, wfi.getItem());
}
}

View File

@@ -7,8 +7,9 @@
*/
package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.authorize.AuthorizeException;
@@ -31,21 +32,22 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
*/
public class FinalEditAction extends ProcessingAction {
private static final String SUBMIT_APPROVE = "submit_approve";
@Override
public void activate(Context c, XmlWorkflowItem wf) throws SQLException {
public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException {
throws SQLException, AuthorizeException {
return processMainPage(c, wfi, step, request);
}
public ActionResult processMainPage(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException {
if (request.getParameter("submit_approve") != null) {
throws SQLException, AuthorizeException {
if (request.getParameter(SUBMIT_APPROVE) != null) {
//Delete the tasks
addApprovedProvenance(c, wfi);
@@ -56,20 +58,28 @@ public class FinalEditAction extends ProcessingAction {
}
}
@Override
public List<String> getOptions() {
List<String> options = new ArrayList<>();
options.add(SUBMIT_APPROVE);
options.add(ProcessingAction.SUBMIT_EDIT_METADATA);
return options;
}
private void addApprovedProvenance(Context c, XmlWorkflowItem wfi) throws SQLException, AuthorizeException {
//Add the provenance for the accept
String now = DCDate.getCurrent().toString();
// Get user's name + email address
String usersName = XmlWorkflowServiceFactory.getInstance().getXmlWorkflowService()
.getEPersonName(c.getCurrentUser());
.getEPersonName(c.getCurrentUser());
String provDescription = getProvenanceStartId() + " Approved for entry into archive by "
+ usersName + " on " + now + " (GMT) ";
+ usersName + " on " + now + " (GMT) ";
// Add to item as a DC field
itemService.addMetadata(c, wfi.getItem(), MetadataSchemaEnum.DC.getName(), "description", "provenance", "en",
provDescription);
provDescription);
itemService.update(c, wfi.getItem());
}

View File

@@ -34,6 +34,7 @@ public abstract class ProcessingAction extends Action {
@Autowired(required = true)
protected ItemService itemService;
protected static final String SUBMIT_EDIT_METADATA = "submit_edit_metadata";
@Override
public boolean isAuthorized(Context context, HttpServletRequest request, XmlWorkflowItem wfi) throws SQLException {

View File

@@ -9,6 +9,8 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -34,6 +36,8 @@ public class ReviewAction extends ProcessingAction {
public static final int MAIN_PAGE = 0;
public static final int REJECT_PAGE = 1;
private static final String SUBMIT_APPROVE = "submit_approve";
private static final String SUBMIT_REJECT = "submit_reject";
@Override
public void activate(Context c, XmlWorkflowItem wfItem) {
@@ -43,10 +47,10 @@ public class ReviewAction extends ProcessingAction {
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException {
if (request.getParameter("submit_approve") != null) {
if (request.getParameter(SUBMIT_APPROVE) != null) {
return processAccept(c, wfi, step, request);
} else {
if (request.getParameter("submit_reject") != null) {
if (request.getParameter(SUBMIT_REJECT) != null) {
return processRejectPage(c, wfi, step, request);
}
}
@@ -54,6 +58,14 @@ public class ReviewAction extends ProcessingAction {
return new ActionResult(ActionResult.TYPE.TYPE_CANCEL);
}
@Override
public List<String> getOptions() {
List<String> options = new ArrayList<>();
options.add(SUBMIT_APPROVE);
options.add(SUBMIT_REJECT);
return options;
}
public ActionResult processAccept(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException {
//Delete the tasks

View File

@@ -9,6 +9,7 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -17,7 +18,6 @@ import org.dspace.content.Item;
import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue;
import org.dspace.core.Context;
import org.dspace.workflow.WorkflowException;
import org.dspace.xmlworkflow.factory.XmlWorkflowServiceFactory;
import org.dspace.xmlworkflow.service.WorkflowRequirementsService;
import org.dspace.xmlworkflow.state.Step;
@@ -40,14 +40,13 @@ public class ScoreEvaluationAction extends ProcessingAction {
private int minimumAcceptanceScore;
@Override
public void activate(Context c, XmlWorkflowItem wf)
throws SQLException, IOException, AuthorizeException, WorkflowException {
public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException, WorkflowException {
throws SQLException, AuthorizeException, IOException {
boolean hasPassed = false;
//Retrieve all our scores from the metadata & add em up
List<MetadataValue> scores = itemService
@@ -82,6 +81,11 @@ public class ScoreEvaluationAction extends ProcessingAction {
}
}
@Override
public List<String> getOptions() {
return new ArrayList<>();
}
public int getMinimumAcceptanceScore() {
return minimumAcceptanceScore;
}

View File

@@ -7,14 +7,14 @@
*/
package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.app.util.Util;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.workflow.WorkflowException;
import org.dspace.xmlworkflow.service.WorkflowRequirementsService;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.actions.ActionResult;
@@ -32,20 +32,21 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
*/
public class ScoreReviewAction extends ProcessingAction {
private static final String SUBMIT_SCORE = "submit_score";
@Override
public void activate(Context c, XmlWorkflowItem wf)
throws SQLException, IOException, AuthorizeException, WorkflowException {
public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException, WorkflowException {
if (request.getParameter("submit_score") != null) {
throws SQLException, AuthorizeException {
if (request.getParameter(SUBMIT_SCORE) != null) {
int score = Util.getIntParameter(request, "score");
//Add our score to the metadata
itemService.addMetadata(c, wfi.getItem(), WorkflowRequirementsService.WORKFLOW_SCHEMA, "score", null, null,
String.valueOf(score));
String.valueOf(score));
itemService.update(c, wfi.getItem());
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
@@ -54,4 +55,9 @@ public class ScoreReviewAction extends ProcessingAction {
return new ActionResult(ActionResult.TYPE.TYPE_SUBMISSION_PAGE);
}
}
@Override
public List<String> getOptions() {
return Arrays.asList(SUBMIT_SCORE);
}
}

View File

@@ -7,8 +7,8 @@
*/
package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
@@ -18,7 +18,6 @@ import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.service.EPersonService;
import org.dspace.workflow.WorkflowException;
import org.dspace.xmlworkflow.Role;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.actions.ActionResult;
@@ -39,36 +38,38 @@ import org.springframework.beans.factory.annotation.Required;
*/
public class SelectReviewerAction extends ProcessingAction {
public static final int MAIN_PAGE = 0;
public static final int SEARCH_RESULTS_PAGE = 1;
public static final int RESULTS_PER_PAGE = 5;
private static final String SUBMIT_CANCEL = "submit_cancel";
private static final String SUBMIT_SEARCH = "submit_search";
private static final String SUBMIT_SELECT_REVIEWER = "submit_select_reviewer_";
private Role role;
@Autowired(required = true)
protected EPersonService ePersonService;
private EPersonService ePersonService;
@Autowired(required = true)
protected WorkflowItemRoleService workflowItemRoleService;
private WorkflowItemRoleService workflowItemRoleService;
@Override
public void activate(Context c, XmlWorkflowItem wf)
throws SQLException, IOException, AuthorizeException, WorkflowException {
public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException, WorkflowException {
String submitButton = Util.getSubmitButton(request, "submit_cancel");
throws SQLException, AuthorizeException {
String submitButton = Util.getSubmitButton(request, SUBMIT_CANCEL);
//Check if our user has pressed cancel
if (submitButton.equals("submit_cancel")) {
if (submitButton.equals(SUBMIT_CANCEL)) {
//Send us back to the submissions page
return new ActionResult(ActionResult.TYPE.TYPE_CANCEL);
} else if (submitButton.equals("submit_search")) {
} else if (submitButton.equals(SUBMIT_SEARCH)) {
//Perform the search
String query = request.getParameter("query");
int page = Util.getIntParameter(request, "result-page");
@@ -85,7 +86,7 @@ public class SelectReviewerAction extends ProcessingAction {
request.setAttribute("result-page", page);
request.setAttribute("page", SEARCH_RESULTS_PAGE);
return new ActionResult(ActionResult.TYPE.TYPE_PAGE, SEARCH_RESULTS_PAGE);
} else if (submitButton.startsWith("submit_select_reviewer_")) {
} else if (submitButton.startsWith(SUBMIT_SELECT_REVIEWER)) {
//Retrieve the identifier of the eperson which will do the reviewing
UUID reviewerId = UUID.fromString(submitButton.substring(submitButton.lastIndexOf("_") + 1));
EPerson reviewer = ePersonService.find(c, reviewerId);
@@ -102,6 +103,14 @@ public class SelectReviewerAction extends ProcessingAction {
return new ActionResult(ActionResult.TYPE.TYPE_ERROR);
}
@Override
public List<String> getOptions() {
List<String> options = new ArrayList<>();
options.add(SUBMIT_SEARCH);
options.add(SUBMIT_SELECT_REVIEWER);
return options;
}
public Role getRole() {
return role;
}

View File

@@ -9,6 +9,8 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.app.util.Util;
@@ -38,6 +40,10 @@ public class SingleUserReviewAction extends ProcessingAction {
public static final int OUTCOME_REJECT = 1;
protected static final String SUBMIT_APPROVE = "submit_approve";
protected static final String SUBMIT_REJECT = "submit_reject";
protected static final String SUBMIT_DECLINE_TASK = "submit_decline_task";
@Override
public void activate(Context c, XmlWorkflowItem wfItem) {
@@ -58,19 +64,28 @@ public class SingleUserReviewAction extends ProcessingAction {
}
}
@Override
public List<String> getOptions() {
List<String> options = new ArrayList<>();
options.add(SUBMIT_APPROVE);
options.add(SUBMIT_REJECT);
options.add(SUBMIT_DECLINE_TASK);
return options;
}
public ActionResult processMainPage(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException {
if (request.getParameter("submit_approve") != null) {
if (request.getParameter(SUBMIT_APPROVE) != null) {
//Delete the tasks
addApprovedProvenance(c, wfi);
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
} else if (request.getParameter("submit_reject") != null) {
} else if (request.getParameter(SUBMIT_REJECT) != null) {
// Make sure we indicate which page we want to process
request.setAttribute("page", REJECT_PAGE);
// We have pressed reject item, so take the user to a page where he can reject
return new ActionResult(ActionResult.TYPE.TYPE_PAGE);
} else if (request.getParameter("submit_decline_task") != null) {
} else if (request.getParameter(SUBMIT_DECLINE_TASK) != null) {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, OUTCOME_REJECT);
} else {

View File

@@ -8,6 +8,8 @@
package org.dspace.xmlworkflow.state.actions.userassignment;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.core.Context;
@@ -34,6 +36,11 @@ public class AssignAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
@Override
public List<String> getOptions() {
return new ArrayList<>();
}
public void generateTasks() {
}

View File

@@ -9,7 +9,9 @@ package org.dspace.xmlworkflow.state.actions.userassignment;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
@@ -112,6 +114,11 @@ public class AssignOriginalSubmitterAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
@Override
public List<String> getOptions() {
return new ArrayList<>();
}
/**
* Create a claimed task for the user IF this user doesn't have a claimed action for this workflow item
*

View File

@@ -9,6 +9,7 @@ package org.dspace.xmlworkflow.state.actions.userassignment;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -106,6 +107,11 @@ public class AutoAssignAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
@Override
public List<String> getOptions() {
return new ArrayList<>();
}
/**
* Create a claimed task for the user IF this user doesn't have a claimed action for this workflow item
*

View File

@@ -10,6 +10,7 @@ package org.dspace.xmlworkflow.state.actions.userassignment;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
@@ -67,6 +68,11 @@ public class ClaimAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
@Override
public List<String> getOptions() {
return new ArrayList<>();
}
@Override
public void alertUsersOnActivation(Context c, XmlWorkflowItem wfi, RoleMembers roleMembers)
throws IOException, SQLException {

View File

@@ -8,6 +8,8 @@
package org.dspace.xmlworkflow.state.actions.userassignment;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.core.Context;
@@ -37,6 +39,11 @@ public class InheritUsersAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
@Override
public List<String> getOptions() {
return new ArrayList<>();
}
@Override
public boolean isFinished(XmlWorkflowItem wfi) {
return false;

View File

@@ -7,14 +7,12 @@
*/
package org.dspace.xmlworkflow.state.actions.userassignment;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.xmlworkflow.RoleMembers;
import org.dspace.xmlworkflow.WorkflowConfigurationException;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.actions.ActionResult;
import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
@@ -34,12 +32,11 @@ public class NoUserSelectionAction extends UserSelectionAction {
}
@Override
public void regenerateTasks(Context c, XmlWorkflowItem wfi, RoleMembers roleMembers) throws SQLException {
public void regenerateTasks(Context c, XmlWorkflowItem wfi, RoleMembers roleMembers) {
}
@Override
public boolean isValidUserSelection(Context context, XmlWorkflowItem wfi, boolean hasUI)
throws WorkflowConfigurationException, SQLException {
public boolean isValidUserSelection(Context context, XmlWorkflowItem wfi, boolean hasUI) {
return true;
}
@@ -49,12 +46,16 @@ public class NoUserSelectionAction extends UserSelectionAction {
}
@Override
public void activate(Context c, XmlWorkflowItem wf) throws SQLException, IOException {
public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException {
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request) {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
@Override
public List<String> getOptions() {
return new ArrayList<>();
}
}

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 #
##########################
# Spring boot test by default mock the server on the localhost (80)
dspace.baseUrl = http://localhost
# Spring boot test: by default mock the server on the localhost (80)
dspace.server.url = http://localhost
# DSpace installation directory.
# This is the location where you want to install DSpace.

View File

@@ -21,92 +21,18 @@
autowire="byType"
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.
To mint DOIs you need a registration agency. The DOIIdentifierProvider
maintains the doi database table and handling of DSpaceObject. It uses
a DOIConnector that handles all API calls to your DOI registration
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"
class="org.dspace.identifier.DOIIdentifierProvider"
scope="singleton">
<property name="configurationService"
ref="org.dspace.services.ConfigurationService"/>
<property name="DOIConnector"
ref="org.dspace.identifier.doi.DOIConnector"/>
<!-- NOTE: A DOIConnector is not configured here because it is mocked in the tests themselves -->
<!--<property name="DOIConnector"
ref="org.dspace.identifier.doi.DOIConnector"/>-->
</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>

View File

@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id="claimactionAPI" class="org.dspace.xmlworkflow.state.actions.userassignment.ClaimAction" scope="prototype"/>
<bean id="reviewactionAPI" class="org.dspace.xmlworkflow.state.actions.processingaction.ReviewAction" scope="prototype"/>
<bean id="editactionAPI" class="org.dspace.xmlworkflow.state.actions.processingaction.AcceptEditRejectAction" scope="prototype"/>
<bean id="finaleditactionAPI" class="org.dspace.xmlworkflow.state.actions.processingaction.FinalEditAction" scope="prototype"/>
<bean id="singleuserreviewactionAPI" class="org.dspace.xmlworkflow.state.actions.processingaction.SingleUserReviewAction" scope="prototype"/>
<bean id="selectrevieweractionAPI" class="org.dspace.xmlworkflow.state.actions.processingaction.SelectReviewerAction" scope="prototype">
<property name="role" ref="scoreAssignedReviewer"/>
</bean>
<bean id="scorereviewactionAPI" class="org.dspace.xmlworkflow.state.actions.processingaction.ScoreReviewAction" scope="prototype"/>
<bean id="evaluationactionAPI" class="org.dspace.xmlworkflow.state.actions.processingaction.ScoreEvaluationAction" scope="prototype">
<property name="minimumAcceptanceScore" value="50" />
</bean>
<bean id="autoassignactionAPI" class="org.dspace.xmlworkflow.state.actions.userassignment.AutoAssignAction" scope="prototype"/>
<bean id="noUserSelectionActionAPI" class="org.dspace.xmlworkflow.state.actions.userassignment.NoUserSelectionAction" scope="prototype"/>
<bean id="assignoriginalsubmitteractionAPI" class="org.dspace.xmlworkflow.state.actions.userassignment.AssignOriginalSubmitterAction" scope="prototype"/>
<bean id="reviewaction" class="org.dspace.xmlworkflow.state.actions.WorkflowActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="reviewaction"/>
<property name="processingAction" ref="reviewactionAPI"/>
<property name="requiresUI" value="true"/>
</bean>
<bean id="editaction" class="org.dspace.xmlworkflow.state.actions.WorkflowActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="editaction"/>
<property name="processingAction" ref="editactionAPI"/>
<property name="requiresUI" value="true"/>
</bean>
<bean id="finaleditaction" class="org.dspace.xmlworkflow.state.actions.WorkflowActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="finaleditaction"/>
<property name="processingAction" ref="finaleditactionAPI"/>
<property name="requiresUI" value="true"/>
</bean>
<!--Action for the select single reviewer workflow -->
<bean id="selectrevieweraction" class="org.dspace.xmlworkflow.state.actions.WorkflowActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="selectrevieweraction"/>
<property name="processingAction" ref="selectrevieweractionAPI"/>
<property name="requiresUI" value="true"/>
</bean>
<bean id="singleuserreviewaction" class="org.dspace.xmlworkflow.state.actions.WorkflowActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="singleuserreviewaction"/>
<property name="processingAction" ref="singleuserreviewactionAPI"/>
<property name="requiresUI" value="true"/>
</bean>
<bean id="scorereviewaction" class="org.dspace.xmlworkflow.state.actions.WorkflowActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="scorereviewaction"/>
<property name="processingAction" ref="scorereviewactionAPI" />
<property name="requiresUI" value="true"/>
</bean>
<!--Autmatic step that evaluates scores (workflow.score) and checks if they match the configured minimum for archiving -->
<bean id="evaluationaction" class="org.dspace.xmlworkflow.state.actions.WorkflowActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="evaluationaction"/>
<property name="processingAction" ref="evaluationactionAPI" />
<property name="requiresUI" value="false"/>
</bean>
<!--User selection actions-->
<bean id="claimaction" class="org.dspace.xmlworkflow.state.actions.UserSelectionActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="claimaction"/>
<property name="processingAction" ref="claimactionAPI"/>
<property name="requiresUI" value="true"/>
</bean>
<bean id="autoassignAction" class="org.dspace.xmlworkflow.state.actions.UserSelectionActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="autoassignAction"/>
<property name="processingAction" ref="autoassignactionAPI"/>
<property name="requiresUI" value="false"/>
</bean>
<bean id="noUserSelectionAction" class="org.dspace.xmlworkflow.state.actions.UserSelectionActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value="noUserSelectionAction"/>
<property name="processingAction" ref="noUserSelectionActionAPI"/>
<property name="requiresUI" value="false"/>
</bean>
<bean id="originalSubmitterAssignAction" class="org.dspace.xmlworkflow.state.actions.UserSelectionActionConfig" scope="prototype">
<constructor-arg type="java.lang.String" value=""/>
<property name="processingAction" ref="assignoriginalsubmitteractionAPI"/>
<property name="requiresUI" value="false"/>
</bean>
</beans>

View File

@@ -9,8 +9,8 @@
<util:map>
<entry key="defaultWorkflow"
value-ref="defaultWorkflow"/>
<entry key="123456789/4" value-ref="selectSingleReviewer"/>
<!-- <entry key="123456789/5" value-ref="scoreReview"/>-->
<entry key="123456789/workflow-test-1" value-ref="selectSingleReviewer"/>
<!-- <entry key="123456789/5" value-ref="scoreReview"/>-->
</util:map>
</property>
</bean>

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.TimeZone;
import mockit.integration.junit4.JMockit;
import org.apache.logging.log4j.Logger;
import org.dspace.app.util.MockUtil;
import org.dspace.servicemanager.DSpaceKernelImpl;
import org.dspace.servicemanager.DSpaceKernelInit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
/**
* DSpace Unit Tests need to initialize the DSpace Kernel / Service Mgr
@@ -39,7 +38,7 @@ import org.junit.runner.RunWith;
* @see AbstractIntegrationTest
*/
@Ignore
@RunWith(JMockit.class)
@RunWith(MockitoJUnitRunner.class)
public class AbstractDSpaceTest {
/**
@@ -86,11 +85,9 @@ public class AbstractDSpaceTest {
kernelImpl = DSpaceKernelInit.getKernel(null);
if (!kernelImpl.isRunning()) {
// 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
}
// Initialize mock Util class (allows Util.getSourceVersion() to work in Unit tests)
new MockUtil();
} catch (IOException ex) {
log.error("Error initializing tests", ex);
fail("Error initializing tests: " + ex.getMessage());

View File

@@ -11,16 +11,18 @@ import static org.junit.Assert.fail;
import java.sql.SQLException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.discovery.MockIndexEventConsumer;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.factory.EPersonServiceFactory;
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.junit.After;
import org.junit.Before;
@@ -86,9 +88,6 @@ public class AbstractUnitTest extends AbstractDSpaceTest {
fail("Error initializing database: " + se.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);
context.restoreAuthSystemState();
// Ensure all tests run with Solr indexing disabled
disableSolrIndexing();
} catch (AuthorizeException ex) {
log.error("Error creating initial eperson or default groups", ex);
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 {
// If context still valid, abort it
if (c != null && c.isValid()) {
c.complete();
c.abort();
}
// Cleanup Context object by setting it to null
@@ -168,4 +171,23 @@ public class AbstractUnitTest extends AbstractDSpaceTest {
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.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
@@ -47,7 +45,6 @@ import org.xmlunit.diff.ComparisonFormatter;
import org.xmlunit.diff.DefaultComparisonFormatter;
import org.xmlunit.diff.Diff;
import org.xmlunit.diff.Difference;
import org.xmlunit.util.Predicate;
/**
* 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(
"description",
"intro",
@@ -330,5 +327,5 @@ public class StructBuilderIT
String type = node.getLocalName();
return ! dontCare.contains(type);
}
}
}*/
}

View File

@@ -8,7 +8,7 @@
package org.dspace.app.util;
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 java.util.ArrayList;
@@ -24,12 +24,8 @@ import org.dspace.core.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class GoogleBitstreamComparatorTest extends AbstractUnitTest {
@Mock

View File

@@ -14,7 +14,9 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.List;
import com.google.common.base.Splitter;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException;
@@ -85,7 +87,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
} 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.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/");
assertEquals("Pdf", urlSplitted[urlSplitted.length - 1]);
List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("Pdf", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -154,8 +157,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/");
assertEquals("size9", urlSplitted[urlSplitted.length - 1]);
List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("size9", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -189,8 +192,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/");
assertEquals("first", urlSplitted[urlSplitted.length - 1]);
List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("first", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -225,8 +228,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/");
assertEquals("primary", urlSplitted[urlSplitted.length - 1]);
List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("primary", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -261,8 +264,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/");
assertEquals("large", urlSplitted[urlSplitted.length - 1]);
List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("large", urlSplitted.get(urlSplitted.size() - 1));
}
@@ -285,7 +288,7 @@ public class GoogleMetadataTest extends AbstractUnitTest {
@Test
public void testGetPDFURLWithNoBitstreams() throws Exception {
context.turnOffAuthorisationSystem();
Bundle bundle = ContentServiceFactory.getInstance().getBundleService().create(context, it, "ORIGINAL");
ContentServiceFactory.getInstance().getBundleService().create(context, it, "ORIGINAL");
context.restoreAuthSystemState();
context.commit();
@@ -319,8 +322,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
String[] urlSplitted = gm.getPDFURL().get(0).split("/");
assertEquals("small", urlSplitted[urlSplitted.length - 1]);
List<String> urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
assertEquals("small", urlSplitted.get(urlSplitted.size() - 1));
}
@After
@@ -334,12 +337,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
community = context.reloadEntity(community);
ContentServiceFactory.getInstance().getCommunityService().delete(context, community);
community = null;
} catch (SQLException e) {
e.printStackTrace();
} catch (AuthorizeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
throw new AssertionError("Error occurred in destroy()", e);
}
it = null;
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"));
}
private ArrayList<String> getAllIp4Except(ArrayList<String> exceptions) {
// Commented out as this is currently not used in tests
/*private ArrayList<String> getAllIp4Except(ArrayList<String> exceptions) {
int d1 = 0;
int d2 = 0;
int d3 = 0;
@@ -284,7 +284,7 @@ public class IPMatcherTest {
}
}
return ips;
}
}*/
private void verifyAllIp4Except(ArrayList<String> exceptions, boolean asserted, IPMatcher ipMatcher)
throws IPMatcherException {

View File

@@ -90,8 +90,7 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
@Test
public void testauthorizeMethodRespectSpecialGroups() {
EPerson eperson1;
EPerson eperson2;
EPerson eperson;
Group group1;
Community dso;
@@ -99,7 +98,7 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
context.turnOffAuthorisationSystem();
// create an eperson and a group
eperson1 = ePersonService.create(context);
eperson = ePersonService.create(context);
group1 = groupService.create(context);
// A group has to have a name, otherwise there are queries that break
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
// is allowed for the user
authorizeService.addPolicy(context, dso, Constants.ADD, group1);
context.setCurrentUser(eperson1);
context.setCurrentUser(eperson);
context.setSpecialGroup(group1.getID());
context.commit();
} catch (SQLException | AuthorizeException ex) {
throw new RuntimeException(ex);
throw new AssertionError(ex);
} finally {
context.restoreAuthSystemState();
}
try {
Assert.assertTrue(authorizeService.authorizeActionBoolean(context, eperson1, dso, Constants.ADD, true));
Assert.assertTrue(authorizeService.authorizeActionBoolean(context, eperson, dso, Constants.ADD, true));
} 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.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
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.service.BitstreamFormatService;
import org.dspace.core.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* 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()
.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
@@ -75,6 +81,13 @@ public class BitstreamFormatTest extends AbstractUnitTest {
try {
bf = bitstreamFormatService.find(context, 5);
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) {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -199,11 +212,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test
public void testCreateAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full Admin perms
authorizeService.isAdmin((Context) any);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
BitstreamFormat found = bitstreamFormatService.create(context);
assertThat("testCreate 0", found, notNullValue());
@@ -219,13 +229,10 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full Admin perms
authorizeService.isAdmin((Context) any);
result = false;
}};
// Disalow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
BitstreamFormat found = bitstreamFormatService.create(context);
bitstreamFormatService.create(context);
fail("Exception should have been thrown");
}
@@ -442,11 +449,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full Admin perms
authorizeService.isAdmin((Context) any);
result = false;
}};
// Disallow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
bitstreamFormatService.update(context, bf);
fail("Exception should have been thrown");
@@ -457,11 +461,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test
public void testUpdateAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full Admin perms
authorizeService.isAdmin((Context) any);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String desc = "Test description";
String oldDescription = bf.getDescription();
@@ -478,11 +479,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testDeleteNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full Admin perms
authorizeService.isAdmin((Context) any);
result = false;
}};
// Disallow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
bitstreamFormatService.delete(context, bf);
fail("Exception should have been thrown");
@@ -493,11 +491,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test
public void testDeleteAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full Admin perms
authorizeService.isAdmin((Context) any);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
BitstreamFormat bitstreamFormat = bitstreamFormatService.create(context);
int toDeleteIdentifier = bitstreamFormat.getID();
@@ -511,11 +506,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = IllegalArgumentException.class)
public void testDeleteUnknown() throws SQLException, AuthorizeException {
new NonStrictExpectations(AuthorizeServiceImpl.class) {{
// Allow full Admin perms
authorizeService.isAdmin((Context) any);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
bitstreamFormatService.delete(context, bunknown);
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.assertTrue;
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.FileInputStream;
@@ -23,9 +28,9 @@ import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService;
import org.dspace.core.Constants;
@@ -33,6 +38,7 @@ import org.dspace.core.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit Tests for class Bitstream
@@ -54,6 +60,12 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/
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
* initialize resources required for the tests.
@@ -67,10 +79,18 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
super.init();
try {
//we have to create a new bitstream in the database
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString());
this.bs = bitstreamService.create(context, new FileInputStream(f));
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) {
log.error("IO Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -146,11 +166,10 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRegister() throws IOException, SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow general Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(any(Context.class), any(Bitstream.class),
eq(Constants.WRITE));
int assetstore = 0;
File f = new File(testProps.get("test.bitstream").toString());
Bitstream registered = bitstreamService.register(context, assetstore, f.getName());
@@ -366,13 +385,9 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNotAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Bitstream WRITE perms
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = new AuthorizeException();
// Disallow Bitstream WRITE permissions
doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, bs, Constants.WRITE);
}};
//TODO: we need to verify the update, how?
bitstreamService.update(context, bs);
}
@@ -382,13 +397,8 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUpdateAdmin() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bitstream WRITE perms
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, bs, Constants.WRITE);
//TODO: we need to verify the update, how?
bitstreamService.update(context, bs);
@@ -399,21 +409,18 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
*/
@Test
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
// tests is unpredictable we don't want to delete the global bitstream
context.ignoreAuthorization();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream delBS = bitstreamService.create(context, new FileInputStream(f));
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
assertFalse("testIsDeleted 0", delBS.isDeleted());
@@ -431,12 +438,8 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
@Test
public void testRetrieveCanRead() throws IOException, SQLException,
AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bitstream READ perms
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.READ);
result = null;
}};
// Allow Bitstream READ permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, bs, Constants.READ);
assertThat("testRetrieveCanRead 0", bitstreamService.retrieve(context, bs), notNullValue());
}
@@ -447,12 +450,8 @@ public class BitstreamTest extends AbstractDSpaceObjectTest {
@Test(expected = AuthorizeException.class)
public void testRetrieveNoRead() throws IOException, SQLException,
AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Bitstream READ perms
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.READ);
result = new AuthorizeException();
}};
// Disallow Bitstream READ permissions
doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, bs, Constants.READ);
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.assertTrue;
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.FileInputStream;
@@ -26,16 +31,17 @@ import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import mockit.NonStrictExpectations;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Units tests for class Bundle
@@ -56,6 +62,11 @@ public class BundleTest extends AbstractDSpaceObjectTest {
private Collection collection;
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
@@ -79,6 +90,15 @@ public class BundleTest extends AbstractDSpaceObjectTest {
//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 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) {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -155,14 +175,9 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreate() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {
{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
}
};
// Allow Item ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.ADD);
Bundle created = bundleService.create(context, item, "testCreateBundle");
//the item created by default has no name nor type set
assertThat("testCreate 0", created, notNullValue());
@@ -221,16 +236,14 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testSetPrimaryBitstreamID() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {
{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}
};
// Allow Item WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bundleService.addBitstream(context, b, bs);
@@ -243,16 +256,14 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUnsetPrimaryBitstreamID() throws IOException, SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {
{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}
};
// Allow Item WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
//set a value different than default
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
@@ -279,27 +290,25 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetBitstreamByName() throws FileNotFoundException, SQLException, IOException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
String name = "name";
//by default there is no bitstream
assertThat("testGetHandle 0", bundleService.getBitstreamByName(b, name), nullValue());
//let's add a bitstream
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, name);
bundleService.addBitstream(context, b, bs);
bundleService.update(context, b);
context.restoreAuthSystemState();
assertThat("testGetHandle 1", bundleService.getBitstreamByName(b, name), notNullValue());
assertThat("testGetHandle 2", bundleService.getBitstreamByName(b, name), equalTo(bs));
assertThat("testGetHandle 3", bundleService.getBitstreamByName(b, name).getName(), equalTo(name));
@@ -310,27 +319,25 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetBitstreams() throws FileNotFoundException, SQLException, IOException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
//default bundle has no bitstreams
assertThat("testGetBitstreams 0", b.getBitstreams(), notNullValue());
assertThat("testGetBitstreams 1", b.getBitstreams().size(), equalTo(0));
//let's add a bitstream
context.turnOffAuthorisationSystem();
String name = "name";
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, name);
bundleService.addBitstream(context, b, bs);
context.restoreAuthSystemState();
assertThat("testGetBitstreams 2", b.getBitstreams(), notNullValue());
assertThat("testGetBitstreams 3", b.getBitstreams().size(), equalTo(1));
assertThat("testGetBitstreams 4", b.getBitstreams().get(0).getName(), equalTo(name));
@@ -352,16 +359,11 @@ public class BundleTest extends AbstractDSpaceObjectTest {
@Test(expected = AuthorizeException.class)
public void testCreateBitstreamNoAuth()
throws FileNotFoundException, AuthorizeException, SQLException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = new AuthorizeException();
}};
// Disallow Bundle ADD permissions
doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
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");
}
@@ -370,16 +372,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateBitstreamAuth() throws FileNotFoundException, AuthorizeException, SQLException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow Item WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
String name = "name";
File f = new File(testProps.get("test.bitstream").toString());
@@ -395,17 +394,12 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRegisterBitstreamNoAuth() throws AuthorizeException, IOException, SQLException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = new AuthorizeException();
}};
// Disallow Bundle ADD permissions
doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
int assetstore = 0; //default assetstore
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");
}
@@ -414,16 +408,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRegisterBitstreamAuth() throws AuthorizeException, IOException, SQLException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow Item WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
int assetstore = 0; //default assetstore
String name = "name bitstream";
@@ -440,13 +431,8 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testAddBitstreamNoAuth() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = new AuthorizeException();
}};
// Disallow Bundle ADD permissions
doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// create a new Bitstream to add to Bundle
File f = new File(testProps.get("test.bitstream").toString());
@@ -461,16 +447,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testAddBitstreamAuth() throws SQLException, AuthorizeException, FileNotFoundException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow Item WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
@@ -487,17 +470,15 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveBitstreamNoAuth() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow Bundle REMOVE perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.REMOVE);
result = new AuthorizeException();
}};
// Disallow Bundle ADD permissions
doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.REMOVE);
File f = new File(testProps.get("test.bitstream").toString());
context.turnOffAuthorisationSystem();
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, "name");
context.restoreAuthSystemState();
bundleService.removeBitstream(context, b, bs);
fail("Exception should have been thrown");
}
@@ -507,28 +488,26 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveBitstreamAuth() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms (to create a new Bitstream and add it)
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
// Allow Bundle REMOVE perms (to test remove)
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.REMOVE);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
authorizeService.authorizeAction(context, (Bitstream) any,
Constants.DELETE);
result = null;
}};
// Allow Item WRITE permissions (to create a new bitstream)
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD permissions (to create a new bitstream)
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bundle REMOVE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.REMOVE);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
// Allow Bitstream DELETE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.DELETE));
// Create a new Bitstream to test with
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bundleService.addBitstream(context, b, bs);
context.restoreAuthSystemState();
bundleService.removeBitstream(context, b, bs);
assertThat("testRemoveBitstreamAuth 0", bundleService.getBitstreamByName(b, bs.getName()), nullValue());
}
@@ -549,19 +528,10 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testDelete() throws SQLException, AuthorizeException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms (to create a new Bitstream and add it)
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
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;
}};
// Allow Item REMOVE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.REMOVE);
// Allow Bundle DELETE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.DELETE);
UUID id = b.getID();
itemService.removeBundle(context, item, b);
@@ -676,17 +646,18 @@ public class BundleTest extends AbstractDSpaceObjectTest {
@Test
public void testSetOrder() throws SQLException, AuthorizeException, FileNotFoundException, IOException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Bundle ADD perms
authorizeService.authorizeAction((Context) any, (Bundle) any,
Constants.ADD);
result = null;
authorizeService.authorizeAction((Context) any, (Bitstream) any,
Constants.WRITE);
result = null;
}};
// Allow Item WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
// Allow Bundle ADD permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// Allow Bundle WRITE permissions
doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.WRITE);
// Allow Bitstream WRITE permissions
doNothing().when(authorizeServiceSpy)
.authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
// Create three Bitstreams to test ordering with. Give them different names
context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, "bitstream1");
@@ -697,6 +668,7 @@ public class BundleTest extends AbstractDSpaceObjectTest {
Bitstream bs3 = bitstreamService.create(context, new FileInputStream(f));
bs3.setName(context, "bitstream3");
bundleService.addBitstream(context, b, bs3);
context.restoreAuthSystemState();
// Assert Bitstreams are in the order added
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 org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -28,11 +27,6 @@ import org.junit.Test;
* @author pvillega
*/
public class DCDateTest {
/**
* log4j category
*/
private static Logger log = org.apache.logging.log4j.LogManager.getLogger(DCDateTest.class);
/**
* Object to use in the tests
*/

View File

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

View File

@@ -8,7 +8,7 @@
package org.dspace.content;
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.when;
@@ -23,7 +23,7 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class EntityTypeServiceImplTest {

View File

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

View File

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

View File

@@ -16,7 +16,6 @@ import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractIntegrationTest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.factory.ContentServiceFactory;
@@ -37,11 +36,6 @@ import org.junit.Test;
* @author pvillega
*/
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 CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();

View File

@@ -7,7 +7,6 @@
*/
package org.dspace.content;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.junit.After;
import org.junit.Before;
@@ -23,11 +22,6 @@ import org.junit.Test;
*/
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
* 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.assertThat;
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.FileInputStream;
@@ -21,24 +23,22 @@ import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService;
import org.dspace.content.service.InstallItemService;
import org.dspace.content.service.ItemService;
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.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit Tests for class InstallItem
@@ -57,6 +57,12 @@ public class InstallItemTest extends AbstractUnitTest {
private Collection collection;
private Community owningCommunity;
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/**
* log4j category
*/
@@ -78,6 +84,14 @@ public class InstallItemTest extends AbstractUnitTest {
this.owningCommunity = communityService.create(null, context);
this.collection = collectionService.create(context, owningCommunity);
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) {
log.error("SQL Error in init", ex);
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
@Test(expected = AuthorizeException.class)
public void testInstallItem_invalidHandle() throws Exception {
//Default to Full-Admin rights
new NonStrictExpectations(authorizeService.getClass()) {{
// 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;
}};
// Allow full Admin rights
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String handle = "123456789/56789";
// create two items for tests
context.turnOffAuthorisationSystem();
WorkspaceItem is = workspaceItemService.create(context, collection, false);
WorkspaceItem is2 = workspaceItemService.create(context, collection, false);
context.restoreAuthSystemState();
//Test assigning the same Handle to two different items
String handle = "123456789/56789";
installItemService.installItem(context, is, handle);
// Assigning the same handle again should throw a RuntimeException
thrown.expect(RuntimeException.class);
installItemService.installItem(context, is2, handle);
fail("Exception expected");
}

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -104,11 +104,11 @@ public class LicenseUtilsTest extends AbstractUnitTest {
@Test
public void testGetLicenseText_5args() throws SQLException, AuthorizeException, IOException {
//parameters for the test
Locale locale = null;
Collection collection = null;
Item item = null;
EPerson person = null;
Map<String, Object> additionalInfo = null;
Locale locale;
Collection collection;
Item item;
EPerson person;
Map<String, Object> additionalInfo;
// 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
@@ -195,10 +195,10 @@ public class LicenseUtilsTest extends AbstractUnitTest {
@Test
public void testGetLicenseText_4args() throws SQLException, AuthorizeException, IOException {
//parameters for the test
Locale locale = null;
Collection collection = null;
Item item = null;
EPerson person = null;
Locale locale;
Collection collection;
Item item;
EPerson person;
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 ";

View File

@@ -13,20 +13,23 @@ import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.sql.SQLException;
import java.util.List;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit Tests for class MetadataFieldTest
@@ -66,6 +69,12 @@ public class MetadataFieldTest extends AbstractUnitTest {
.getMetadataSchemaService();
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
* initialize resources required for the tests.
@@ -90,6 +99,14 @@ public class MetadataFieldTest extends AbstractUnitTest {
}
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) {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -173,11 +190,9 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test
public void testSetSchema() throws NonUniqueMetadataException, SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full admin permissions
authorizeService.isAdmin(context);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
MetadataSchema newSchema = metadataSchemaService.create(context, "testSetSchema", "testSetSchemaNS");
mf.setMetadataSchema(newSchema);
assertThat("testSetSchemaID 0", mf.getMetadataSchema(), equalTo(newSchema));
@@ -206,11 +221,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test
public void testCreateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full admin permissions
authorizeService.isAdmin(context);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String elem = "elem1";
String qual = "qual1";
@@ -225,12 +237,6 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String elem = "elem1";
String qual = "qual1";
metadataFieldService.create(context, dcSchema, elem, qual, null);
@@ -242,11 +248,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test(expected = NonUniqueMetadataException.class)
public void testCreateRepeated() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full admin permissions
authorizeService.isAdmin(context);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String elem = element;
String qual = qualifier;
@@ -310,11 +313,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test
public void testUpdateAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full admin permissions
authorizeService.isAdmin(context);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String elem = "elem2";
String qual = "qual2";
@@ -330,12 +330,6 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String elem = "elem2";
String qual = "qual2";
MetadataField m = metadataFieldService.create(context, dcSchema, elem, qual, null);
@@ -348,11 +342,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test(expected = NonUniqueMetadataException.class)
public void testUpdateRepeated() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full admin permissions
authorizeService.isAdmin(context);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String elem = element;
String qual = qualifier;
@@ -369,11 +360,8 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test
public void testDeleteAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow full admin permissions
authorizeService.isAdmin(context);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String elem = "elem3";
String qual = "qual3";
@@ -390,12 +378,6 @@ public class MetadataFieldTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testDeleteNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
String elem = "elem3";
String qual = "qual3";
MetadataField m = metadataFieldService.create(context, dcSchema, elem, qual, null);

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