Merge remote-tracking branch 'origin/master' into missingParameterException-DS-4428

This commit is contained in:
Andrea Bollini
2020-02-19 19:11:58 +01:00
305 changed files with 4635 additions and 6017 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

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

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

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

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

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

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

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

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

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

@@ -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,11 +229,8 @@ 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);
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,13 +359,8 @@ 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));
@@ -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,13 +394,8 @@ 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());
@@ -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

@@ -27,7 +27,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 {

View File

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

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

File diff suppressed because it is too large Load Diff

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);

View File

@@ -14,18 +14,21 @@ 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.MetadataSchemaService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit Tests for class MetadataSchema
@@ -47,6 +50,12 @@ public class MetadataSchemaTest extends AbstractUnitTest {
protected MetadataSchemaService metadataSchemaService = ContentServiceFactory.getInstance()
.getMetadataSchemaService();
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/**
* This method will be run before every test as per @Before. It will
* initialize resources required for the tests.
@@ -60,6 +69,13 @@ public class MetadataSchemaTest extends AbstractUnitTest {
super.init();
try {
this.ms = metadataSchemaService.find(context, MetadataSchemaEnum.DC.getName());
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded object services
// (To ensure these services use the spy instead of the real service)
ReflectionTestUtils.setField(metadataSchemaService, "authorizeService", authorizeServiceSpy);
} catch (SQLException ex) {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -130,11 +146,8 @@ public class MetadataSchemaTest 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 namespace = "namespace";
String name = "name";
@@ -149,12 +162,6 @@ public class MetadataSchemaTest 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 namespace = "namespace";
String name = "name";
metadataSchemaService.create(context, name, namespace);
@@ -166,11 +173,8 @@ public class MetadataSchemaTest 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 namespace = ms.getNamespace();
String name = ms.getName();
@@ -194,11 +198,8 @@ public class MetadataSchemaTest 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 namespace = "namespace2";
String name = "name2";
@@ -215,12 +216,6 @@ public class MetadataSchemaTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Disallow full admin permissions
authorizeService.isAdmin(context);
result = false;
}};
metadataSchemaService.update(context, ms);
fail("Exception expected");
}
@@ -230,11 +225,8 @@ public class MetadataSchemaTest 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 namespace = ms.getNamespace();
String name = ms.getName();
@@ -251,11 +243,8 @@ public class MetadataSchemaTest 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 namespace = "namespace3";
String name = "name3";
@@ -272,12 +261,6 @@ public class MetadataSchemaTest 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 namespace = "namespace3";
String name = "name3";
MetadataSchema m = metadataSchemaService.create(context, name, namespace);

View File

@@ -28,7 +28,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 RelationshipServiceImplTest {

View File

@@ -26,7 +26,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 RelationshipTypeTest {

View File

@@ -141,7 +141,7 @@ public class SiteTest extends AbstractUnitTest {
*/
@Test
public void testGetURL() {
assertThat("testGetURL 0", s.getURL(), equalTo(ConfigurationManager.getProperty("dspace.url")));
assertThat("testGetURL 0", s.getURL(), equalTo(ConfigurationManager.getProperty("dspace.ui.url")));
}
}

View File

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

View File

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

View File

@@ -22,9 +22,8 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.dspace.AbstractIntegrationTest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
@@ -75,7 +74,7 @@ import org.junit.rules.TemporaryFolder;
*
* @author Tim Donohue
*/
public class ITDSpaceAIP extends AbstractUnitTest {
public class ITDSpaceAIP extends AbstractIntegrationTest {
/**
* log4j category
*/
@@ -295,10 +294,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
// Override default value of configured temp directory to point at our
// JUnit TemporaryFolder. This ensures Crosswalk classes like RoleCrosswalk
// store their temp files in a place where JUnit can clean them up automatically.
new NonStrictExpectations(configService.getClass()) {{
configService.getProperty("upload.temp.dir");
result = uploadTempFolder.getRoot().getAbsolutePath();
}};
configService.setProperty("upload.temp.dir", uploadTempFolder.getRoot().getAbsolutePath());
try {
context = new Context();
@@ -322,13 +318,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreCommunityHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreCommunityHierarchy() - BEGIN");
// Locate the top level community (from our test data)
@@ -378,13 +367,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreRestrictedCommunity() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreRestrictedCommunity() - BEGIN");
// Locate the top-level Community (as a parent)
@@ -457,13 +439,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testReplaceCommunityHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testReplaceCommunityHierarchy() - BEGIN");
// Locate the top level community (from our test data)
@@ -535,13 +510,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testReplaceCommunityOnly() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Community WRITE perms
authorizeService.authorizeAction((Context) any, (Community) any,
Constants.WRITE, true);
result = null;
}};
log.info("testReplaceCommunityOnly() - BEGIN");
// Locate the top level community (from our test data)
@@ -575,13 +543,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreCollectionHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreCollectionHierarchy() - BEGIN");
// Locate the collection (from our test data)
@@ -620,13 +581,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreRestrictedCollection() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreRestrictedCollection() - BEGIN");
// Locate the top-level Community (as a parent)
@@ -699,13 +653,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testReplaceCollectionHierarchy() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy you really need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testReplaceCollectionHierarchy() - BEGIN");
// Locate the collection (from our test data)
@@ -759,13 +706,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testReplaceCollectionOnly() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Collection WRITE perms
authorizeService.authorizeAction((Context) any, (Collection) any,
Constants.WRITE, true);
result = null;
}};
log.info("testReplaceCollectionOnly() - BEGIN");
// Locate the collection (from our test data)
@@ -801,13 +741,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreItem() - BEGIN");
// Locate the item (from our test data)
@@ -870,13 +803,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreRestrictedItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreRestrictedItem() - BEGIN");
// Locate the test Collection (as a parent)
@@ -948,13 +874,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreItemNoPolicies() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testRestoreItemNoPolicies() - BEGIN");
// Locate the test Collection (as a parent)
@@ -1009,13 +928,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testReplaceItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
}};
log.info("testReplaceItem() - BEGIN");
// Locate the item (from our test data)
@@ -1049,17 +961,6 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*/
@Test
public void testRestoreMappedItem() throws Exception {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Full Admin permissions. Since we are working with an object
// hierarchy (Items/Bundles/Bitstreams) you need full admin rights
authorizeService.isAdmin((Context) any);
result = true;
authorizeService.authorizeAction(context, (Collection) any, Constants.REMOVE);
result = null;
authorizeService.authorizeAction(context, (Collection) any, Constants.ADD);
result = null;
}};
log.info("testRestoreMappedItem() - BEGIN");
// Get a reference to our test mapped Item
@@ -1105,7 +1006,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
* to avoid having to rewrite this code into several tests.
*
* @param dso DSpaceObject to create AIP(s) for
* @param pkParams any special PackageParameters to pass (if any)
* @param pkgParams any special PackageParameters to pass (if any)
* @param recursive whether to recursively create AIPs or just a single AIP
* @return exported root AIP file
*/
@@ -1145,7 +1046,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*
* @param parent The DSpaceObject which will be the parent object of the newly restored object(s)
* @param aipFile AIP file to start restoration from
* @param pkParams any special PackageParameters to pass (if any)
* @param pkgParams any special PackageParameters to pass (if any)
* @param recursive whether to recursively restore AIPs or just a single AIP
*/
private void restoreFromAIP(DSpaceObject parent, File aipFile, PackageParameters pkgParams, boolean recursive)
@@ -1183,7 +1084,7 @@ public class ITDSpaceAIP extends AbstractUnitTest {
*
* @param dso The DSpaceObject to be replaced from AIP
* @param aipFile AIP file to start replacement from
* @param pkParams any special PackageParameters to pass (if any)
* @param pkgParams any special PackageParameters to pass (if any)
* @param recursive whether to recursively restore AIPs or just a single AIP
*/
private void replaceFromAIP(DSpaceObject dso, File aipFile, PackageParameters pkgParams, boolean recursive)

View File

@@ -22,7 +22,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 CollectedTest {

View File

@@ -22,7 +22,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 ConcatenateTest {

View File

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

View File

@@ -29,7 +29,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 RelatedTest {

View File

@@ -21,7 +21,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)

View File

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

View File

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

View File

@@ -13,21 +13,25 @@ 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 java.util.Locale;
import java.util.UUID;
import mockit.NonStrictExpectations;
import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService;
import org.dspace.eperson.service.GroupService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Perform some basic unit tests for Context Class
@@ -38,6 +42,33 @@ public class ContextTest extends AbstractUnitTest {
protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
/**
* Spy of AuthorizeService to use for tests
* (initialized / setup in @Before method)
*/
private AuthorizeService authorizeServiceSpy;
/**
* This method will be run before every test as per @Before. It will
* initialize resources required for the tests.
*
* Other methods can be annotated with @Before here or in subclasses
* but no execution order is guaranteed
*/
@Before
@Override
public void init() {
super.init();
// Initialize our spy of the autowired (global) authorizeService bean.
// This allows us to customize the bean's method return values in tests below
authorizeServiceSpy = spy(authorizeService);
// "Wire" our spy to be used by the current loaded object services
// (To ensure these services use the spy instead of the real service)
ReflectionTestUtils.setField(ePersonService, "authorizeService", authorizeServiceSpy);
ReflectionTestUtils.setField(groupService, "authorizeService", authorizeServiceSpy);
}
/**
* Test of getDBConnection method, of class Context.
*/
@@ -54,11 +85,8 @@ public class ContextTest extends AbstractUnitTest {
*/
@Test
public void testSetCurrentUser() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Admin permissions - needed to create a new EPerson
authorizeService.isAdmin((Context) any);
result = true;
}};
// Allow full Admin perms
when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
EPerson oldUser = context.getCurrentUser();
@@ -104,7 +132,6 @@ public class ContextTest extends AbstractUnitTest {
*/
@Test
public void testSetCurrentLocale() {
//Get previous value
Locale oldLocale = context.getCurrentLocale();
@@ -171,6 +198,9 @@ public class ContextTest extends AbstractUnitTest {
assertThat("testSetExtraLogInfo 0", context.getExtraLogInfo(), notNullValue());
assertThat("testSetExtraLogInfo 1", context.getExtraLogInfo(), equalTo(newValue));
//restore old value
context.setExtraLogInfo(oldValue);
}
/**
@@ -230,15 +260,12 @@ public class ContextTest extends AbstractUnitTest {
*/
@Test
public void testAbort() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Admin permissions - needed to create a new EPerson
authorizeService.isAdmin((Context) any);
result = true;
}};
// To test abort() we need a new Context object
Context instance = new Context();
// Allow full Admin perms (in new context)
when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
// Create a new EPerson (DO NOT COMMIT IT)
String createdEmail = "susie@email.com";
EPerson newUser = ePersonService.create(instance);
@@ -268,16 +295,12 @@ public class ContextTest extends AbstractUnitTest {
*/
@Test
public void testClose() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Admin permissions - needed to create a new EPerson
authorizeService.isAdmin((Context) any);
result = true;
}};
String createdEmail = "susie@email.com";
// To test close() we need a new Context object in a try-with-resources block
try (Context instance = new Context()) {
// Allow full Admin perms (in new context)
when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
// Create a new EPerson (DO NOT COMMIT IT)
EPerson newUser = ePersonService.create(instance);
@@ -411,15 +434,12 @@ public class ContextTest extends AbstractUnitTest {
*/
@Test
public void testGetSpecialGroups() throws SQLException, AuthorizeException {
new NonStrictExpectations(authorizeService.getClass()) {{
// Allow Admin permissions - needed to create a new Group
authorizeService.isAdmin((Context) any);
result = true;
}};
// To test special groups we need a new Context object
Context instance = new Context();
// Allow full Admin perms (in new context)
when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
// Create a new group & add it as a special group
Group group = groupService.create(instance);
UUID groupID = group.getID();

View File

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

View File

@@ -7,7 +7,7 @@
*/
package org.dspace.core;
import static com.sun.org.apache.bcel.internal.Constants.ACC_PUBLIC;
import static org.apache.bcel.Const.ACC_PUBLIC;
import static org.junit.Assert.assertTrue;
import java.io.File;
@@ -16,7 +16,7 @@ import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import com.sun.org.apache.bcel.internal.generic.ClassGen;
import org.apache.bcel.generic.ClassGen;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;

View File

@@ -0,0 +1,71 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.dspace.AbstractUnitTest;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.junit.Test;
/**
* Perform some basic unit tests for Utils Class
*
* @author tdonohue
*/
public class UtilsTest extends AbstractUnitTest {
/**
* Test of getHostName method, of class Utils
*/
@Test
public void testGetHostName() {
assertEquals("Test remove HTTP", "dspace.org",
Utils.getHostName("http://dspace.org"));
assertEquals("Test remove HTTPS", "dspace.org",
Utils.getHostName("https://dspace.org"));
assertEquals("Test remove trailing slash", "dspace.org",
Utils.getHostName("https://dspace.org/"));
assertEquals("Test remove www.", "dspace.org",
Utils.getHostName("https://www.dspace.org"));
assertEquals("Test keep other prefixes", "demo.dspace.org",
Utils.getHostName("https://demo.dspace.org"));
// This uses a bunch of reserved URI characters
assertNull("Test invalid URI returns null", Utils.getHostName("&+,?/@="));
}
/**
* Test of interpolateConfigsInString method, of class Utils
*/
@Test
public void testInterpolateConfigsInString() {
ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
// Add a new config to test with
String configName = "not.a.dspace.config.at.all";
String configValue = "demo.dspace.org";
configurationService.setProperty(configName, configValue);
// Create a string where the config is represented by ${variable}
String stringWithVariable = "The config " + configName + " has a value of ${" + configName + "}!";
String expectedValue = "The config " + configName + " has a value of " + configValue + "!";
assertEquals("Test config interpolation", expectedValue,
Utils.interpolateConfigsInString(stringWithVariable));
// remove the config we added
configurationService.setProperty(configName, null);
}
}

View File

@@ -29,7 +29,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 FullTextContentStreamsTest {

View File

@@ -1,32 +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.discovery;
import mockit.Mock;
import mockit.MockUp;
import org.dspace.core.Context;
import org.dspace.event.Event;
/**
* Dummy Discovery IndexEventConsumer. It essentially does nothing,
* as Discovery/Solr is not actively running during unit testing.
*
* @author tdonohue
*/
public class MockIndexEventConsumer
extends MockUp<IndexEventConsumer> {
@Mock
public void consume(Context ctx, Event event) throws Exception {
//do nothing - Solr is not running during unit testing, so we cannot index test content in Solr
}
@Mock
public void end(Context ctx) throws Exception {
//do nothing - Solr is not running during unit testing, so we cannot index test content in Solr
}
}

View File

@@ -13,6 +13,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeNotNull;
import static org.mockito.Mockito.mock;
import java.io.IOException;
import java.sql.SQLException;
@@ -36,6 +37,7 @@ import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService;
import org.dspace.identifier.doi.DOIConnector;
import org.dspace.identifier.factory.IdentifierServiceFactory;
import org.dspace.identifier.service.DOIService;
import org.dspace.services.ConfigurationService;
@@ -48,7 +50,7 @@ import org.junit.Before;
import org.junit.Test;
/**
* Tests for {@link DataCiteIdentifierProvider}.
* Tests for {@link DOIIdentifierProvider}.
*
* @author Mark H. Wood
* @author Pascal-Nicolas Becker
@@ -75,7 +77,7 @@ public class DOIIdentifierProviderTest
private static Community community;
private static Collection collection;
private static MockDOIConnector connector;
private static DOIConnector connector;
private DOIIdentifierProvider provider;
public DOIIdentifierProviderTest() {
@@ -111,7 +113,7 @@ public class DOIIdentifierProviderTest
config.setProperty(DOIIdentifierProvider.CFG_NAMESPACE_SEPARATOR,
NAMESPACE_SEPARATOR);
connector = new MockDOIConnector();
connector = mock(DOIConnector.class);
provider = DSpaceServicesFactory.getInstance().getServiceManager()
.getServiceByName(DOIIdentifierProvider.class.getName(),
@@ -140,7 +142,6 @@ public class DOIIdentifierProviderTest
public void destroy() {
community = null;
collection = null;
connector.reset();
connector = null;
provider = null;
super.destroy();
@@ -261,14 +262,13 @@ public class DOIIdentifierProviderTest
@Test
public void testSupports_valid_String() {
String[] validDOIs = new String[]
{
"10.5072/123abc-lkj/kljl",
PREFIX + "/" + NAMESPACE_SEPARATOR + "lkjljasd1234",
DOI.SCHEME + "10.5072/123abc-lkj/kljl",
"http://dx.doi.org/10.5072/123abc-lkj/kljl",
DOI.RESOLVER + "/10.5072/123abc-lkj/kljl"
};
String[] validDOIs = new String[] {
"10.5072/123abc-lkj/kljl",
PREFIX + "/" + NAMESPACE_SEPARATOR + "lkjljasd1234",
DOI.SCHEME + "10.5072/123abc-lkj/kljl",
"http://dx.doi.org/10.5072/123abc-lkj/kljl",
DOI.RESOLVER + "/10.5072/123abc-lkj/kljl"
};
for (String doi : validDOIs) {
assertTrue("DOI should be supported", provider.supports(doi));
@@ -277,13 +277,12 @@ public class DOIIdentifierProviderTest
@Test
public void testDoes_not_support_invalid_String() {
String[] invalidDOIs = new String[]
{
"11.5072/123abc-lkj/kljl",
"http://hdl.handle.net/handle/10.5072/123abc-lkj/kljl",
"",
null
};
String[] invalidDOIs = new String[] {
"11.5072/123abc-lkj/kljl",
"http://hdl.handle.net/handle/10.5072/123abc-lkj/kljl",
"",
null
};
for (String notADoi : invalidDOIs) {
assertFalse("Invalid DOIs shouldn't be supported",

View File

@@ -449,7 +449,7 @@ public class EZIDIdentifierProviderTest
// Evaluate
String target = (String) metadata.get("_target");
assertEquals("Generates correct _target metadatum",
config.getProperty("dspace.url") + "/handle/" + handle,
config.getProperty("dspace.ui.url") + "/handle/" + handle,
target);
assertTrue("Has title", metadata.containsKey("datacite.title"));
assertTrue("Has publication year", metadata.containsKey("datacite.publicationyear"));

View File

@@ -1,124 +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.identifier;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import mockit.Mock;
import mockit.MockUp;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Context;
import org.dspace.identifier.doi.DOIConnector;
import org.dspace.identifier.doi.DOIIdentifierException;
/**
* @author Pascal-Nicolas Becker (p dot becker at tu hyphen berlin dot de)
*/
public class MockDOIConnector
extends MockUp<DOIConnector>
implements org.dspace.identifier.doi.DOIConnector {
public Map<String, UUID> reserved;
public Map<String, UUID> registered;
public MockDOIConnector() {
reserved = new HashMap<String, UUID>();
registered = new HashMap<String, UUID>();
}
public void reset() {
reserved.clear();
registered.clear();
}
@Override
@Mock
public boolean isDOIReserved(Context context, String doi)
throws DOIIdentifierException {
return reserved.containsKey(doi);
}
@Override
@Mock
public boolean isDOIRegistered(Context context, String doi)
throws DOIIdentifierException {
return registered.containsKey(doi);
}
@Override
@Mock
public void deleteDOI(Context context, String doi)
throws DOIIdentifierException {
if (reserved.remove(doi) == null) {
throw new DOIIdentifierException("Trying to delete a DOI that was "
+ "never reserved!", DOIIdentifierException.DOI_DOES_NOT_EXIST);
}
registered.remove(doi);
}
@Override
@Mock
public void reserveDOI(Context context, DSpaceObject dso, String doi)
throws DOIIdentifierException {
UUID itemId = reserved.get(doi);
if (null != itemId) {
if (dso.getID().equals(itemId)) {
return;
} else {
throw new DOIIdentifierException("Trying to reserve a DOI that "
+ "is reserved for another object.",
DOIIdentifierException.MISMATCH);
}
}
reserved.put(doi, dso.getID());
}
@Override
@Mock
public void registerDOI(Context context, DSpaceObject dso, String doi)
throws DOIIdentifierException {
if (!reserved.containsKey(doi)) {
throw new DOIIdentifierException("Trying to register an unreserverd "
+ "DOI.", DOIIdentifierException.RESERVE_FIRST);
}
if (!reserved.get(doi).equals(dso.getID())) {
throw new DOIIdentifierException("Trying to register a DOI that is"
+ " reserved for another item.", DOIIdentifierException.MISMATCH);
}
if (registered.containsKey(doi)) {
if (registered.get(doi).equals(dso.getID())) {
return;
} else {
throw new DOIIdentifierException("Trying to register a DOI that "
+ "is registered for another item.",
DOIIdentifierException.MISMATCH);
}
}
registered.put(doi, dso.getID());
}
@Override
@Mock
public void updateMetadata(Context context, DSpaceObject dso, String doi)
throws DOIIdentifierException {
if (!reserved.containsKey(doi)) {
throw new DOIIdentifierException("Trying to update a DOI that is not "
+ "registered!", DOIIdentifierException.DOI_DOES_NOT_EXIST);
}
if (!reserved.get(doi).equals(dso.getID())) {
throw new DOIIdentifierException("Trying to update metadata of an "
+ "unreserved DOI.", DOIIdentifierException.DOI_DOES_NOT_EXIST);
}
}
}

View File

@@ -18,8 +18,6 @@ import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.statistics.util.DummyHttpServletRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Unit test class for the {@link ClientInfoServiceImpl} class which implements
@@ -27,7 +25,6 @@ import org.mockito.runners.MockitoJUnitRunner;
*
* @author tom dot desair at gmail dot com
*/
@RunWith(MockitoJUnitRunner.class)
public class ClientInfoServiceImplTest extends AbstractDSpaceTest {
private ClientInfoService clientInfoService;
@@ -162,4 +159,4 @@ public class ClientInfoServiceImplTest extends AbstractDSpaceTest {
assertFalse(clientInfoService.isUseProxiesEnabled());
}
}
}

View File

@@ -1,118 +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.statistics;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Continent;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.MaxMind;
import com.maxmind.geoip2.record.Postal;
import com.maxmind.geoip2.record.RepresentedCountry;
import com.maxmind.geoip2.record.Subdivision;
import com.maxmind.geoip2.record.Traits;
import mockit.Deencapsulation;
import mockit.Mock;
import mockit.MockUp;
/**
* Mock service to mock the location Lookup Service used by the SOLR statistics
* logger.
*/
public class FakeDatabaseReader
extends MockUp<DatabaseReader> {
FakeDatabaseReader() {
}
public FakeDatabaseReader(Object object) {
}
public FakeDatabaseReader $init(Builder builder) {
return this;
}
/*
@Override
public Location getLocation(String str) {
Location location = new Location();
location.countryCode = "US";
location.countryName = "United States";
location.region = "NY";
location.city = "New York";
location.postalCode = "10036";
location.latitude = 40.760498F;
location.longitude = -73.9933F;
location.dma_code = 501;
location.area_code = 212;
location.metro_code = 501;
return location;
}
*/
@Mock
public CityResponse city(InetAddress address) {
List<String> names = new ArrayList<>(1);
names.add("New York");
City city = new City(names, 1, 1, new HashMap());
Continent continent = new Continent();
names.clear();
names.add("United States");
Country country = new Country(names, 1, 1, "US", new HashMap());
Location location = new Location(1, 1, 40.760498D, -73.9933D, 501, 1, "EST");
MaxMind maxmind = new MaxMind();
Postal postal = new Postal("10036", 1);
RepresentedCountry representedCountry = new RepresentedCountry();
ArrayList<Subdivision> subdivisions = new ArrayList<>(0);
Traits traits = new Traits();
CityResponse response = new CityResponse(city, continent, country,
location, maxmind, postal, country, representedCountry,
subdivisions, traits);
return response;
}
public static class Builder
extends MockUp<DatabaseReader.Builder> {
public Builder() {}
/**
* Fake constructor.
* @param file ignored.
*/
@Mock
public void $init(File file) {
}
@Mock
public DatabaseReader build()
throws IOException {
return Deencapsulation.newUninitializedInstance(DatabaseReader.class);
}
}
}

View File

@@ -7,9 +7,26 @@
*/
package org.dspace.statistics;
import java.io.File;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Continent;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.MaxMind;
import com.maxmind.geoip2.record.Postal;
import com.maxmind.geoip2.record.RepresentedCountry;
import com.maxmind.geoip2.record.Traits;
import org.springframework.beans.factory.InitializingBean;
/**
@@ -17,7 +34,7 @@ import org.springframework.beans.factory.InitializingBean;
* <p>
* <strong>NOTE:</strong> this class is overridden by one <em>of the same name</em>
* defined in dspace-server-webapp and declared as a bean there.
* See {@code config/spring/api/Z-mock-services.xml}. Some kind of classpath
* See {@code test/data/dspaceFolder/config/spring/api/solr-services.xml}. Some kind of classpath
* magic makes this work.
*/
public class MockSolrLoggerServiceImpl
@@ -32,11 +49,31 @@ public class MockSolrLoggerServiceImpl
//We don't use SOLR in the tests of this module
solr = null;
new FakeDatabaseReader(); // Activate fake
new FakeDatabaseReader.Builder(); // Activate fake
File locationDb = File.createTempFile("GeoIP", ".db");
locationDb.deleteOnExit();
locationService = new DatabaseReader.Builder(locationDb).build();
// Mock GeoIP's DatabaseReader
DatabaseReader reader = mock(DatabaseReader.class);
// Ensure that any tests requesting a city() get a mock/fake CityResponse
when(reader.city(any(InetAddress.class))).thenReturn(mockCityResponse());
// Save this mock DatabaseReader to be used by SolrLoggerService
locationService = reader;
}
/**
* A mock/fake GeoIP CityResponse, which will be used for *all* test statistical requests
* @return faked CityResponse
*/
private CityResponse mockCityResponse() {
List<String> cityNames = new ArrayList<String>(Collections.singleton("New York"));
City city = new City(cityNames, 1, 1, new HashMap());
List<String> countryNames = new ArrayList<String>(Collections.singleton("United States"));
Country country = new Country(countryNames, 1, 1, "US", new HashMap());
Location location = new Location(1, 1, 40.760498D, -73.9933D, 501, 1, "EST");
Postal postal = new Postal("10036", 1);
return new CityResponse(city, new Continent(), country, location, new MaxMind(), postal,
country, new RepresentedCountry(), new ArrayList<>(0),
new Traits());
}
}

View File

@@ -10,25 +10,19 @@ package org.dspace.statistics.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import mockit.Mock;
import mockit.MockUp;
import org.dspace.AbstractDSpaceTest;
import org.dspace.core.factory.CoreServiceFactory;
import org.dspace.service.ClientInfoService;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.statistics.SolrLoggerServiceImpl;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
/**
* @author mwood
* @author frederic at atmire.com
*/
@RunWith(MockitoJUnitRunner.class)
public class SpiderDetectorServiceImplTest extends AbstractDSpaceTest {
private static final String NOT_A_BOT_ADDRESS = "192.168.0.1";
@@ -338,30 +332,5 @@ public class SpiderDetectorServiceImplTest extends AbstractDSpaceTest {
public void cleanup() throws Exception {
spiderDetectorService = null;
configurationService.setProperty("usage-statistics.bots.case-insensitive", false);
;
}
/**
* Dummy SolrLogger for testing.
*
* @author mwood
*/
static public class MockSolrLogger
extends MockUp<SolrLoggerServiceImpl> {
@Mock
public void $init() {
}
@Mock
public void $clinit() {
}
@Mock
public boolean isUseProxies() {
return false;
}
}
}

View File

@@ -10,10 +10,10 @@ package org.dspace.statistics.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import mockit.Mock;
import mockit.MockUp;
import org.dspace.AbstractDSpaceTest;
import org.dspace.statistics.SolrLoggerServiceImpl;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.junit.Before;
import org.junit.Test;
/**
@@ -22,6 +22,15 @@ import org.junit.Test;
public class SpiderDetectorTest extends AbstractDSpaceTest {
private static final String NOT_A_BOT_ADDRESS = "192.168.0.1";
@Before
public void init() {
// Get current configuration
ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
// Ensure useProxies is set to false for all tests
configurationService.setProperty("useProxies", false);
}
/**
* Test method for {@link org.dspace.statistics.util.SpiderDetector#readPatterns(java.io.File)}.
*/
@@ -128,25 +137,4 @@ public class SpiderDetectorTest extends AbstractDSpaceTest {
SpiderDetector.isSpider(candidate, null, null, null));
}
/**
* Dummy SolrLogger for testing.
*
* @author mwood
*/
static public class MockSolrLogger
extends MockUp<SolrLoggerServiceImpl> {
@Mock
public void $init() {
}
@Mock
public void $clinit() {
}
@Mock
public boolean isUseProxies() {
return false;
}
}
}

View File

@@ -81,8 +81,8 @@ public class MultiFormatDateParserTest {
{"Should parse: yyyyMM", "195701", "yyyyMM", true},
{"Should parse: yyyy", "1957", "yyyy", true},
{"Should parse: yyyy-MM-dd'T'HH:mm:ss'Z'", "1957-01-27T12:34:56Z", "yyyy-MM-dd'T'HH:mm:ss'Z'", true},
{"Should parse: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "1957-01-27T12:34:56.789Z", "yyyy-MM-dd'T'HH:mm:ss" +
".SSS'Z'", true},
{"Should parse: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "1957-01-27T12:34:56.789Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
true},
{"Shouldn't parse: yyyy/MM/ddHH:mm:ss", "1957/01/2720:06:20", "yyyy/MM/ddHH:mm:ss", false}
});
}

View File

@@ -289,8 +289,8 @@ public class BasicWorkflowAuthorizationIT
int i = 0;
// check item policies
for (int action : new int[] {Constants.READ, Constants.WRITE, Constants.ADD, Constants.REMOVE, Constants
.DELETE}) {
for (int action : new int[] {Constants.READ, Constants.WRITE, Constants.ADD, Constants.REMOVE,
Constants.DELETE}) {
Assert.assertTrue("testReviewerPermissions 1-" + i++,
authorizeService.authorizeActionBoolean(context, member, item, action, false));
}

View File

@@ -6,8 +6,8 @@
# http://www.dspace.org/license/
#
# Defines the test folder where the unit tests will be run
# (Used by AbstractDSpaceTest)
test.folder = ./target/testing/
test.folder.assetstore = ./target/testing/dspace/assetstore
#Path for a test file to create bitstreams
# Path of the test bitstream (to use in BitstreamTest and elsewhere)
test.bitstream = ./target/testing/dspace/assetstore/ConstitutionofIreland.pdf

View File

@@ -7,22 +7,49 @@
*/
package org.dspace.xoai.services.impl.config;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Utils;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.xoai.services.api.config.ConfigurationService;
public class DSpaceConfigurationService implements ConfigurationService {
private org.dspace.services.ConfigurationService configurationService =
DSpaceServicesFactory.getInstance().getConfigurationService();
/**
* Initialize the OAI Configuration Service
*/
public DSpaceConfigurationService() {
// Check the DSpace ConfigurationService for required OAI-PMH settings.
// If they do not exist, set sane defaults as needed.
// Per OAI Spec, "oai.identifier.prefix" should be the hostname / domain name of the site.
// This configuration is needed by the [dspace]/config/crosswalks/oai/description.xml template, so if
// unspecified we will dynamically set it to the hostname of the "dspace.ui.url" configuration.
if (!configurationService.hasProperty("oai.identifier.prefix")) {
configurationService.setProperty("oai.identifier.prefix",
Utils.getHostName(configurationService.getProperty("dspace.ui.url")));
}
}
@Override
public String getProperty(String key) {
return ConfigurationManager.getProperty(key);
return configurationService.getProperty(key);
}
@Override
public String getProperty(String module, String key) {
return ConfigurationManager.getProperty(module, key);
return configurationService.getProperty(module, key);
}
@Override
public boolean getBooleanProperty(String module, String key, boolean defaultValue) {
return ConfigurationManager.getBooleanProperty(module, key, defaultValue);
if (module == null) {
return configurationService.getBooleanProperty(key, defaultValue);
}
// Assume "module" properties are always prefixed with the module name
return configurationService.getBooleanProperty(module + "." + key, defaultValue);
}
}

View File

@@ -9,6 +9,7 @@ package org.dspace.xoai.services.impl.xoai;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
@@ -22,6 +23,7 @@ import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.config.ConfigurationService;
@@ -132,13 +134,13 @@ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration {
@Override
public List<String> getDescription() {
List<String> result = new ArrayList<String>();
String descriptionFile = configurationService.getProperty("oai", "description.file");
String descriptionFile = configurationService.getProperty("oai.description.file");
if (descriptionFile == null) {
// Try indexed
boolean stop = false;
List<String> descriptionFiles = new ArrayList<String>();
for (int i = 0; !stop; i++) {
String tmp = configurationService.getProperty("oai", "description.file." + i);
String tmp = configurationService.getProperty("oai.description.file." + i);
if (tmp == null) {
stop = true;
} else {
@@ -150,7 +152,10 @@ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration {
try {
File f = new File(path);
if (f.exists()) {
result.add(FileUtils.readFileToString(f));
String fileAsString = FileUtils.readFileToString(f, StandardCharsets.UTF_8);
// replace any configuration placeholders (e.g. ${variable}) in string
fileAsString = Utils.interpolateConfigsInString(fileAsString);
result.add(fileAsString);
}
} catch (IOException e) {
log.debug(e.getMessage(), e);
@@ -161,7 +166,10 @@ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration {
try {
File f = new File(descriptionFile);
if (f.exists()) {
result.add(FileUtils.readFileToString(f));
String fileAsString = FileUtils.readFileToString(f, StandardCharsets.UTF_8);
// replace any configuration placeholders (e.g. ${variable}) in string
fileAsString = Utils.interpolateConfigsInString(fileAsString);
result.add(fileAsString);
}
} catch (IOException e) {
log.debug(e.getMessage(), e);

View File

@@ -176,7 +176,7 @@ public class ItemUtils {
}
/**
* This method will add all sub-elements to a top element, like: dc, or dcterms, ... *
* This method will add all sub-elements to a top element, like: dc, or dcterms, ... *
* @param schema Element argument passed by reference that will be changed
* @param val Metadatavalue that will be processed
* @throws SQLException
@@ -284,7 +284,7 @@ public class ItemUtils {
// Repository Info
Element repository = create("repository");
repository.getField().add(createValue("url", ConfigurationManager.getProperty("dspace.baseUrl")));
repository.getField().add(createValue("url", ConfigurationManager.getProperty("dspace.ui.url")));
repository.getField().add(createValue("name", ConfigurationManager.getProperty("dspace.name")));
repository.getField().add(createValue("mail", ConfigurationManager.getProperty("mail.admin")));
metadata.getElement().add(repository);

View File

@@ -61,7 +61,7 @@ public class DataProviderServlet extends HttpServlet {
log.debug("lang = " + lang + ", cType = " + cType + " and pathInfo: " + pathInfo);
if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) {
String dspaceURI =
DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.url");
DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.ui.url");
this.serveNamedGraph(dspaceURI, lang, cType, response);
return;
}

View File

@@ -51,7 +51,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>
@@ -95,7 +94,6 @@
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId>
<version>2.0</version>
<executions>
<execution>
<id>setproperty</id>
@@ -350,11 +348,6 @@
<artifactId>json-path-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <!-- Keep jmockit before junit -->
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@@ -82,7 +82,7 @@ public class AuthenticationRestController implements InitializingBean {
EPersonRest ePersonRest = null;
Projection projection = utils.obtainProjection();
if (context.getCurrentUser() != null) {
ePersonRest = ePersonConverter.fromModelWithGroups(context, context.getCurrentUser(), projection);
ePersonRest = converter.toRest(context.getCurrentUser(), projection);
}
AuthenticationStatusRest authenticationStatusRest = new AuthenticationStatusRest(ePersonRest);

View File

@@ -22,7 +22,6 @@ import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.link.HalLinkService;
import org.dspace.app.rest.model.BitstreamRest;
import org.dspace.app.rest.model.BundleRest;
import org.dspace.app.rest.model.hateoas.BundleResource;
import org.dspace.app.rest.repository.BitstreamRestRepository;
import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
@@ -33,12 +32,7 @@ import org.dspace.content.DSpaceObject;
import org.dspace.content.service.BitstreamService;
import org.dspace.core.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.ControllerUtils;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
@@ -48,12 +42,10 @@ import org.springframework.web.bind.annotation.RestController;
/**
* Controller to access bitstreams and the bundles they're in
* Controller to manage bundle of bitstreams.
* Endpoint: /api/core/bitstreams/{uuid}
* This controller can:
* - request bundle a bitstream is in (GET /api/core/bitstreams/{uuid}/bundle)
* - move bitstreams between bundles (POST /api/core/bitstreams/{uuid}/bundle (text/uri-list) -d link-to-new-bundle)
*
*/
@RestController
@RequestMapping("/api/" + BitstreamRest.CATEGORY + "/" + BitstreamRest.PLURAL_NAME
@@ -75,44 +67,6 @@ public class BitstreamBundleController {
@Autowired
BitstreamRestRepository bitstreamRestRepository;
/**
* This method gets the bundle of the bitstream that corresponds to to the provided bitstream uuid. When multiple
* bundles are present, only the first will be returned.
*
* @param uuid The UUID of the bitstream for which the bundle will be retrieved
* @param response The response object
* @param request The request object
* @return The wrapped resource containing the first bundle of the bitstream
* @throws IOException
* @throws SQLException
* @throws AuthorizeException
*/
@PreAuthorize("hasPermission(#uuid, 'BITSTREAM', 'READ')")
@RequestMapping(method = {RequestMethod.GET, RequestMethod.HEAD})
public ResponseEntity<ResourceSupport> getBundle(@PathVariable UUID uuid, HttpServletResponse response,
HttpServletRequest request)
throws IOException, SQLException, AuthorizeException {
Context context = ContextUtil.obtainContext(request);
Bitstream bitstream = bitstreamService.find(context, uuid);
if (bitstream == null) {
throw new ResourceNotFoundException(
BitstreamRest.CATEGORY + "." + BitstreamRest.NAME + " with id: " + uuid + " not found");
}
List<Bundle> bundles = bitstream.getBundles();
if (bundles.isEmpty()) {
return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT);
}
BundleResource bundleResource = converter.toResource(
converter.toRest(bundles.get(0), utils.obtainProjection()));
return ControllerUtils.toResponseEntity(HttpStatus.OK, new HttpHeaders(), bundleResource);
}
/**
* This method moves the bitstream to the bundle corresponding the the link provided in the body of the put request
*

View File

@@ -17,10 +17,11 @@ import javax.ws.rs.BadRequestException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.model.CollectionRest;
import org.dspace.app.rest.model.ItemRest;
import org.dspace.app.rest.model.hateoas.ItemResource;
import org.dspace.app.rest.model.TemplateItemRest;
import org.dspace.app.rest.model.hateoas.TemplateItemResource;
import org.dspace.app.rest.repository.CollectionRestRepository;
import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
@@ -60,6 +61,9 @@ public class CollectionItemtemplateController {
@Autowired
private CollectionService collectionService;
@Autowired
private ConverterService converter;
/**
* This method will create an Item and add it as a template to a Collection.
*
@@ -108,19 +112,20 @@ public class CollectionItemtemplateController {
Context context = ContextUtil.obtainContext(request);
Collection collection = getCollection(context, uuid);
ItemRest inputItemRest;
TemplateItemRest inputTemplateItemRest;
try {
ObjectMapper mapper = new ObjectMapper();
inputItemRest = mapper.readValue(itemBody.toString(), ItemRest.class);
inputTemplateItemRest = mapper.readValue(itemBody.toString(), TemplateItemRest.class);
} catch (IOException e1) {
throw new UnprocessableEntityException("Error parsing request body", e1);
}
ItemRest templateItem = collectionRestRepository.createTemplateItem(context, collection, inputItemRest);
TemplateItemRest templateItem =
collectionRestRepository.createTemplateItem(context, collection, inputTemplateItemRest);
context.commit();
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, new HttpHeaders(),
new ItemResource(templateItem, utils));
converter.toResource(templateItem));
}
/**
@@ -140,14 +145,14 @@ public class CollectionItemtemplateController {
*/
@PreAuthorize("hasPermission(#uuid, 'COLLECTION', 'READ')")
@RequestMapping(method = RequestMethod.GET)
public ItemResource getTemplateItem(HttpServletRequest request, @PathVariable UUID uuid)
public TemplateItemResource getTemplateItem(HttpServletRequest request, @PathVariable UUID uuid)
throws SQLException {
Context context = ContextUtil.obtainContext(request);
Collection collection = getCollection(context, uuid);
ItemRest templateItem = collectionRestRepository.getTemplateItem(collection);
TemplateItemRest templateItem = collectionRestRepository.getTemplateItem(collection);
return new ItemResource(templateItem, utils);
return converter.toResource(templateItem);
}
private Collection getCollection(Context context, UUID uuid) throws SQLException {

View File

@@ -65,7 +65,7 @@ public class CollectionLogoController {
/**
* This method will add a logo to the collection.
*
* curl -X POST http://<dspace.restUrl>/api/core/collections/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
* curl -X POST http://<dspace.server.url>/api/core/collections/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
* -XPOST -H 'Content-Type: multipart/form-data' \
* -H 'Authorization: Bearer eyJhbGciOiJI...' \
* -F "file=@Downloads/test.png"
@@ -73,7 +73,7 @@ public class CollectionLogoController {
* Example:
* <pre>
* {@code
* curl -X POST http://<dspace.restUrl>/api/core/collections/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
* curl -X POST http://<dspace.server.url>/api/core/collections/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
* -XPOST -H 'Content-Type: multipart/form-data' \
* -H 'Authorization: Bearer eyJhbGciOiJI...' \
* -F "file=@Downloads/test.png"

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