{
/**
* set the action this policy authorizes
*
- * @param myid action ID from {@link org.dspace.core.Constants#Constants Constants}
+ * @param myid action ID from {@link org.dspace.core.Constants Constants}
*/
public void setAction(int myid) {
this.actionId = myid;
diff --git a/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java b/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java
index 350facaad5..b4688c4807 100644
--- a/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java
+++ b/dspace-api/src/main/java/org/dspace/checker/DailyReportEmailer.java
@@ -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;
/**
*
@@ -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 " +
diff --git a/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java b/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java
index 363b3a8df0..cc6d32b8c3 100644
--- a/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/content/CollectionServiceImpl.java
@@ -367,7 +367,7 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl i
@Override
public void setWorkflowGroup(Context context, Collection collection, int step, Group group)
- throws SQLException, AuthorizeException {
+ throws SQLException {
Workflow workflow = null;
try {
workflow = workflowFactory.getWorkflow(collection);
@@ -889,4 +889,4 @@ public class CollectionServiceImpl extends DSpaceObjectServiceImpl i
throws SQLException {
return collectionDAO.getCollectionsWithBitstreamSizesTotal(context);
}
-}
\ No newline at end of file
+}
diff --git a/dspace-api/src/main/java/org/dspace/content/DSpaceObjectServiceImpl.java b/dspace-api/src/main/java/org/dspace/content/DSpaceObjectServiceImpl.java
index ee188dc144..6886d41e1b 100644
--- a/dspace-api/src/main/java/org/dspace/content/DSpaceObjectServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/content/DSpaceObjectServiceImpl.java
@@ -694,9 +694,11 @@ public abstract class DSpaceObjectServiceImpl implements
List list = getMetadata(dso, schema, element, qualifier);
- if (from >= list.size()) {
+ if (from >= list.size() || to >= list.size() || to < 0 || from < 0) {
throw new IllegalArgumentException(
- "The \"from\" location MUST exist for the operation to be successful. Idx:" + from);
+ "The \"from\" and \"to\" locations MUST exist for the operation to be successful." +
+ "\n To and from indices must be between 0 and " + (list.size() - 1) +
+ "\n Idx from:" + from + " Idx to: " + to);
}
clearMetadata(context, dso, schema, element, qualifier, Item.ANY);
@@ -757,4 +759,9 @@ public abstract class DSpaceObjectServiceImpl implements
}
}
+ @Override
+ public void setMetadataModified(T dso) {
+ dso.setMetadataModified();
+ }
+
}
diff --git a/dspace-api/src/main/java/org/dspace/content/MetadataFieldServiceImpl.java b/dspace-api/src/main/java/org/dspace/content/MetadataFieldServiceImpl.java
index e3ed9c8ae7..c71db2d131 100644
--- a/dspace-api/src/main/java/org/dspace/content/MetadataFieldServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/content/MetadataFieldServiceImpl.java
@@ -12,11 +12,13 @@ import java.sql.SQLException;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.dao.MetadataFieldDAO;
import org.dspace.content.service.MetadataFieldService;
+import org.dspace.content.service.MetadataSchemaService;
import org.dspace.content.service.MetadataValueService;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
@@ -42,6 +44,8 @@ public class MetadataFieldServiceImpl implements MetadataFieldService {
protected AuthorizeService authorizeService;
@Autowired(required = true)
protected MetadataValueService metadataValueService;
+ @Autowired(required = true)
+ protected MetadataSchemaService metadataSchemaService;
protected MetadataFieldServiceImpl() {
@@ -87,13 +91,25 @@ public class MetadataFieldServiceImpl implements MetadataFieldService {
return metadataFieldDAO.findByElement(context, metadataSchema, element, qualifier);
}
-
@Override
public MetadataField findByElement(Context context, String metadataSchemaName, String element, String qualifier)
throws SQLException {
return metadataFieldDAO.findByElement(context, metadataSchemaName, element, qualifier);
}
+ @Override
+ public MetadataField findByString(Context context, String mdString, char separator) throws SQLException {
+ String[] seq = StringUtils.split(mdString, separator);
+ String schema = seq.length > 1 ? seq[0] : null;
+ String element = seq.length > 1 ? seq[1] : null;
+ String qualifier = seq.length == 3 ? seq[2] : null;
+ if (schema == null || element == null) {
+ return null;
+ } else {
+ return this.findByElement(context, schema, element, qualifier);
+ }
+ }
+
@Override
public List findFieldsByElementNameUnqualified(Context context, String metadataSchemaName,
String element) throws SQLException {
diff --git a/dspace-api/src/main/java/org/dspace/content/Site.java b/dspace-api/src/main/java/org/dspace/content/Site.java
index ade0f62408..2704a3d518 100644
--- a/dspace-api/src/main/java/org/dspace/content/Site.java
+++ b/dspace-api/src/main/java/org/dspace/content/Site.java
@@ -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() {
diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/OREDisseminationCrosswalk.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/OREDisseminationCrosswalk.java
index f0e20cfffc..3dde093784 100644
--- a/dspace-api/src/main/java/org/dspace/content/crosswalk/OREDisseminationCrosswalk.java
+++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/OREDisseminationCrosswalk.java
@@ -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);
diff --git a/dspace-api/src/main/java/org/dspace/content/crosswalk/PREMISCrosswalk.java b/dspace-api/src/main/java/org/dspace/content/crosswalk/PREMISCrosswalk.java
index 9f927244c9..7bb7b38b43 100644
--- a/dspace-api/src/main/java/org/dspace/content/crosswalk/PREMISCrosswalk.java
+++ b/dspace-api/src/main/java/org/dspace/content/crosswalk/PREMISCrosswalk.java
@@ -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 bn = bitstream.getBundles();
diff --git a/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java b/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java
index f32990ea5b..d5e01002b3 100644
--- a/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java
+++ b/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java
@@ -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());
}
diff --git a/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java b/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java
index 753516a373..203d2a1787 100644
--- a/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java
+++ b/dspace-api/src/main/java/org/dspace/content/service/DSpaceObjectService.java
@@ -182,7 +182,7 @@ public interface DSpaceObjectService {
/**
* Add metadata fields. These are appended to existing values.
- * Use clearDC
to remove values. The ordering of values
+ * Use clearMetadata
to remove values. The ordering of values
* passed in is maintained.
*
* If metadata authority control is available, try to get authority
@@ -207,7 +207,7 @@ public interface DSpaceObjectService {
/**
* Add metadata fields. These are appended to existing values.
- * Use clearDC
to remove values. The ordering of values
+ * Use clearMetadata
to remove values. The ordering of values
* passed in is maintained.
*
* @param context DSpace context
@@ -231,7 +231,7 @@ public interface DSpaceObjectService {
/**
* Add metadata fields. These are appended to existing values.
- * Use clearDC
to remove values. The ordering of values
+ * Use clearMetadata
to remove values. The ordering of values
* passed in is maintained.
*
* @param context DSpace context
@@ -272,7 +272,7 @@ public interface DSpaceObjectService {
/**
* Add a single metadata field. This is appended to existing
- * values. Use clearDC
to remove values.
+ * values. Use clearMetadata
to remove values.
*
* @param context DSpace context
* @param dso DSpaceObject
@@ -292,7 +292,7 @@ public interface DSpaceObjectService {
/**
* Add a single metadata field. This is appended to existing
- * values. Use clearDC
to remove values.
+ * values. Use clearMetadata
to remove values.
*
* @param context DSpace context
* @param dso DSpaceObject
@@ -314,10 +314,10 @@ public interface DSpaceObjectService {
/**
* Clear metadata values. As with getDC
above,
- * passing in null
only matches fields where the qualifier or
+ * passing in null
only matches fields where the qualifier orr
* language is actually null
.Item.ANY
will
* match any element, qualifier or language, including null
.
- * Thus, dspaceobject.clearDC(Item.ANY, Item.ANY, Item.ANY)
will
+ * Thus, dspaceobject.clearMetadata(Item.ANY, Item.ANY, Item.ANY)
will
* remove all Dublin Core metadata associated with an DSpaceObject.
*
* @param context DSpace context
@@ -370,6 +370,26 @@ public interface DSpaceObjectService {
public void delete(Context context, T dso) throws SQLException, AuthorizeException, IOException;
+ /**
+ * Add a single metadata field. Whether it's appended or prepended depends on index parameter.
+ * Use clearMetadata
to remove values.
+ *
+ * @param context DSpace context
+ * @param dso DSpaceObject
+ * @param schema the schema for the metadata field. Must match
+ * the name
of an existing metadata schema.
+ * @param element the metadata element name
+ * @param qualifier the metadata qualifier, or null
for
+ * unqualified
+ * @param lang the ISO639 language code, optionally followed by an underscore
+ * and the ISO3166 country code. null
means the
+ * value has no language (for example, a date).
+ * @param value the value to add.
+ * @param authority the external authority key for this value (or null)
+ * @param confidence the authority confidence (default 0)
+ * @param index the index at which this metadata is added (0: first place, -1 for last)
+ * @throws SQLException if database error
+ */
void addAndShiftRightMetadata(Context context, T dso, String schema, String element, String qualifier, String lang,
String value, String authority, int confidence, int index) throws SQLException;
@@ -385,4 +405,10 @@ public interface DSpaceObjectService {
* @return a org.dspace.core.Constants that represents a IndexableObject type
*/
public int getSupportsTypeConstant();
+
+ /**
+ * Trigger the modifiedMetadata variable in DSpaceObject
+ * @param dso DSpaceObject whose metadata has been modified
+ */
+ public void setMetadataModified(T dso);
}
diff --git a/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java b/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java
index 5bfefd1db0..fa69087dd4 100644
--- a/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java
+++ b/dspace-api/src/main/java/org/dspace/content/service/MetadataFieldService.java
@@ -71,6 +71,16 @@ public interface MetadataFieldService {
public MetadataField findByElement(Context context, String metadataSchemaName, String element, String qualifier)
throws SQLException;
+ /**
+ * Separates an mdString in schema, element and qualifier parts, separated by a given separator
+ * And returns it's matching metadataField if found
+ * @param context dspace context
+ * @param mdString String being separated to find corresponding mdField (ex dc.contributor)
+ * @param separator Separator being used to separate the mdString
+ * @return Corresponding MetadataField if found
+ */
+ public MetadataField findByString(Context context, String mdString, char separator) throws SQLException;
+
public List findFieldsByElementNameUnqualified(Context context, String metadataSchema,
String element)
throws SQLException;
diff --git a/dspace-api/src/main/java/org/dspace/core/Context.java b/dspace-api/src/main/java/org/dspace/core/Context.java
index 1771473c62..64e86eef40 100644
--- a/dspace-api/src/main/java/org/dspace/core/Context.java
+++ b/dspace-api/src/main/java/org/dspace/core/Context.java
@@ -361,20 +361,18 @@ public class Context implements AutoCloseable {
// If Context is no longer open/valid, just note that it has already been closed
if (!isValid()) {
log.info("complete() was called on a closed Context object. No changes to commit.");
+ return;
}
try {
// As long as we have a valid, writeable database connection,
- // rollback any changes if we are in read-only mode,
- // otherwise, commit any changes made as part of the transaction
- if (isReadOnly()) {
- abort();
- } else {
+ // commit changes. Otherwise, we'll just close the DB connection (see below)
+ if (!isReadOnly()) {
commit();
}
} finally {
if (dbConnection != null) {
- // Free the DB connection
+ // Free the DB connection and invalidate the Context
dbConnection.closeDBConnection();
dbConnection = null;
}
@@ -395,29 +393,24 @@ public class Context implements AutoCloseable {
// If Context is no longer open/valid, just note that it has already been closed
if (!isValid()) {
log.info("commit() was called on a closed Context object. No changes to commit.");
+ return;
}
if (isReadOnly()) {
throw new UnsupportedOperationException("You cannot commit a read-only context");
}
- // Our DB Connection (Hibernate) will decide if an actual commit is required or not
try {
- // As long as we have a valid, writeable database connection,
- // commit any changes made as part of the transaction
- if (isValid()) {
- // Dispatch events before committing changes to the database,
- // as the consumers may change something too
- dispatchEvents();
- }
-
+ // Dispatch events before committing changes to the database,
+ // as the consumers may change something too
+ dispatchEvents();
} finally {
if (log.isDebugEnabled()) {
log.debug("Cache size on commit is " + getCacheSize());
}
if (dbConnection != null) {
- //Commit our changes
+ // Commit our changes (this closes the transaction but leaves database connection open)
dbConnection.commit();
reloadContextBoundEntities();
}
@@ -425,8 +418,12 @@ public class Context implements AutoCloseable {
}
+ /**
+ * Dispatch any events (cached in current Context) to configured EventListeners (consumers)
+ * in the EventService. This should be called prior to any commit as some consumers may add
+ * to the current transaction. Once events are dispatched, the Context's event cache is cleared.
+ */
public void dispatchEvents() {
- // Commit any changes made as part of the transaction
Dispatcher dispatcher = null;
try {
@@ -462,6 +459,7 @@ public class Context implements AutoCloseable {
/**
* Add an event to be dispatched when this context is committed.
+ * NOTE: Read-only Contexts cannot add events, as they cannot modify objects.
*
* @param event event to be dispatched
*/
@@ -490,6 +488,10 @@ public class Context implements AutoCloseable {
return events;
}
+ /**
+ * Whether or not the context has events cached.
+ * @return true or false
+ */
public boolean hasEvents() {
return !CollectionUtils.isEmpty(events);
}
@@ -521,22 +523,25 @@ public class Context implements AutoCloseable {
// If Context is no longer open/valid, just note that it has already been closed
if (!isValid()) {
log.info("abort() was called on a closed Context object. No changes to abort.");
+ return;
}
try {
- // Rollback ONLY if we have a database connection, and it is NOT Read Only
- if (isValid() && !isReadOnly()) {
+ // Rollback ONLY if we have a database transaction, and it is NOT Read Only
+ if (!isReadOnly() && isTransactionAlive()) {
dbConnection.rollback();
}
} catch (SQLException se) {
- log.error(se.getMessage(), se);
+ log.error("Error rolling back transaction during an abort()", se);
} finally {
try {
- if (!dbConnection.isSessionAlive()) {
+ if (dbConnection != null) {
+ // Free the DB connection & invalidate the Context
dbConnection.closeDBConnection();
+ dbConnection = null;
}
} catch (Exception ex) {
- log.error("Exception aborting context", ex);
+ log.error("Error closing the database connection", ex);
}
events = null;
}
@@ -558,7 +563,22 @@ public class Context implements AutoCloseable {
*/
public boolean isValid() {
// Only return true if our DB connection is live
- return dbConnection != null && dbConnection.isTransActionAlive();
+ // NOTE: A transaction need not exist for our Context to be valid, as a Context may use multiple transactions.
+ return dbConnection != null && dbConnection.isSessionAlive();
+ }
+
+ /**
+ * Find out whether our context includes an open database transaction.
+ * Returns true
if there is an open transaction. Returns
+ * false
if the context is invalid (e.g. abort() or complete())
+ * was called OR no current transaction exists (e.g. commit() was just called
+ * and no new transaction has begun)
+ *
+ * @return
+ */
+ protected boolean isTransactionAlive() {
+ // Only return true if both Context is valid *and* transaction is alive
+ return isValid() && dbConnection.isTransActionAlive();
}
/**
@@ -571,21 +591,22 @@ public class Context implements AutoCloseable {
return mode != null && mode == Mode.READ_ONLY;
}
+ /**
+ * Add a group's UUID to the list of special groups cached in Context
+ * @param groupID UUID of group
+ */
public void setSpecialGroup(UUID groupID) {
specialGroups.add(groupID);
-
- // System.out.println("Added " + groupID);
}
/**
- * test if member of special group
+ * Test if a group is a special group
*
* @param groupID ID of special group to test
* @return true if member
*/
public boolean inSpecialGroup(UUID groupID) {
if (specialGroups.contains(groupID)) {
- // System.out.println("Contains " + groupID);
return true;
}
@@ -593,10 +614,9 @@ public class Context implements AutoCloseable {
}
/**
- * Get an array of all of the special groups that current user is a member
- * of.
+ * Get an array of all of the special groups that current user is a member of.
*
- * @return list of groups
+ * @return list of special groups
* @throws SQLException if database error
*/
public List getSpecialGroups() throws SQLException {
@@ -608,6 +628,10 @@ public class Context implements AutoCloseable {
return myGroups;
}
+ /**
+ * Close the context, aborting any open transactions (if any).
+ * @throws Throwable
+ */
@Override
protected void finalize() throws Throwable {
/*
diff --git a/dspace-api/src/main/java/org/dspace/core/Email.java b/dspace-api/src/main/java/org/dspace/core/Email.java
index 5e7bbe2332..803497b650 100644
--- a/dspace-api/src/main/java/org/dspace/core/Email.java
+++ b/dspace-api/src/main/java/org/dspace/core/Email.java
@@ -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) {
diff --git a/dspace-api/src/main/java/org/dspace/core/HibernateDBConnection.java b/dspace-api/src/main/java/org/dspace/core/HibernateDBConnection.java
index c88cd0c1cd..57d823c743 100644
--- a/dspace-api/src/main/java/org/dspace/core/HibernateDBConnection.java
+++ b/dspace-api/src/main/java/org/dspace/core/HibernateDBConnection.java
@@ -35,6 +35,23 @@ import org.springframework.orm.hibernate5.SessionFactoryUtils;
/**
* Hibernate implementation of the DBConnection.
+ *
+ * NOTE: This class does NOT represent a single Hibernate database connection. Instead, it wraps
+ * Hibernate's Session object to obtain access to a database connection in order to execute one or more
+ * transactions.
+ *
+ * Per DSpace's current Hibernate configuration ([dspace]/config/core-hibernate.xml), we use the one-session-per-thread
+ * approach (ThreadLocalSessionContext). This means that Hibernate creates a single Session per thread (request), at the
+ * time when getCurrentSession() is first called.
+ *
+ * This Session may be reused for multiple Transactions, but if commit() is called, any objects (Entities) in
+ * the Session become disconnected and MUST be reloaded into the Session (see reloadEntity() method below).
+ *
+ * If an Error occurs, the Session itself is invalidated. No further Transactions can be run on that Session.
+ *
+ * DSpace generally follows the "Session-per-request" transactional pattern described here:
+ * https://docs.jboss.org/hibernate/orm/5.0/userguide/en-US/html/ch06.html#session-per-request
+ *
*
* @author kevinvandevelde at atmire.com
*/
@@ -47,32 +64,61 @@ public class HibernateDBConnection implements DBConnection {
private boolean batchModeEnabled = false;
private boolean readOnlyEnabled = false;
+ /**
+ * Retrieves the current Session from Hibernate (per our settings, Hibernate is configured to create one Session
+ * per thread). If Session doesn't yet exist, it is created. A Transaction is also initialized (or reinintialized)
+ * in the Session if one doesn't exist, or was previously closed (e.g. if commit() was previously called)
+ * @return Hibernate current Session object
+ * @throws SQLException
+ */
@Override
public Session getSession() throws SQLException {
+ // If we don't yet have a live transaction, start a new one
+ // NOTE: a Session cannot be used until a Transaction is started.
if (!isTransActionAlive()) {
sessionFactory.getCurrentSession().beginTransaction();
configureDatabaseMode();
}
+ // Return the current Hibernate Session object (Hibernate will create one if it doesn't yet exist)
return sessionFactory.getCurrentSession();
}
+ /**
+ * Check if the connection has a currently active Transaction. A Transaction is active if it has not yet been
+ * either committed or rolled back.
+ * @return
+ */
@Override
public boolean isTransActionAlive() {
Transaction transaction = getTransaction();
return transaction != null && transaction.isActive();
}
+ /**
+ * Retrieve the current Hibernate Transaction object from our Hibernate Session.
+ * @return current Transaction (may be active or inactive) or null
+ */
protected Transaction getTransaction() {
return sessionFactory.getCurrentSession().getTransaction();
}
+ /**
+ * Check if Hibernate Session is still "alive" / open. An open Session may or may not have an open Transaction
+ * (so isTransactionAlive() may return false even if isSessionAlive() returns true). A Session may be reused for
+ * multiple transactions (e.g. if commit() is called, the Session remains alive while the Transaction is closed)
+ *
+ * @return true if Session is alive, false otherwise
+ */
@Override
public boolean isSessionAlive() {
- return sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession()
- .getTransaction() != null && sessionFactory
- .getCurrentSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE);
+ return sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession().isOpen();
}
+ /**
+ * Rollback any changes applied to the current Transaction. This also closes the Transaction. A new Transaction
+ * may be opened the next time getSession() is called.
+ * @throws SQLException
+ */
@Override
public void rollback() throws SQLException {
if (isTransActionAlive()) {
@@ -80,6 +126,14 @@ public class HibernateDBConnection implements DBConnection {
}
}
+ /**
+ * Close our current Database connection. This also closes & unbinds the Hibernate Session from our thread.
+ *
+ * NOTE: Because DSpace configures Hibernate to automatically create a Session per thread, a Session may still
+ * exist after this method is called (as Hibernate may automatically create a new Session for the current thread).
+ * However, Hibernate will automatically clean up any existing Session when the thread closes.
+ * @throws SQLException
+ */
@Override
public void closeDBConnection() throws SQLException {
if (sessionFactory.getCurrentSession() != null && sessionFactory.getCurrentSession().isOpen()) {
@@ -87,11 +141,23 @@ public class HibernateDBConnection implements DBConnection {
}
}
+ /**
+ * Commits any current changes cached in the Hibernate Session to the database & closes the Transaction.
+ * To open a new Transaction, you may call getSession().
+ *
+ * WARNING: When commit() is called, while the Session is still "alive", all previously loaded objects (entities)
+ * become disconnected from the Session. Therefore, if you continue to use the Session, you MUST reload any needed
+ * objects (entities) using reloadEntity() method.
+ *
+ * @throws SQLException
+ */
@Override
public void commit() throws SQLException {
if (isTransActionAlive() && !getTransaction().getStatus().isOneOf(TransactionStatus.MARKED_ROLLBACK,
TransactionStatus.ROLLING_BACK)) {
+ // Flush synchronizes the database with in-memory objects in Session (and frees up that memory)
getSession().flush();
+ // Commit those results to the database & ends the Transaction
getTransaction().commit();
}
}
@@ -132,6 +198,16 @@ public class HibernateDBConnection implements DBConnection {
return getSession().getStatistics().getEntityCount();
}
+ /**
+ * Reload an entity into the Hibernate cache. This can be called after a call to commit() to re-cache an object
+ * in the Hibernate Session (see commit()). Failing to reload objects into the cache may result in a Hibernate
+ * throwing a "LazyInitializationException" if you attempt to use an object that has been disconnected from the
+ * Session cache.
+ * @param entity The DSpace object to reload
+ * @param The class of the entity. The entity must implement the {@link ReloadableEntity} interface.
+ * @return the newly cached object.
+ * @throws SQLException
+ */
@Override
@SuppressWarnings("unchecked")
public E reloadEntity(final E entity) throws SQLException {
@@ -167,10 +243,13 @@ public class HibernateDBConnection implements DBConnection {
}
/**
- * Evict an entity from the hibernate cache. This is necessary when batch processing a large number of items.
+ * Evict an entity from the hibernate cache.
+ *
+ * When an entity is evicted, it frees up the memory used by that entity in the cache. This is often
+ * necessary when batch processing a large number of objects (to avoid out-of-memory exceptions).
*
- * @param entity The entity to reload
- * @param The class of the enity. The entity must implement the {@link ReloadableEntity} interface.
+ * @param entity The entity to evict
+ * @param The class of the entity. The entity must implement the {@link ReloadableEntity} interface.
* @throws SQLException When reloading the entity from the database fails.
*/
@Override
diff --git a/dspace-api/src/main/java/org/dspace/core/Utils.java b/dspace-api/src/main/java/org/dspace/core/Utils.java
index 32c32776f7..29ed446f1b 100644
--- a/dspace-api/src/main/java/org/dspace/core/Utils.java
+++ b/dspace-api/src/main/java/org/dspace/core/Utils.java
@@ -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.
+ *
+ * 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());
+ }
}
diff --git a/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java b/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java
index 6af1564830..94361b7cf9 100644
--- a/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/discovery/SolrServiceImpl.java
@@ -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;
diff --git a/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoverySortFieldConfiguration.java b/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoverySortFieldConfiguration.java
index 37e024515a..bda2e780ba 100644
--- a/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoverySortFieldConfiguration.java
+++ b/dspace-api/src/main/java/org/dspace/discovery/configuration/DiscoverySortFieldConfiguration.java
@@ -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();
+ }
}
diff --git a/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java b/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java
index 0e1034328a..e00a9568e3 100644
--- a/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/eperson/AccountServiceImpl.java
@@ -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(
diff --git a/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java b/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java
index 4f094bb5c5..319dcad65c 100644
--- a/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java
+++ b/dspace-api/src/main/java/org/dspace/eperson/EPersonConsumer.java
@@ -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());
diff --git a/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java b/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java
index ca545e0722..4c5138cf35 100644
--- a/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/handle/HandleServiceImpl.java
@@ -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");
diff --git a/dspace-api/src/main/java/org/dspace/health/InfoCheck.java b/dspace-api/src/main/java/org/dspace/health/InfoCheck.java
index ba6ba9b6c0..ddb8785d6d 100644
--- a/dspace-api/src/main/java/org/dspace/health/InfoCheck.java
+++ b/dspace-api/src/main/java/org/dspace/health/InfoCheck.java
@@ -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");
diff --git a/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java b/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java
index b34d10167c..8defe4bc2e 100644
--- a/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java
+++ b/dspace-api/src/main/java/org/dspace/identifier/EZIDIdentifierProvider.java
@@ -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);
diff --git a/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java b/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java
index e5475e5eb4..409a4f1518 100644
--- a/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java
+++ b/dspace-api/src/main/java/org/dspace/rdf/conversion/SimpleDSORelationsConverterPlugin.java
@@ -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.
diff --git a/dspace-api/src/main/java/org/dspace/rdf/negotiation/Negotiator.java b/dspace-api/src/main/java/org/dspace/rdf/negotiation/Negotiator.java
index dbf703e8de..c28b9ec1e6 100644
--- a/dspace-api/src/main/java/org/dspace/rdf/negotiation/Negotiator.java
+++ b/dspace-api/src/main/java/org/dspace/rdf/negotiation/Negotiator.java
@@ -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/");
diff --git a/dspace-api/src/main/java/org/dspace/scripts/DSpaceCommandLineParameter.java b/dspace-api/src/main/java/org/dspace/scripts/DSpaceCommandLineParameter.java
index 0615aaace3..2862d014c9 100644
--- a/dspace-api/src/main/java/org/dspace/scripts/DSpaceCommandLineParameter.java
+++ b/dspace-api/src/main/java/org/dspace/scripts/DSpaceCommandLineParameter.java
@@ -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();
+ }
}
diff --git a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java
index 92691b99a8..7ad9e9cf88 100644
--- a/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java
+++ b/dspace-api/src/main/java/org/dspace/statistics/content/StatisticsDataVisits.java
@@ -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 {
diff --git a/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java b/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java
index 9d7ec14143..29f17bc442 100644
--- a/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java
+++ b/dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java
@@ -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
diff --git a/dspace-api/src/main/java/org/dspace/submit/model/AccessConditionOption.java b/dspace-api/src/main/java/org/dspace/submit/model/AccessConditionOption.java
index ca8efc09c4..398097a9ec 100644
--- a/dspace-api/src/main/java/org/dspace/submit/model/AccessConditionOption.java
+++ b/dspace-api/src/main/java/org/dspace/submit/model/AccessConditionOption.java
@@ -8,22 +8,59 @@
package org.dspace.submit.model;
/**
+ * This class represents an option available in the submission upload section to
+ * set permission on a file. An option is defined by a name such as "open
+ * access", "embargo", "restricted access", etc. and some optional attributes to
+ * better clarify the constraints and input available to the user. For instance
+ * an embargo option could allow to set a start date not longer than 3 years,
+ * etc
+ *
* @author Luigi Andrea Pascarelli (luigiandrea.pascarelli at 4science.it)
*/
public class AccessConditionOption {
-
+ /** An unique name identifying the access contion option **/
private String name;
+ /**
+ * the name of the group that will be bound to the resource policy created if
+ * such option is used
+ */
private String groupName;
+ /**
+ * this is in alternative to the {@link #groupName}. The sub-groups listed in
+ * the DSpace group identified by the name here specified will be available to
+ * the user to personalize the access condition. They can be for instance
+ * University Staff, University Students, etc. so that a "restricted access"
+ * option can be further specified without the need to create separate access
+ * condition options for each group
+ */
private String selectGroupName;
+ /**
+ * set to true
if this option requires a start date to be indicated
+ * for the underlying resource policy to create
+ */
private Boolean hasStartDate;
+ /**
+ * set to true
if this option requires an end date to be indicated
+ * for the underlying resource policy to create
+ */
private Boolean hasEndDate;
+ /**
+ * It contains, if applicable, the maximum start date (i.e. when the "embargo
+ * expires") that can be selected. It accepts date math via joda library (such as
+ * +3years)
+ */
private String startDateLimit;
+ /**
+ * It contains, if applicable, the maximum end date (i.e. when the "lease
+ * expires") that can be selected. It accepts date math via joda library (such as
+ * +3years)
+ */
private String endDateLimit;
public String getName() {
@@ -81,6 +118,4 @@ public class AccessConditionOption {
public void setSelectGroupName(String selectGroupName) {
this.selectGroupName = selectGroupName;
}
-
-
}
diff --git a/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java b/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java
index 6ddd750b20..58f393804a 100644
--- a/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/workflowbasic/BasicWorkflowServiceImpl.java
@@ -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,
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java
index 175078564f..7edafe7efe 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/WorkflowUtils.java
@@ -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);
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowFactoryImpl.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowFactoryImpl.java
index 1689ff0bb0..ffc62dcddb 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowFactoryImpl.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowFactoryImpl.java
@@ -7,29 +7,53 @@
*/
package org.dspace.xmlworkflow;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.logging.log4j.Logger;
import org.dspace.content.Collection;
+import org.dspace.content.service.CollectionService;
+import org.dspace.core.Context;
+import org.dspace.handle.service.HandleService;
+import org.dspace.utils.DSpace;
import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
+import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.Workflow;
+import org.dspace.xmlworkflow.state.actions.WorkflowActionConfig;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
/**
- * The workflowfactory is responsible for parsing the
- * workflow xml file and is used to retrieve the workflow for
- * a certain collection
+ * The workflowfactory is responsible for parsing the workflow xml file and is used to retrieve info about the workflow:
+ * - the workflow for a certain collection
+ * - collections mapped to a certain workflow
+ * - collections not mapped to any workflow
+ * - configured workflows and the default workflow
+ * - workflow action by name
*
* @author Bram De Schouwer (bram.deschouwer at dot com)
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
+ * @author Maria Verdonck (Atmire) on 11/12/2019
*/
public class XmlWorkflowFactoryImpl implements XmlWorkflowFactory {
public static final String LEGACY_WORKFLOW_NAME = "defaultWorkflow";
+ private Logger log = org.apache.logging.log4j.LogManager.getLogger(XmlWorkflowFactoryImpl.class);
+
private Map workflowMapping;
+ @Autowired
+ protected CollectionService collectionService;
+
+ @Autowired
+ protected HandleService handleService;
+
@Override
public Workflow getWorkflow(Collection collection) throws WorkflowConfigurationException {
// Attempt to retrieve our workflow object
@@ -50,4 +74,93 @@ public class XmlWorkflowFactoryImpl implements XmlWorkflowFactory {
public void setWorkflowMapping(Map workflowMapping) {
this.workflowMapping = workflowMapping;
}
-}
\ No newline at end of file
+
+ @Override
+ public Workflow getWorkflowByName(String workflowName) throws WorkflowConfigurationException {
+ for (Workflow workflow : workflowMapping.values()) {
+ if (workflow.getID().equals(workflowName)) {
+ return workflow;
+ }
+ }
+ throw new WorkflowConfigurationException(
+ "Error while retrieving workflow by the following name: " + workflowName);
+ }
+
+ @Override
+ public Workflow getDefaultWorkflow() {
+ return this.workflowMapping.get(LEGACY_WORKFLOW_NAME);
+ }
+
+ @Override
+ public List getAllConfiguredWorkflows() {
+ return new ArrayList<>(this.workflowMapping.values());
+ }
+
+ @Override
+ public List getCollectionHandlesMappedToWorklow(Context context, String workflowName) {
+ List collectionsMapped = new ArrayList<>();
+ for (String handle : this.workflowMapping.keySet()) {
+ if (this.workflowMapping.get(handle).getID().equals(workflowName)) {
+ try {
+ Collection collection = (Collection) handleService.resolveToObject(context, handle);
+ if (collection != null) {
+ collectionsMapped.add(collection);
+ }
+ } catch (SQLException e) {
+ log.error("SQLException in XmlWorkflowFactoryImpl.getCollectionHandlesMappedToWorklow trying to " +
+ "retrieve collection with handle: " + handle, e);
+ }
+ }
+ }
+ return collectionsMapped;
+ }
+
+ @Override
+ public List getAllNonMappedCollectionsHandles(Context context) {
+ List nonMappedCollections = new ArrayList<>();
+ try {
+ for (Collection collection : this.collectionService.findAll(context)) {
+ if (workflowMapping.get(collection.getHandle()) == null) {
+ nonMappedCollections.add(collection);
+ }
+ }
+ } catch (SQLException e) {
+ log.error("SQLException in XmlWorkflowFactoryImpl.getAllNonMappedCollectionsHandles trying to " +
+ "retrieve all collections", e);
+ }
+ return nonMappedCollections;
+ }
+
+ @Override
+ public boolean workflowByThisNameExists(String workflowName) {
+ for (Workflow workflow : this.workflowMapping.values()) {
+ if (workflow.getID().equals(workflowName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+ @Override
+ public boolean isDefaultWorkflow(String workflowName) {
+ if (StringUtils.isNotBlank(workflowName)) {
+ Workflow defaultWorkflow = this.getDefaultWorkflow();
+ if (defaultWorkflow != null && StringUtils.isNotBlank(defaultWorkflow.getID())) {
+ return (defaultWorkflow.getID().equals(workflowName));
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public WorkflowActionConfig getActionByName(String workflowActionName) {
+ return new DSpace().getServiceManager().getServiceByName(workflowActionName, WorkflowActionConfig.class);
+ }
+
+ @Override
+ public Step getStepByName(String workflowStepName) {
+ return new DSpace().getServiceManager().getServiceByName(workflowStepName, Step.class);
+ }
+
+}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java
index 591d5f6b29..3b7937bca1 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/XmlWorkflowServiceImpl.java
@@ -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 {
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/factory/XmlWorkflowFactory.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/factory/XmlWorkflowFactory.java
index 47626bed44..5d33843747 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/factory/XmlWorkflowFactory.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/factory/XmlWorkflowFactory.java
@@ -7,23 +7,31 @@
*/
package org.dspace.xmlworkflow.factory;
+import java.util.List;
+
import org.dspace.content.Collection;
+import org.dspace.core.Context;
import org.dspace.xmlworkflow.WorkflowConfigurationException;
+import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.Workflow;
+import org.dspace.xmlworkflow.state.actions.WorkflowActionConfig;
/**
- * The xmlworkflowfactory is responsible for parsing the
- * workflow xml file and is used to retrieve the workflow for
- * a certain collection
+ * The workflowfactory is responsible for parsing the workflow xml file and is used to retrieve info about the workflow:
+ * - the workflow for a certain collection
+ * - collections mapped to a certain workflow
+ * - collections not mapped to any workflow
+ * - configured workflows and the default workflow
+ * - workflow action by name
*
* @author Bram De Schouwer (bram.deschouwer at dot com)
* @author Kevin Van de Velde (kevin at atmire dot com)
* @author Ben Bosman (ben at atmire dot com)
* @author Mark Diggory (markd at atmire dot com)
+ * @author Maria Verdonck (Atmire) on 11/12/2019
*/
public interface XmlWorkflowFactory {
-
/**
* Retrieve the workflow configuration for a single collection
*
@@ -32,4 +40,74 @@ public interface XmlWorkflowFactory {
* @throws WorkflowConfigurationException occurs if there is a configuration error in the workflow
*/
public Workflow getWorkflow(Collection collection) throws WorkflowConfigurationException;
+
+ /**
+ * Retrieves the workflow configuration by name
+ *
+ * @param workflowName the name for which we want our workflow
+ * @return the workflow configuration
+ * @throws WorkflowConfigurationException occurs if there is no workflow configured by that name
+ */
+ public Workflow getWorkflowByName(String workflowName) throws WorkflowConfigurationException;
+
+ /**
+ * Creates a list of all configured workflows, or returns the cache of this if it was already created
+ *
+ * @return List of all configured workflows
+ */
+ public List getAllConfiguredWorkflows();
+
+ /**
+ * Check to see if there is a workflow configured by the given name
+ *
+ * @param workflowName Name of a possible configured workflow
+ * @return True if there is a workflow configured by this name, false otherwise
+ */
+ public boolean workflowByThisNameExists(String workflowName);
+
+ /**
+ * Check to see if the given workflowName is the workflow configured to be default for collections
+ *
+ * @param workflowName Name of workflow to check if default
+ * @return True if given workflowName is the workflow mapped to default for collections, otherwise false
+ */
+ public boolean isDefaultWorkflow(String workflowName);
+
+ /**
+ * Gets the default workflow, i.e. the workflow that is mapped to collection=default in workflow.xml
+ */
+ public Workflow getDefaultWorkflow();
+
+ /**
+ * Return a list of collections that are mapped to the given workflow in the workflow configuration.
+ * * Makes use of a cache so it only retrieves the workflowName->List if it's not cached
+ *
+ * @param context Dspace context
+ * @param workflowName Name of workflow we want the collections of that are mapped to is
+ * @return List of collections mapped to the requested workflow
+ */
+ public List getCollectionHandlesMappedToWorklow(Context context, String workflowName);
+
+ /**
+ * Returns list of collections that are not mapped to any configured workflow, and thus use the default workflow
+ *
+ * @return List of collections not mapped to any workflow
+ */
+ public List getAllNonMappedCollectionsHandles(Context context);
+
+ /**
+ * Retrieves a {@link WorkflowActionConfig} object based on its name, should correspond with bean id in workflow-actions.xml
+ *
+ * @param workflowActionName Name of workflow action we want to retrieve
+ * @return Workflow action object corresponding to the given workflowActionName
+ */
+ public WorkflowActionConfig getActionByName(String workflowActionName);
+
+ /**
+ * Retrieves a {@link Step} object based on its name, should correspond with bean id in workflow.xml
+ *
+ * @param workflowStepName Name of workflow step we want to retrieve
+ * @return Workflow step object corresponding to the given workflowStepName
+ */
+ public Step getStepByName(String workflowStepName);
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java
index ba481be3d9..9cf202f12d 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/Action.java
@@ -36,8 +36,7 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
public abstract class Action {
private WorkflowActionConfig parent;
- private static String ERROR_FIELDS_ATTRIBUTE = "dspace.workflow.error_fields";
-
+ private static final String ERROR_FIELDS_ATTRIBUTE = "dspace.workflow.error_fields";
public abstract void activate(Context c, XmlWorkflowItem wf)
throws SQLException, IOException, AuthorizeException, WorkflowException;
@@ -45,6 +44,12 @@ public abstract class Action {
public abstract ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException, WorkflowException;
+ /**
+ * Returns a list of options that the user can select at this action which results in the next step in the workflow
+ * @return A list of options of this action, resulting in the next step of the workflow
+ */
+ public abstract List getOptions();
+
public WorkflowActionConfig getParent() {
return parent;
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/WorkflowActionConfig.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/WorkflowActionConfig.java
index 2c1a7b1fe8..1dc61888b1 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/WorkflowActionConfig.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/WorkflowActionConfig.java
@@ -7,6 +7,8 @@
*/
package org.dspace.xmlworkflow.state.actions;
+import java.util.List;
+
import org.dspace.xmlworkflow.state.Step;
/**
@@ -59,4 +61,12 @@ public class WorkflowActionConfig {
return step;
}
+ /**
+ * Returns a list of options the user has on this action, resulting in the next step of the workflow
+ * @return A list of options of this action, resulting in the next step of the workflow
+ */
+ public List getOptions() {
+ return this.processingAction.getOptions();
+ }
+
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/AcceptEditRejectAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/AcceptEditRejectAction.java
index 7d330aace9..3c595b7545 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/AcceptEditRejectAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/AcceptEditRejectAction.java
@@ -9,6 +9,8 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.authorize.AuthorizeException;
@@ -31,40 +33,49 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
*/
public class AcceptEditRejectAction extends ProcessingAction {
- public static final int MAIN_PAGE = 0;
- public static final int REJECT_PAGE = 1;
+ private static final String SUBMIT_APPROVE = "submit_approve";
+ private static final String SUBMIT_REJECT = "submit_reject";
//TODO: rename to AcceptAndEditMetadataAction
@Override
- public void activate(Context c, XmlWorkflowItem wf) throws SQLException {
+ public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException, IOException {
+ throws SQLException, AuthorizeException, IOException {
- if (request.getParameter("submit_approve") != null) {
- return processAccept(c, wfi, step, request);
+ if (request.getParameter(SUBMIT_APPROVE) != null) {
+ return processAccept(c, wfi);
} else {
- if (request.getParameter("submit_reject") != null) {
- return processRejectPage(c, wfi, step, request);
+ if (request.getParameter(SUBMIT_REJECT) != null) {
+ return processRejectPage(c, wfi, request);
}
}
return new ActionResult(ActionResult.TYPE.TYPE_CANCEL);
}
- public ActionResult processAccept(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException {
+ @Override
+ public List getOptions() {
+ List options = new ArrayList<>();
+ options.add(SUBMIT_APPROVE);
+ options.add(SUBMIT_REJECT);
+ options.add(ProcessingAction.SUBMIT_EDIT_METADATA);
+ return options;
+ }
+
+ public ActionResult processAccept(Context c, XmlWorkflowItem wfi)
+ throws SQLException, AuthorizeException {
//Delete the tasks
addApprovedProvenance(c, wfi);
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
- public ActionResult processRejectPage(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException, IOException {
+ public ActionResult processRejectPage(Context c, XmlWorkflowItem wfi, HttpServletRequest request)
+ throws SQLException, AuthorizeException, IOException {
String reason = request.getParameter("reason");
if (reason == null || 0 == reason.trim().length()) {
addErrorField(request, "reason");
@@ -85,14 +96,14 @@ public class AcceptEditRejectAction extends ProcessingAction {
// Get user's name + email address
String usersName = XmlWorkflowServiceFactory.getInstance().getXmlWorkflowService()
- .getEPersonName(c.getCurrentUser());
+ .getEPersonName(c.getCurrentUser());
String provDescription = getProvenanceStartId() + " Approved for entry into archive by "
- + usersName + " on " + now + " (GMT) ";
+ + usersName + " on " + now + " (GMT) ";
// Add to item as a DC field
itemService.addMetadata(c, wfi.getItem(), MetadataSchemaEnum.DC.getName(), "description", "provenance", "en",
- provDescription);
+ provDescription);
itemService.update(c, wfi.getItem());
}
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/FinalEditAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/FinalEditAction.java
index 50686f3993..fe73bf6a5d 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/FinalEditAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/FinalEditAction.java
@@ -7,8 +7,9 @@
*/
package org.dspace.xmlworkflow.state.actions.processingaction;
-import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.authorize.AuthorizeException;
@@ -31,21 +32,22 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
*/
public class FinalEditAction extends ProcessingAction {
+ private static final String SUBMIT_APPROVE = "submit_approve";
@Override
- public void activate(Context c, XmlWorkflowItem wf) throws SQLException {
+ public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException, IOException {
+ throws SQLException, AuthorizeException {
return processMainPage(c, wfi, step, request);
}
public ActionResult processMainPage(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException {
- if (request.getParameter("submit_approve") != null) {
+ throws SQLException, AuthorizeException {
+ if (request.getParameter(SUBMIT_APPROVE) != null) {
//Delete the tasks
addApprovedProvenance(c, wfi);
@@ -56,20 +58,28 @@ public class FinalEditAction extends ProcessingAction {
}
}
+ @Override
+ public List getOptions() {
+ List options = new ArrayList<>();
+ options.add(SUBMIT_APPROVE);
+ options.add(ProcessingAction.SUBMIT_EDIT_METADATA);
+ return options;
+ }
+
private void addApprovedProvenance(Context c, XmlWorkflowItem wfi) throws SQLException, AuthorizeException {
//Add the provenance for the accept
String now = DCDate.getCurrent().toString();
// Get user's name + email address
String usersName = XmlWorkflowServiceFactory.getInstance().getXmlWorkflowService()
- .getEPersonName(c.getCurrentUser());
+ .getEPersonName(c.getCurrentUser());
String provDescription = getProvenanceStartId() + " Approved for entry into archive by "
- + usersName + " on " + now + " (GMT) ";
+ + usersName + " on " + now + " (GMT) ";
// Add to item as a DC field
itemService.addMetadata(c, wfi.getItem(), MetadataSchemaEnum.DC.getName(), "description", "provenance", "en",
- provDescription);
+ provDescription);
itemService.update(c, wfi.getItem());
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ProcessingAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ProcessingAction.java
index 1fbb02710d..98af6facf3 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ProcessingAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ProcessingAction.java
@@ -34,6 +34,7 @@ public abstract class ProcessingAction extends Action {
@Autowired(required = true)
protected ItemService itemService;
+ protected static final String SUBMIT_EDIT_METADATA = "submit_edit_metadata";
@Override
public boolean isAuthorized(Context context, HttpServletRequest request, XmlWorkflowItem wfi) throws SQLException {
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ReviewAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ReviewAction.java
index 6ccb2c53e6..5284874572 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ReviewAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ReviewAction.java
@@ -9,6 +9,8 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -34,6 +36,8 @@ public class ReviewAction extends ProcessingAction {
public static final int MAIN_PAGE = 0;
public static final int REJECT_PAGE = 1;
+ private static final String SUBMIT_APPROVE = "submit_approve";
+ private static final String SUBMIT_REJECT = "submit_reject";
@Override
public void activate(Context c, XmlWorkflowItem wfItem) {
@@ -43,10 +47,10 @@ public class ReviewAction extends ProcessingAction {
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException, IOException {
- if (request.getParameter("submit_approve") != null) {
+ if (request.getParameter(SUBMIT_APPROVE) != null) {
return processAccept(c, wfi, step, request);
} else {
- if (request.getParameter("submit_reject") != null) {
+ if (request.getParameter(SUBMIT_REJECT) != null) {
return processRejectPage(c, wfi, step, request);
}
}
@@ -54,6 +58,14 @@ public class ReviewAction extends ProcessingAction {
return new ActionResult(ActionResult.TYPE.TYPE_CANCEL);
}
+ @Override
+ public List getOptions() {
+ List options = new ArrayList<>();
+ options.add(SUBMIT_APPROVE);
+ options.add(SUBMIT_REJECT);
+ return options;
+ }
+
public ActionResult processAccept(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException {
//Delete the tasks
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreEvaluationAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreEvaluationAction.java
index df06c6b0de..a834641111 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreEvaluationAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreEvaluationAction.java
@@ -9,6 +9,7 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -17,7 +18,6 @@ import org.dspace.content.Item;
import org.dspace.content.MetadataSchemaEnum;
import org.dspace.content.MetadataValue;
import org.dspace.core.Context;
-import org.dspace.workflow.WorkflowException;
import org.dspace.xmlworkflow.factory.XmlWorkflowServiceFactory;
import org.dspace.xmlworkflow.service.WorkflowRequirementsService;
import org.dspace.xmlworkflow.state.Step;
@@ -40,14 +40,13 @@ public class ScoreEvaluationAction extends ProcessingAction {
private int minimumAcceptanceScore;
@Override
- public void activate(Context c, XmlWorkflowItem wf)
- throws SQLException, IOException, AuthorizeException, WorkflowException {
+ public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException, IOException, WorkflowException {
+ throws SQLException, AuthorizeException, IOException {
boolean hasPassed = false;
//Retrieve all our scores from the metadata & add em up
List scores = itemService
@@ -82,6 +81,11 @@ public class ScoreEvaluationAction extends ProcessingAction {
}
}
+ @Override
+ public List getOptions() {
+ return new ArrayList<>();
+ }
+
public int getMinimumAcceptanceScore() {
return minimumAcceptanceScore;
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreReviewAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreReviewAction.java
index 07780704bc..c28fe2d93e 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreReviewAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/ScoreReviewAction.java
@@ -7,14 +7,14 @@
*/
package org.dspace.xmlworkflow.state.actions.processingaction;
-import java.io.IOException;
import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.app.util.Util;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
-import org.dspace.workflow.WorkflowException;
import org.dspace.xmlworkflow.service.WorkflowRequirementsService;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.actions.ActionResult;
@@ -32,20 +32,21 @@ import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
*/
public class ScoreReviewAction extends ProcessingAction {
+ private static final String SUBMIT_SCORE = "submit_score";
+
@Override
- public void activate(Context c, XmlWorkflowItem wf)
- throws SQLException, IOException, AuthorizeException, WorkflowException {
+ public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException, IOException, WorkflowException {
- if (request.getParameter("submit_score") != null) {
+ throws SQLException, AuthorizeException {
+ if (request.getParameter(SUBMIT_SCORE) != null) {
int score = Util.getIntParameter(request, "score");
//Add our score to the metadata
itemService.addMetadata(c, wfi.getItem(), WorkflowRequirementsService.WORKFLOW_SCHEMA, "score", null, null,
- String.valueOf(score));
+ String.valueOf(score));
itemService.update(c, wfi.getItem());
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
@@ -54,4 +55,9 @@ public class ScoreReviewAction extends ProcessingAction {
return new ActionResult(ActionResult.TYPE.TYPE_SUBMISSION_PAGE);
}
}
+
+ @Override
+ public List getOptions() {
+ return Arrays.asList(SUBMIT_SCORE);
+ }
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SelectReviewerAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SelectReviewerAction.java
index e31756538f..b768b4ff8b 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SelectReviewerAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SelectReviewerAction.java
@@ -7,8 +7,8 @@
*/
package org.dspace.xmlworkflow.state.actions.processingaction;
-import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
@@ -18,7 +18,6 @@ import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.service.EPersonService;
-import org.dspace.workflow.WorkflowException;
import org.dspace.xmlworkflow.Role;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.actions.ActionResult;
@@ -39,36 +38,38 @@ import org.springframework.beans.factory.annotation.Required;
*/
public class SelectReviewerAction extends ProcessingAction {
- public static final int MAIN_PAGE = 0;
public static final int SEARCH_RESULTS_PAGE = 1;
public static final int RESULTS_PER_PAGE = 5;
+ private static final String SUBMIT_CANCEL = "submit_cancel";
+ private static final String SUBMIT_SEARCH = "submit_search";
+ private static final String SUBMIT_SELECT_REVIEWER = "submit_select_reviewer_";
+
private Role role;
@Autowired(required = true)
- protected EPersonService ePersonService;
+ private EPersonService ePersonService;
@Autowired(required = true)
- protected WorkflowItemRoleService workflowItemRoleService;
+ private WorkflowItemRoleService workflowItemRoleService;
@Override
- public void activate(Context c, XmlWorkflowItem wf)
- throws SQLException, IOException, AuthorizeException, WorkflowException {
+ public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException, IOException, WorkflowException {
- String submitButton = Util.getSubmitButton(request, "submit_cancel");
+ throws SQLException, AuthorizeException {
+ String submitButton = Util.getSubmitButton(request, SUBMIT_CANCEL);
//Check if our user has pressed cancel
- if (submitButton.equals("submit_cancel")) {
+ if (submitButton.equals(SUBMIT_CANCEL)) {
//Send us back to the submissions page
return new ActionResult(ActionResult.TYPE.TYPE_CANCEL);
- } else if (submitButton.equals("submit_search")) {
+ } else if (submitButton.equals(SUBMIT_SEARCH)) {
//Perform the search
String query = request.getParameter("query");
int page = Util.getIntParameter(request, "result-page");
@@ -85,7 +86,7 @@ public class SelectReviewerAction extends ProcessingAction {
request.setAttribute("result-page", page);
request.setAttribute("page", SEARCH_RESULTS_PAGE);
return new ActionResult(ActionResult.TYPE.TYPE_PAGE, SEARCH_RESULTS_PAGE);
- } else if (submitButton.startsWith("submit_select_reviewer_")) {
+ } else if (submitButton.startsWith(SUBMIT_SELECT_REVIEWER)) {
//Retrieve the identifier of the eperson which will do the reviewing
UUID reviewerId = UUID.fromString(submitButton.substring(submitButton.lastIndexOf("_") + 1));
EPerson reviewer = ePersonService.find(c, reviewerId);
@@ -102,6 +103,14 @@ public class SelectReviewerAction extends ProcessingAction {
return new ActionResult(ActionResult.TYPE.TYPE_ERROR);
}
+ @Override
+ public List getOptions() {
+ List options = new ArrayList<>();
+ options.add(SUBMIT_SEARCH);
+ options.add(SUBMIT_SELECT_REVIEWER);
+ return options;
+ }
+
public Role getRole() {
return role;
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SingleUserReviewAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SingleUserReviewAction.java
index 215eaaf645..d115832389 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SingleUserReviewAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/processingaction/SingleUserReviewAction.java
@@ -9,6 +9,8 @@ package org.dspace.xmlworkflow.state.actions.processingaction;
import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.app.util.Util;
@@ -38,6 +40,10 @@ public class SingleUserReviewAction extends ProcessingAction {
public static final int OUTCOME_REJECT = 1;
+ protected static final String SUBMIT_APPROVE = "submit_approve";
+ protected static final String SUBMIT_REJECT = "submit_reject";
+ protected static final String SUBMIT_DECLINE_TASK = "submit_decline_task";
+
@Override
public void activate(Context c, XmlWorkflowItem wfItem) {
@@ -58,19 +64,28 @@ public class SingleUserReviewAction extends ProcessingAction {
}
}
+ @Override
+ public List getOptions() {
+ List options = new ArrayList<>();
+ options.add(SUBMIT_APPROVE);
+ options.add(SUBMIT_REJECT);
+ options.add(SUBMIT_DECLINE_TASK);
+ return options;
+ }
+
public ActionResult processMainPage(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
throws SQLException, AuthorizeException {
- if (request.getParameter("submit_approve") != null) {
+ if (request.getParameter(SUBMIT_APPROVE) != null) {
//Delete the tasks
addApprovedProvenance(c, wfi);
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
- } else if (request.getParameter("submit_reject") != null) {
+ } else if (request.getParameter(SUBMIT_REJECT) != null) {
// Make sure we indicate which page we want to process
request.setAttribute("page", REJECT_PAGE);
// We have pressed reject item, so take the user to a page where he can reject
return new ActionResult(ActionResult.TYPE.TYPE_PAGE);
- } else if (request.getParameter("submit_decline_task") != null) {
+ } else if (request.getParameter(SUBMIT_DECLINE_TASK) != null) {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, OUTCOME_REJECT);
} else {
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignAction.java
index 5b8d9b08b8..e837a8a893 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignAction.java
@@ -8,6 +8,8 @@
package org.dspace.xmlworkflow.state.actions.userassignment;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.core.Context;
@@ -34,6 +36,11 @@ public class AssignAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
+ @Override
+ public List getOptions() {
+ return new ArrayList<>();
+ }
+
public void generateTasks() {
}
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignOriginalSubmitterAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignOriginalSubmitterAction.java
index 5786515a81..01d995ccf6 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignOriginalSubmitterAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AssignOriginalSubmitterAction.java
@@ -9,7 +9,9 @@ package org.dspace.xmlworkflow.state.actions.userassignment;
import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
@@ -112,6 +114,11 @@ public class AssignOriginalSubmitterAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
+ @Override
+ public List getOptions() {
+ return new ArrayList<>();
+ }
+
/**
* Create a claimed task for the user IF this user doesn't have a claimed action for this workflow item
*
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AutoAssignAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AutoAssignAction.java
index 3c6ce50b0d..3f87c26029 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AutoAssignAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/AutoAssignAction.java
@@ -9,6 +9,7 @@ package org.dspace.xmlworkflow.state.actions.userassignment;
import java.io.IOException;
import java.sql.SQLException;
+import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -106,6 +107,11 @@ public class AutoAssignAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
+ @Override
+ public List getOptions() {
+ return new ArrayList<>();
+ }
+
/**
* Create a claimed task for the user IF this user doesn't have a claimed action for this workflow item
*
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/ClaimAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/ClaimAction.java
index fb154aa7ed..78742c6553 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/ClaimAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/ClaimAction.java
@@ -10,6 +10,7 @@ package org.dspace.xmlworkflow.state.actions.userassignment;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
+import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
@@ -67,6 +68,11 @@ public class ClaimAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
+ @Override
+ public List getOptions() {
+ return new ArrayList<>();
+ }
+
@Override
public void alertUsersOnActivation(Context c, XmlWorkflowItem wfi, RoleMembers roleMembers)
throws IOException, SQLException {
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/InheritUsersAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/InheritUsersAction.java
index 5e134855a7..1ffce1afdb 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/InheritUsersAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/InheritUsersAction.java
@@ -8,6 +8,8 @@
package org.dspace.xmlworkflow.state.actions.userassignment;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.dspace.core.Context;
@@ -37,6 +39,11 @@ public class InheritUsersAction extends UserSelectionAction {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
+ @Override
+ public List getOptions() {
+ return new ArrayList<>();
+ }
+
@Override
public boolean isFinished(XmlWorkflowItem wfi) {
return false;
diff --git a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/NoUserSelectionAction.java b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/NoUserSelectionAction.java
index 35eeaf1a0e..d23a98cedb 100644
--- a/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/NoUserSelectionAction.java
+++ b/dspace-api/src/main/java/org/dspace/xmlworkflow/state/actions/userassignment/NoUserSelectionAction.java
@@ -7,14 +7,12 @@
*/
package org.dspace.xmlworkflow.state.actions.userassignment;
-import java.io.IOException;
-import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletRequest;
-import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.xmlworkflow.RoleMembers;
-import org.dspace.xmlworkflow.WorkflowConfigurationException;
import org.dspace.xmlworkflow.state.Step;
import org.dspace.xmlworkflow.state.actions.ActionResult;
import org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem;
@@ -34,12 +32,11 @@ public class NoUserSelectionAction extends UserSelectionAction {
}
@Override
- public void regenerateTasks(Context c, XmlWorkflowItem wfi, RoleMembers roleMembers) throws SQLException {
+ public void regenerateTasks(Context c, XmlWorkflowItem wfi, RoleMembers roleMembers) {
}
@Override
- public boolean isValidUserSelection(Context context, XmlWorkflowItem wfi, boolean hasUI)
- throws WorkflowConfigurationException, SQLException {
+ public boolean isValidUserSelection(Context context, XmlWorkflowItem wfi, boolean hasUI) {
return true;
}
@@ -49,12 +46,16 @@ public class NoUserSelectionAction extends UserSelectionAction {
}
@Override
- public void activate(Context c, XmlWorkflowItem wf) throws SQLException, IOException {
+ public void activate(Context c, XmlWorkflowItem wf) {
}
@Override
- public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request)
- throws SQLException, AuthorizeException, IOException {
+ public ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request) {
return new ActionResult(ActionResult.TYPE.TYPE_OUTCOME, ActionResult.OUTCOME_COMPLETE);
}
+
+ @Override
+ public List getOptions() {
+ return new ArrayList<>();
+ }
}
diff --git a/dspace-api/src/test/data/dspace.cfg.more b/dspace-api/src/test/data/dspace.cfg.more
deleted file mode 100644
index c23646b3d8..0000000000
--- a/dspace-api/src/test/data/dspace.cfg.more
+++ /dev/null
@@ -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
diff --git a/dspace-api/src/test/data/dspaceFolder/config/local.cfg b/dspace-api/src/test/data/dspaceFolder/config/local.cfg
index faf6db71ee..3c4b4a839d 100644
--- a/dspace-api/src/test/data/dspaceFolder/config/local.cfg
+++ b/dspace-api/src/test/data/dspaceFolder/config/local.cfg
@@ -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.
diff --git a/dspace-api/src/test/data/dspaceFolder/config/spring/api/access-conditions.xml b/dspace-api/src/test/data/dspaceFolder/config/spring/api/access-conditions.xml
new file mode 100644
index 0000000000..b734c78937
--- /dev/null
+++ b/dspace-api/src/test/data/dspaceFolder/config/spring/api/access-conditions.xml
@@ -0,0 +1,82 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/dspace-api/src/test/data/dspaceFolder/config/spring/api/identifier-service-test.xml b/dspace-api/src/test/data/dspaceFolder/config/spring/api/identifier-service-test.xml
index 3efda0c73b..a5ae684a57 100644
--- a/dspace-api/src/test/data/dspaceFolder/config/spring/api/identifier-service-test.xml
+++ b/dspace-api/src/test/data/dspaceFolder/config/spring/api/identifier-service-test.xml
@@ -21,92 +21,18 @@
autowire="byType"
scope="singleton"/>
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
diff --git a/dspace-api/src/test/data/dspaceFolder/config/spring/api/workflow-actions.xml b/dspace-api/src/test/data/dspaceFolder/config/spring/api/workflow-actions.xml
new file mode 100644
index 0000000000..7381972961
--- /dev/null
+++ b/dspace-api/src/test/data/dspaceFolder/config/spring/api/workflow-actions.xml
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/dspace-api/src/test/data/dspaceFolder/config/spring/api/workflow.xml b/dspace-api/src/test/data/dspaceFolder/config/spring/api/workflow.xml
index 96ebdababd..47f22c5d88 100644
--- a/dspace-api/src/test/data/dspaceFolder/config/spring/api/workflow.xml
+++ b/dspace-api/src/test/data/dspaceFolder/config/spring/api/workflow.xml
@@ -9,8 +9,8 @@
-
-
+
+
diff --git a/dspace-api/src/test/data/dspaceFolder/solr/solr.xml b/dspace-api/src/test/data/dspaceFolder/solr/solr.xml
deleted file mode 100644
index 201cdf7f8a..0000000000
--- a/dspace-api/src/test/data/dspaceFolder/solr/solr.xml
+++ /dev/null
@@ -1,2 +0,0 @@
-
-
diff --git a/dspace-api/src/test/java/org/dspace/AbstractDSpaceTest.java b/dspace-api/src/test/java/org/dspace/AbstractDSpaceTest.java
index 7326b7188e..e53d6a675d 100644
--- a/dspace-api/src/test/java/org/dspace/AbstractDSpaceTest.java
+++ b/dspace-api/src/test/java/org/dspace/AbstractDSpaceTest.java
@@ -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 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());
diff --git a/dspace-api/src/test/java/org/dspace/AbstractUnitTest.java b/dspace-api/src/test/java/org/dspace/AbstractUnitTest.java
index cf8a50fcf6..cd3669b143 100644
--- a/dspace-api/src/test/java/org/dspace/AbstractUnitTest.java
+++ b/dspace-api/src/test/java/org/dspace/AbstractUnitTest.java
@@ -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);
+ }
+ }
+
}
diff --git a/dspace-api/src/test/java/org/dspace/administer/StructBuilderIT.java b/dspace-api/src/test/java/org/dspace/administer/StructBuilderIT.java
index 43b47e83b2..8ff16f5baf 100644
--- a/dspace-api/src/test/java/org/dspace/administer/StructBuilderIT.java
+++ b/dspace-api/src/test/java/org/dspace/administer/StructBuilderIT.java
@@ -15,9 +15,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
-import java.util.Arrays;
import java.util.Iterator;
-import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
@@ -47,7 +45,6 @@ import org.xmlunit.diff.ComparisonFormatter;
import org.xmlunit.diff.DefaultComparisonFormatter;
import org.xmlunit.diff.Diff;
import org.xmlunit.diff.Difference;
-import org.xmlunit.util.Predicate;
/**
* Tests of {@link StructBuilder}.
@@ -314,9 +311,9 @@ public class StructBuilderIT
}
/**
- * Reject uninteresting nodes.
+ * Reject uninteresting nodes. (currently commented out of tests above)
*/
- private static class MyNodeFilter implements Predicate {
+ /*private static class MyNodeFilter implements Predicate {
private static final List dontCare = Arrays.asList(
"description",
"intro",
@@ -330,5 +327,5 @@ public class StructBuilderIT
String type = node.getLocalName();
return ! dontCare.contains(type);
}
- }
+ }*/
}
diff --git a/dspace-api/src/test/java/org/dspace/app/util/GoogleBitstreamComparatorTest.java b/dspace-api/src/test/java/org/dspace/app/util/GoogleBitstreamComparatorTest.java
index 039d634938..84e776b983 100644
--- a/dspace-api/src/test/java/org/dspace/app/util/GoogleBitstreamComparatorTest.java
+++ b/dspace-api/src/test/java/org/dspace/app/util/GoogleBitstreamComparatorTest.java
@@ -8,7 +8,7 @@
package org.dspace.app.util;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
@@ -24,12 +24,8 @@ import org.dspace.core.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-
-@RunWith(MockitoJUnitRunner.class)
public class GoogleBitstreamComparatorTest extends AbstractUnitTest {
@Mock
diff --git a/dspace-api/src/test/java/org/dspace/app/util/GoogleMetadataTest.java b/dspace-api/src/test/java/org/dspace/app/util/GoogleMetadataTest.java
index 5bd95a51bb..e2b49ab76a 100644
--- a/dspace-api/src/test/java/org/dspace/app/util/GoogleMetadataTest.java
+++ b/dspace-api/src/test/java/org/dspace/app/util/GoogleMetadataTest.java
@@ -14,7 +14,9 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
+import java.util.List;
+import com.google.common.base.Splitter;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException;
@@ -85,7 +87,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
} catch (IOException e) {
- e.printStackTrace();
+ log.error("IO Error in init", e);
+ fail("IO Error in init: " + e.getMessage());
}
}
@@ -119,8 +122,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
- String[] urlSplitted = gm.getPDFURL().get(0).split("/");
- assertEquals("Pdf", urlSplitted[urlSplitted.length - 1]);
+ List urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
+ assertEquals("Pdf", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -154,8 +157,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
- String[] urlSplitted = gm.getPDFURL().get(0).split("/");
- assertEquals("size9", urlSplitted[urlSplitted.length - 1]);
+ List urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
+ assertEquals("size9", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -189,8 +192,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
- String[] urlSplitted = gm.getPDFURL().get(0).split("/");
- assertEquals("first", urlSplitted[urlSplitted.length - 1]);
+ List urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
+ assertEquals("first", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -225,8 +228,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
- String[] urlSplitted = gm.getPDFURL().get(0).split("/");
- assertEquals("primary", urlSplitted[urlSplitted.length - 1]);
+ List urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
+ assertEquals("primary", urlSplitted.get(urlSplitted.size() - 1));
}
/**
@@ -261,8 +264,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
- String[] urlSplitted = gm.getPDFURL().get(0).split("/");
- assertEquals("large", urlSplitted[urlSplitted.length - 1]);
+ List urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
+ assertEquals("large", urlSplitted.get(urlSplitted.size() - 1));
}
@@ -285,7 +288,7 @@ public class GoogleMetadataTest extends AbstractUnitTest {
@Test
public void testGetPDFURLWithNoBitstreams() throws Exception {
context.turnOffAuthorisationSystem();
- Bundle bundle = ContentServiceFactory.getInstance().getBundleService().create(context, it, "ORIGINAL");
+ ContentServiceFactory.getInstance().getBundleService().create(context, it, "ORIGINAL");
context.restoreAuthSystemState();
context.commit();
@@ -319,8 +322,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
context.restoreAuthSystemState();
context.commit();
GoogleMetadata gm = new GoogleMetadata(this.context, it);
- String[] urlSplitted = gm.getPDFURL().get(0).split("/");
- assertEquals("small", urlSplitted[urlSplitted.length - 1]);
+ List urlSplitted = Splitter.on("/").splitToList(gm.getPDFURL().get(0));
+ assertEquals("small", urlSplitted.get(urlSplitted.size() - 1));
}
@After
@@ -334,12 +337,8 @@ public class GoogleMetadataTest extends AbstractUnitTest {
community = context.reloadEntity(community);
ContentServiceFactory.getInstance().getCommunityService().delete(context, community);
community = null;
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (AuthorizeException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
+ } catch (Exception e) {
+ throw new AssertionError("Error occurred in destroy()", e);
}
it = null;
super.destroy();
diff --git a/dspace-api/src/test/java/org/dspace/app/util/MockUtil.java b/dspace-api/src/test/java/org/dspace/app/util/MockUtil.java
deleted file mode 100644
index 6043f1b848..0000000000
--- a/dspace-api/src/test/java/org/dspace/app/util/MockUtil.java
+++ /dev/null
@@ -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 {
- /**
- * 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.
- *
- * 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";
- }
-}
diff --git a/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java b/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java
index 3f5a08a648..511ea0da25 100644
--- a/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java
+++ b/dspace-api/src/test/java/org/dspace/authenticate/IPMatcherTest.java
@@ -264,8 +264,8 @@ public class IPMatcherTest {
assertFalse(ipMatcher.match("192.1.2.2"));
}
-
- private ArrayList getAllIp4Except(ArrayList exceptions) {
+ // Commented out as this is currently not used in tests
+ /*private ArrayList getAllIp4Except(ArrayList exceptions) {
int d1 = 0;
int d2 = 0;
int d3 = 0;
@@ -284,7 +284,7 @@ public class IPMatcherTest {
}
}
return ips;
- }
+ }*/
private void verifyAllIp4Except(ArrayList exceptions, boolean asserted, IPMatcher ipMatcher)
throws IPMatcherException {
diff --git a/dspace-api/src/test/java/org/dspace/authorize/AuthorizeServiceTest.java b/dspace-api/src/test/java/org/dspace/authorize/AuthorizeServiceTest.java
index 7cd5873e06..110700070f 100644
--- a/dspace-api/src/test/java/org/dspace/authorize/AuthorizeServiceTest.java
+++ b/dspace-api/src/test/java/org/dspace/authorize/AuthorizeServiceTest.java
@@ -90,8 +90,7 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
@Test
public void testauthorizeMethodRespectSpecialGroups() {
- EPerson eperson1;
- EPerson eperson2;
+ EPerson eperson;
Group group1;
Community dso;
@@ -99,7 +98,7 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
context.turnOffAuthorisationSystem();
// create an eperson and a group
- eperson1 = ePersonService.create(context);
+ eperson = ePersonService.create(context);
group1 = groupService.create(context);
// A group has to have a name, otherwise there are queries that break
groupService.setName(group1, "My test group 2");
@@ -111,19 +110,19 @@ public class AuthorizeServiceTest extends AbstractUnitTest {
// special group to the user. Then test if the action on the DSO
// is allowed for the user
authorizeService.addPolicy(context, dso, Constants.ADD, group1);
- context.setCurrentUser(eperson1);
+ context.setCurrentUser(eperson);
context.setSpecialGroup(group1.getID());
context.commit();
} catch (SQLException | AuthorizeException ex) {
- throw new RuntimeException(ex);
+ throw new AssertionError(ex);
} finally {
context.restoreAuthSystemState();
}
try {
- Assert.assertTrue(authorizeService.authorizeActionBoolean(context, eperson1, dso, Constants.ADD, true));
+ Assert.assertTrue(authorizeService.authorizeActionBoolean(context, eperson, dso, Constants.ADD, true));
} catch (SQLException ex) {
- throw new RuntimeException(ex);
+ throw new AssertionError(ex);
}
}
}
diff --git a/dspace-api/src/test/java/org/dspace/content/BitstreamFormatTest.java b/dspace-api/src/test/java/org/dspace/content/BitstreamFormatTest.java
index c12234635c..958ddc0876 100644
--- a/dspace-api/src/test/java/org/dspace/content/BitstreamFormatTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/BitstreamFormatTest.java
@@ -15,23 +15,24 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.dspace.authorize.AuthorizeException;
-import org.dspace.authorize.AuthorizeServiceImpl;
+import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService;
-import org.dspace.core.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.test.util.ReflectionTestUtils;
/**
* This class tests BitstreamFormat. Due to it being tighly coupled with the
@@ -60,6 +61,11 @@ public class BitstreamFormatTest extends AbstractUnitTest {
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance()
.getBitstreamFormatService();
+ /**
+ * Spy of AuthorizeService to use for tests
+ * (initialized / setup in @Before method)
+ */
+ private AuthorizeService authorizeServiceSpy;
/**
* This method will be run before every test as per @Before. It will
@@ -75,6 +81,13 @@ public class BitstreamFormatTest extends AbstractUnitTest {
try {
bf = bitstreamFormatService.find(context, 5);
bunknown = bitstreamFormatService.findUnknown(context);
+
+ // Initialize our spy of the autowired (global) authorizeService bean.
+ // This allows us to customize the bean's method return values in tests below
+ authorizeServiceSpy = spy(authorizeService);
+ // "Wire" our spy to be used by the current loaded bitstreamFormatService
+ // (To ensure it uses the spy instead of the real service)
+ ReflectionTestUtils.setField(bitstreamFormatService, "authorizeService", authorizeServiceSpy);
} catch (SQLException ex) {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -199,11 +212,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test
public void testCreateAdmin() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
BitstreamFormat found = bitstreamFormatService.create(context);
assertThat("testCreate 0", found, notNullValue());
@@ -219,13 +229,10 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateNotAdmin() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = false;
- }};
+ // Disalow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
- BitstreamFormat found = bitstreamFormatService.create(context);
+ bitstreamFormatService.create(context);
fail("Exception should have been thrown");
}
@@ -442,11 +449,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNotAdmin() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = false;
- }};
+ // Disallow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
bitstreamFormatService.update(context, bf);
fail("Exception should have been thrown");
@@ -457,11 +461,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test
public void testUpdateAdmin() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
String desc = "Test description";
String oldDescription = bf.getDescription();
@@ -478,11 +479,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = AuthorizeException.class)
public void testDeleteNotAdmin() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = false;
- }};
+ // Disallow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
bitstreamFormatService.delete(context, bf);
fail("Exception should have been thrown");
@@ -493,11 +491,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test
public void testDeleteAdmin() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
BitstreamFormat bitstreamFormat = bitstreamFormatService.create(context);
int toDeleteIdentifier = bitstreamFormat.getID();
@@ -511,11 +506,8 @@ public class BitstreamFormatTest extends AbstractUnitTest {
*/
@Test(expected = IllegalArgumentException.class)
public void testDeleteUnknown() throws SQLException, AuthorizeException {
- new NonStrictExpectations(AuthorizeServiceImpl.class) {{
- // Allow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
bitstreamFormatService.delete(context, bunknown);
fail("Exception should have been thrown");
diff --git a/dspace-api/src/test/java/org/dspace/content/BitstreamTest.java b/dspace-api/src/test/java/org/dspace/content/BitstreamTest.java
index b390de4598..b732b90111 100644
--- a/dspace-api/src/test/java/org/dspace/content/BitstreamTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/BitstreamTest.java
@@ -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());
}
diff --git a/dspace-api/src/test/java/org/dspace/content/BundleTest.java b/dspace-api/src/test/java/org/dspace/content/BundleTest.java
index 09e3e704eb..bd8cca912b 100644
--- a/dspace-api/src/test/java/org/dspace/content/BundleTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/BundleTest.java
@@ -15,6 +15,11 @@ import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
import java.io.File;
import java.io.FileInputStream;
@@ -26,16 +31,17 @@ import java.util.Iterator;
import java.util.List;
import java.util.UUID;
-import mockit.NonStrictExpectations;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy;
+import org.dspace.authorize.service.AuthorizeService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.test.util.ReflectionTestUtils;
/**
* Units tests for class Bundle
@@ -56,6 +62,11 @@ public class BundleTest extends AbstractDSpaceObjectTest {
private Collection collection;
private Community owningCommunity;
+ /**
+ * Spy of AuthorizeService to use for tests
+ * (initialized / setup in @Before method)
+ */
+ private AuthorizeService authorizeServiceSpy;
/**
* This method will be run before every test as per @Before. It will
@@ -79,6 +90,15 @@ public class BundleTest extends AbstractDSpaceObjectTest {
//we need to commit the changes so we don't block the table for testing
context.restoreAuthSystemState();
+
+ // Initialize our spy of the autowired (global) authorizeService bean.
+ // This allows us to customize the bean's method return values in tests below
+ authorizeServiceSpy = spy(authorizeService);
+ // "Wire" our spy to be used by the current loaded itemService, bundleService & bitstreamService
+ // (To ensure it uses the spy instead of the real service)
+ ReflectionTestUtils.setField(itemService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(bundleService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(bitstreamService, "authorizeService", authorizeServiceSpy);
} catch (SQLException | AuthorizeException ex) {
log.error("SQL Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -155,14 +175,9 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreate() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- }
- };
+ // Allow Item ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.ADD);
+
Bundle created = bundleService.create(context, item, "testCreateBundle");
//the item created by default has no name nor type set
assertThat("testCreate 0", created, notNullValue());
@@ -221,16 +236,14 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testSetPrimaryBitstreamID() throws SQLException, AuthorizeException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
- }
- };
+ // Allow Item WRITE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
+
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bundleService.addBitstream(context, b, bs);
@@ -243,16 +256,14 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUnsetPrimaryBitstreamID() throws IOException, SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
- }
- };
+ // Allow Item WRITE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
+
//set a value different than default
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
@@ -279,27 +290,25 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetBitstreamByName() throws FileNotFoundException, SQLException, IOException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
-
- }};
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
String name = "name";
//by default there is no bitstream
assertThat("testGetHandle 0", bundleService.getBitstreamByName(b, name), nullValue());
//let's add a bitstream
+ context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, name);
bundleService.addBitstream(context, b, bs);
bundleService.update(context, b);
+ context.restoreAuthSystemState();
+
assertThat("testGetHandle 1", bundleService.getBitstreamByName(b, name), notNullValue());
assertThat("testGetHandle 2", bundleService.getBitstreamByName(b, name), equalTo(bs));
assertThat("testGetHandle 3", bundleService.getBitstreamByName(b, name).getName(), equalTo(name));
@@ -310,27 +319,25 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetBitstreams() throws FileNotFoundException, SQLException, IOException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
-
- }};
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
//default bundle has no bitstreams
assertThat("testGetBitstreams 0", b.getBitstreams(), notNullValue());
assertThat("testGetBitstreams 1", b.getBitstreams().size(), equalTo(0));
//let's add a bitstream
+ context.turnOffAuthorisationSystem();
String name = "name";
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, name);
bundleService.addBitstream(context, b, bs);
+ context.restoreAuthSystemState();
+
assertThat("testGetBitstreams 2", b.getBitstreams(), notNullValue());
assertThat("testGetBitstreams 3", b.getBitstreams().size(), equalTo(1));
assertThat("testGetBitstreams 4", b.getBitstreams().get(0).getName(), equalTo(name));
@@ -352,16 +359,11 @@ public class BundleTest extends AbstractDSpaceObjectTest {
@Test(expected = AuthorizeException.class)
public void testCreateBitstreamNoAuth()
throws FileNotFoundException, AuthorizeException, SQLException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = new AuthorizeException();
-
- }};
+ // Disallow Bundle ADD permissions
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
File f = new File(testProps.get("test.bitstream").toString());
- Bitstream bs = bitstreamService.create(context, b, new FileInputStream(f));
+ bitstreamService.create(context, b, new FileInputStream(f));
fail("Exception should be thrown");
}
@@ -370,16 +372,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateBitstreamAuth() throws FileNotFoundException, AuthorizeException, SQLException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
-
- }};
+ // Allow Item WRITE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
String name = "name";
File f = new File(testProps.get("test.bitstream").toString());
@@ -395,17 +394,12 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRegisterBitstreamNoAuth() throws AuthorizeException, IOException, SQLException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = new AuthorizeException();
-
- }};
+ // Disallow Bundle ADD permissions
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
int assetstore = 0; //default assetstore
File f = new File(testProps.get("test.bitstream").toString());
- Bitstream bs = bitstreamService.register(context, b, assetstore, f.getAbsolutePath());
+ bitstreamService.register(context, b, assetstore, f.getAbsolutePath());
fail("Exception should be thrown");
}
@@ -414,16 +408,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRegisterBitstreamAuth() throws AuthorizeException, IOException, SQLException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
-
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow Item WRITE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
int assetstore = 0; //default assetstore
String name = "name bitstream";
@@ -440,13 +431,8 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testAddBitstreamNoAuth() throws SQLException, AuthorizeException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = new AuthorizeException();
-
- }};
+ // Disallow Bundle ADD permissions
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
// create a new Bitstream to add to Bundle
File f = new File(testProps.get("test.bitstream").toString());
@@ -461,16 +447,13 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testAddBitstreamAuth() throws SQLException, AuthorizeException, FileNotFoundException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
-
- }};
+ // Allow Item WRITE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
@@ -487,17 +470,15 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveBitstreamNoAuth() throws SQLException, AuthorizeException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Bundle REMOVE perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.REMOVE);
- result = new AuthorizeException();
-
- }};
+ // Disallow Bundle ADD permissions
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, b, Constants.REMOVE);
File f = new File(testProps.get("test.bitstream").toString());
+ context.turnOffAuthorisationSystem();
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, "name");
+ context.restoreAuthSystemState();
+
bundleService.removeBitstream(context, b, bs);
fail("Exception should have been thrown");
}
@@ -507,28 +488,26 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveBitstreamAuth() throws SQLException, AuthorizeException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms (to create a new Bitstream and add it)
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- // Allow Bundle REMOVE perms (to test remove)
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.REMOVE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
- authorizeService.authorizeAction(context, (Bitstream) any,
- Constants.DELETE);
- result = null;
-
- }};
+ // Allow Item WRITE permissions (to create a new bitstream)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+ // Allow Bundle ADD permissions (to create a new bitstream)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bundle REMOVE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.REMOVE);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
+ // Allow Bitstream DELETE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.DELETE));
// Create a new Bitstream to test with
+ context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bundleService.addBitstream(context, b, bs);
+ context.restoreAuthSystemState();
+
bundleService.removeBitstream(context, b, bs);
assertThat("testRemoveBitstreamAuth 0", bundleService.getBitstreamByName(b, bs.getName()), nullValue());
}
@@ -549,19 +528,10 @@ public class BundleTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testDelete() throws SQLException, AuthorizeException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms (to create a new Bitstream and add it)
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- // Allow Bundle REMOVE perms (to test remove)
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.REMOVE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.DELETE);
- result = null;
- }};
+ // Allow Item REMOVE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.REMOVE);
+ // Allow Bundle DELETE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.DELETE);
UUID id = b.getID();
itemService.removeBundle(context, item, b);
@@ -676,17 +646,18 @@ public class BundleTest extends AbstractDSpaceObjectTest {
@Test
public void testSetOrder() throws SQLException, AuthorizeException, FileNotFoundException, IOException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Bundle ADD perms
- authorizeService.authorizeAction((Context) any, (Bundle) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Bitstream) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow Item WRITE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+ // Allow Bundle ADD permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.ADD);
+ // Allow Bundle WRITE permissions
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, b, Constants.WRITE);
+ // Allow Bitstream WRITE permissions
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
// Create three Bitstreams to test ordering with. Give them different names
+ context.turnOffAuthorisationSystem();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bs = bitstreamService.create(context, new FileInputStream(f));
bs.setName(context, "bitstream1");
@@ -697,6 +668,7 @@ public class BundleTest extends AbstractDSpaceObjectTest {
Bitstream bs3 = bitstreamService.create(context, new FileInputStream(f));
bs3.setName(context, "bitstream3");
bundleService.addBitstream(context, b, bs3);
+ context.restoreAuthSystemState();
// Assert Bitstreams are in the order added
Bitstream[] bitstreams = b.getBitstreams().toArray(new Bitstream[b.getBitstreams().size()]);
diff --git a/dspace-api/src/test/java/org/dspace/content/CollectionTest.java b/dspace-api/src/test/java/org/dspace/content/CollectionTest.java
index 1e6c7f553a..0b50c53615 100644
--- a/dspace-api/src/test/java/org/dspace/content/CollectionTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/CollectionTest.java
@@ -15,19 +15,23 @@ 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;
-import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
-import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
-import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authorize.AuthorizeException;
+import org.dspace.authorize.factory.AuthorizeServiceFactory;
+import org.dspace.authorize.service.AuthorizeService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.factory.CoreServiceFactory;
@@ -37,6 +41,7 @@ import org.dspace.eperson.Group;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit Tests for class Collection
@@ -59,6 +64,12 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
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
* initialize resources required for the tests.
@@ -78,6 +89,18 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
this.dspaceObject = collection;
//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(communityService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(collectionService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(itemService, "authorizeService", authorizeServiceSpy);
+ // Also wire into current AuthorizeServiceFactory, as that is used for some checks (e.g. AuthorizeUtil)
+ ReflectionTestUtils.setField(AuthorizeServiceFactory.getInstance(), "authorizeService",
+ authorizeServiceSpy);
} catch (AuthorizeException ex) {
log.error("Authorization Error in init", ex);
fail("Authorization Error in init: " + ex.getMessage());
@@ -97,29 +120,22 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
@After
@Override
public void destroy() {
+ context.turnOffAuthorisationSystem();
+ // Delete community & collection created in init()
try {
- if (collection != null) {
- context.turnOffAuthorisationSystem();
- collectionService.update(context, collection);
- communityService.update(context, owningCommunity);
- collection = collectionService.find(context, collection.getID());
- if (collection != null) {
- collectionService.delete(context, collection);
- communityService.delete(context, communityService.find(context, owningCommunity.getID()));
- }
- context.restoreAuthSystemState();
- }
-
- } catch (SQLException ex) {
- log.error("SQL Error in init", ex);
- fail("SQL Error in init: " + ex.getMessage());
- } catch (AuthorizeException ex) {
- log.error("Authorization Error in init", ex);
- fail("Authorization Error in init: " + ex.getMessage());
- } catch (IOException ex) {
- log.error("IO Error in init", ex);
- fail("IO Error in init: " + ex.getMessage());
+ collectionService.delete(context, collection);
+ } catch (Exception e) {
+ // ignore
}
+ try {
+ communityService.delete(context, owningCommunity);
+ } catch (Exception e) {
+ // ignore
+ }
+ context.restoreAuthSystemState();
+
+ collection = null;
+ owningCommunity = null;
super.destroy();
}
@@ -141,12 +157,9 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreate() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
+ // Allow Community ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.ADD);
- }};
Collection created = collectionService.create(context, owningCommunity);
assertThat("testCreate 0", created, notNullValue());
assertThat("testCreate 1", created.getName(), equalTo(""));
@@ -157,12 +170,9 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateWithValidHandle() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
+ // Allow Community ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.ADD);
- }};
// test creating collection with a specified handle which is NOT already in use
// (this handle should not already be used by system, as it doesn't start with "1234567689" prefix)
Collection created = collectionService.create(context, owningCommunity, "987654321/100");
@@ -178,18 +188,15 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = IllegalStateException.class)
public void testCreateWithInvalidHandle() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
+ // Allow Community ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.ADD);
- }};
//get handle of our default created collection
String inUseHandle = collection.getHandle();
// test creating collection with a specified handle which IS already in use
// This should throw an exception
- Collection created = collectionService.create(context, owningCommunity, inUseHandle);
+ collectionService.create(context, owningCommunity, inUseHandle);
fail("Exception expected");
}
@@ -284,7 +291,6 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
String itext = "introductory text";
String copy = "copyright declaration";
String sidebar = "side bar text";
- String tempItem = "3";
String provDesc = "provenance description";
String license = "license text";
@@ -330,21 +336,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testSetLogoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, true);
File f = new File(testProps.get("test.bitstream").toString());
Bitstream logo = collectionService.setLogo(context, collection, new FileInputStream(f));
@@ -359,86 +352,15 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testSetLogoAuth2() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow parent Community WRITE perms (test inheritance to Collection)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.WRITE, true);
File f = new File(testProps.get("test.bitstream").toString());
Bitstream logo = collectionService.setLogo(context, collection, new FileInputStream(f));
- assertThat("testSetLogoAuth2 0", collection.getLogo(), equalTo(logo));
+ assertThat("testSetLogoAuth 0", collection.getLogo(), equalTo(logo));
collection.setLogo(null);
- assertThat("testSetLogoAuth2 1", collection.getLogo(), nullValue());
- }
-
- /**
- * Test of setLogo method, of class Collection.
- */
- @Test
- public void testSetLogoAuth3() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- File f = new File(testProps.get("test.bitstream").toString());
- Bitstream logo = collectionService.setLogo(context, collection, new FileInputStream(f));
- assertThat("testSetLogoAuth3 0", collection.getLogo(), equalTo(logo));
-
- collection.setLogo(null);
- assertThat("testSetLogoAuth3 1", collection.getLogo(), nullValue());
- }
-
- /**
- * Test of setLogo method, of class Collection.
- */
- @Test
- public void testSetLogoAuth4() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- File f = new File(testProps.get("test.bitstream").toString());
- Bitstream logo = collectionService.setLogo(context, collection, new FileInputStream(f));
- assertThat("testSetLogoAuth4 0", collection.getLogo(), equalTo(logo));
-
- collection.setLogo(null);
- assertThat("testSetLogoAuth4 1", collection.getLogo(), nullValue());
+ assertThat("testSetLogoAuth 1", collection.getLogo(), nullValue());
}
/**
@@ -446,25 +368,9 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testSetLogoNoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
- }};
-
File f = new File(testProps.get("test.bitstream").toString());
- Bitstream logo = collectionService.setLogo(context, collection, new FileInputStream(f));
- fail("EXception expected");
+ collectionService.setLogo(context, collection, new FileInputStream(f));
+ fail("Exception expected");
}
/**
@@ -472,11 +378,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateWorkflowGroupAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage WorkflowsGroup perms
- AuthorizeUtil.authorizeManageWorkflowsGroup((Context) any, (Collection) any);
- result = null;
- }};
+ // Allow Collection ADMIN (to manage workflow group)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADMIN);
int step = 1;
Group result = collectionService.createWorkflowGroup(context, collection, step);
@@ -488,14 +391,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateWorkflowGroupNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow manage WorkflowsGroup perms
- AuthorizeUtil.authorizeManageWorkflowsGroup((Context) any, (Collection) any);
- result = new AuthorizeException();
- }};
-
int step = 1;
- Group result = collectionService.createWorkflowGroup(context, collection, step);
+ collectionService.createWorkflowGroup(context, collection, step);
fail("Exception expected");
}
@@ -551,11 +448,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateSubmittersAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage SubmittersGroup perms
- AuthorizeUtil.authorizeManageSubmittersGroup((Context) any, (Collection) any);
- result = null;
- }};
+ // Allow Collection ADMIN (to manage submitter group)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADMIN);
Group result = collectionService.createSubmitters(context, collection);
assertThat("testCreateSubmittersAuth 0", result, notNullValue());
@@ -566,13 +460,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateSubmittersNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow manage SubmittersGroup perms
- AuthorizeUtil.authorizeManageSubmittersGroup((Context) any, (Collection) any);
- result = new AuthorizeException();
- }};
-
- Group result = collectionService.createSubmitters(context, collection);
+ collectionService.createSubmitters(context, collection);
fail("Exception expected");
}
@@ -581,11 +469,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveSubmittersAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage SubmittersGroup perms
- AuthorizeUtil.authorizeManageSubmittersGroup((Context) any, (Collection) any);
- result = null;
- }};
+ // Allow Collection ADMIN (to manage submitter group)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADMIN);
collectionService.removeSubmitters(context, collection);
assertThat("testRemoveSubmittersAuth 0", collection.getSubmitters(), nullValue());
@@ -596,12 +481,6 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveSubmittersNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow manage SubmittersGroup perms
- AuthorizeUtil.authorizeManageSubmittersGroup((Context) any, (Collection) any);
- result = new AuthorizeException();
- }};
-
collectionService.removeSubmitters(context, collection);
fail("Exception expected");
}
@@ -619,11 +498,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateAdministratorsAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage AdminGroup perms
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Collection) any);
- result = null;
- }};
+ // Allow Collection ADMIN (to manage admin group)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADMIN);
Group result = collectionService.createAdministrators(context, collection);
assertThat("testCreateAdministratorsAuth 0", result, notNullValue());
@@ -634,13 +510,7 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateAdministratorsNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow manage AdminGroup perms
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Collection) any);
- result = new AuthorizeException();
- }};
-
- Group result = collectionService.createAdministrators(context, collection);
+ collectionService.createAdministrators(context, collection);
fail("Exception expected");
}
@@ -649,17 +519,14 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveAdministratorsAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage AdminGroup perms (needed to possibly create group first)
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Collection) any);
- result = null;
- // Allow remove AdminGroup perms
- AuthorizeUtil.authorizeRemoveAdminGroup((Context) any, (Collection) any);
- result = null;
- }};
+ // Allow parent Community ADMIN (only Community Admins can delete a Collection Admin group)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.ADMIN);
// Ensure admin group is created first
+ context.turnOffAuthorisationSystem();
Group result = collectionService.createAdministrators(context, collection);
+ context.restoreAuthSystemState();
+
assertThat("testRemoveAdministratorsAuth 0", collection.getAdministrators(), notNullValue());
assertThat("testRemoveAdministratorsAuth 1", collection.getAdministrators(), equalTo(result));
collectionService.removeAdministrators(context, collection);
@@ -671,17 +538,11 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveAdministratorsNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage AdminGroup perms (needed to possibly create group first)
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Collection) any);
- result = null;
- // Disallow remove AdminGroup perms
- AuthorizeUtil.authorizeRemoveAdminGroup((Context) any, (Collection) any);
- result = new AuthorizeException();
- }};
-
// Ensure admin group is created first
+ context.turnOffAuthorisationSystem();
Group result = collectionService.createAdministrators(context, collection);
+ context.restoreAuthSystemState();
+
assertThat("testRemoveAdministratorsAuth 0", collection.getAdministrators(), notNullValue());
assertThat("testRemoveAdministratorsAuth 1", collection.getAdministrators(), equalTo(result));
collectionService.removeAdministrators(context, collection);
@@ -749,11 +610,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateTemplateItemAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage TemplateItem perms
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = null;
- }};
+ // Allow Collection ADMIN (to manage template item)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADMIN);
itemService.createTemplateItem(context, collection);
assertThat("testCreateTemplateItemAuth 0", collection.getTemplateItem(), notNullValue());
@@ -764,12 +622,6 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateTemplateItemNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow manage TemplateItem perms
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = new AuthorizeException();
- }};
-
itemService.createTemplateItem(context, collection);
fail("Exception expected");
}
@@ -779,11 +631,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveTemplateItemAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage TemplateItem perms
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = null;
- }};
+ // Allow Collection ADMIN (to manage template item)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADMIN);
collectionService.removeTemplateItem(context, collection);
assertThat("testRemoveTemplateItemAuth 0", collection.getTemplateItem(), nullValue());
@@ -794,12 +643,6 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveTemplateItemNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow manage TemplateItem perms
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = new AuthorizeException();
- }};
-
collectionService.removeTemplateItem(context, collection);
fail("Exception expected");
}
@@ -809,18 +652,15 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testAddItemAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Collection ADD permissions
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow Collection ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADD);
+ // create item first
+ context.turnOffAuthorisationSystem();
WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false);
Item item = installItemService.installItem(context, workspaceItem);
+ context.restoreAuthSystemState();
+
collectionService.addItem(context, collection, item);
boolean added = false;
Iterator- ii = itemService.findByCollection(context, collection);
@@ -837,15 +677,15 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testAddItemNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Collection ADD permissions
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.ADD);
- result = new AuthorizeException();
- }};
+ // Disallow Collection ADD perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADD);
+ // create item first
+ context.turnOffAuthorisationSystem();
WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false);
Item item = installItemService.installItem(context, workspaceItem);
+ context.restoreAuthSystemState();
+
collectionService.addItem(context, collection, item);
fail("Exception expected");
}
@@ -855,25 +695,24 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveItemAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Collection ADD/REMOVE permissions
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.REMOVE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.DELETE);
- result = null;
- }};
+ // Allow Collection REMOVE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.REMOVE);
+ // Allow Item DELETE perms
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Item.class), eq(Constants.DELETE));
+ // Allow Item REMOVE perms
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Item.class), eq(Constants.REMOVE));
+ // Allow Item WRITE perms (Needed to remove identifiers, e.g. DOI, before Item deletion)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Item.class), eq(Constants.WRITE));
+ // create & add item first
+ context.turnOffAuthorisationSystem();
WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false);
Item item = installItemService.installItem(context, workspaceItem);
collectionService.addItem(context, collection, item);
+ context.restoreAuthSystemState();
collectionService.removeItem(context, collection, item);
boolean isthere = false;
@@ -891,20 +730,16 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveItemNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Collection ADD permissions
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.ADD);
- result = null;
- // Disallow Collection REMOVE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.REMOVE);
- result = new AuthorizeException();
- }};
+ // Disallow Collection REMOVE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy)
+ .authorizeAction(context, collection, Constants.REMOVE);
+ // create & add item first
+ context.turnOffAuthorisationSystem();
WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false);
Item item = installItemService.installItem(context, workspaceItem);
collectionService.addItem(context, collection, item);
+ context.restoreAuthSystemState();
collectionService.removeItem(context, collection, item);
fail("Exception expected");
@@ -915,21 +750,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUpdateAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, true);
//TODO: how to check update?
collectionService.update(context, collection);
@@ -940,71 +762,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUpdateAuth2() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- //TODO: how to check update?
- collectionService.update(context, collection);
- }
-
- /**
- * Test of update method, of class Collection.
- */
- @Test
- public void testUpdateAuth3() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- //TODO: how to check update?
- collectionService.update(context, collection);
- }
-
- /**
- * Test of update method, of class Collection.
- */
- @Test
- public void testUpdateAuth4() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow parent Community WRITE perms (test inheritance to Collection)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.WRITE, true);
//TODO: how to check update?
collectionService.update(context, collection);
@@ -1015,21 +774,9 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
- }};
+ // Disallow Collection WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy)
+ .authorizeAction(context, collection, Constants.WRITE, true);
collectionService.update(context, collection);
fail("Exception expected");
@@ -1040,21 +787,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, true);
assertTrue("testCanEditBooleanAuth 0", collectionService.canEditBoolean(context, collection));
}
@@ -1064,93 +798,21 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanAuth2() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow parent Community WRITE perms (test inheritance to Collection)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.WRITE, true);
+
assertTrue("testCanEditBooleanAuth2 0", collectionService.canEditBoolean(context, collection));
}
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditBooleanAuth3() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth3 0", collectionService.canEditBoolean(context, collection));
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditBooleanAuth4() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth4 0", collectionService.canEditBoolean(context, collection));
- }
-
/**
* Test of canEditBoolean method, of class Collection.
*/
@Test
public void testCanEditBooleanNoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
- }};
+ // Disallow Collection WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy)
+ .authorizeAction(context, collection, Constants.WRITE, true);
assertFalse("testCanEditBooleanNoAuth 0", collectionService.canEditBoolean(context, collection));
}
@@ -1159,214 +821,56 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
* Test of canEditBoolean method, of class Collection.
*/
@Test
- public void testCanEditBooleanAuth_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ public void testCanEditBooleanAuth_useInheritance() throws Exception {
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, true);
- assertTrue("testCanEditBooleanAuth_boolean 0", collectionService.canEditBoolean(context, collection, true));
+ assertTrue("testCanEditBooleanAuth_useInheritance",
+ collectionService.canEditBoolean(context, collection, true));
}
/**
* Test of canEditBoolean method, of class Collection.
*/
@Test
- public void testCanEditBooleanAuth2_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ public void testCanEditBooleanAuth2_useInheritance() throws Exception {
+ // Allow parent Community WRITE perms (test inheritance to Collection)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.WRITE, true);
- assertTrue("testCanEditBooleanAuth2_boolean 0", collectionService.canEditBoolean(context, collection, true));
+ assertTrue("testCanEditBooleanAuth2_useInheritance",
+ collectionService.canEditBoolean(context, collection, true));
}
/**
* Test of canEditBoolean method, of class Collection.
*/
@Test
- public void testCanEditBooleanAuth3_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ public void testCanEditBooleanAuth_noInheritance() throws Exception {
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, false);
- assertTrue("testCanEditBooleanAuth3_boolean 0", collectionService.canEditBoolean(context, collection, true));
+ assertTrue("testCanEditBooleanAuth_noInheritance",
+ collectionService.canEditBoolean(context, collection, false));
}
/**
* Test of canEditBoolean method, of class Collection.
*/
@Test
- public void testCanEditBooleanAuth4_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth4_boolean 0", collectionService.canEditBoolean(context, collection, true));
+ public void testCanEditBooleanAuth2_noInheritance() throws Exception {
+ assertFalse("testCanEditBooleanAuth_noInheritance",
+ collectionService.canEditBoolean(context, collection, false));
}
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditBooleanAuth5_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth5_boolean 0", collectionService.canEditBoolean(context, collection, false));
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditBooleanAuth6_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth6_boolean 0", collectionService.canEditBoolean(context, collection, false));
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditBooleanAuth7_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth7_boolean 0", collectionService.canEditBoolean(context, collection, false));
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditBooleanAuth8_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth8_boolean 0", collectionService.canEditBoolean(context, collection, false));
- }
/**
* Test of canEditBoolean method, of class Collection.
*/
@Test
public void testCanEditBooleanNoAuth_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
- }};
+ // Disallow Collection WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy)
+ .authorizeAction(context, collection, Constants.WRITE, true);
assertFalse("testCanEditBooleanNoAuth_boolean 0", collectionService.canEditBoolean(context, collection, true));
}
@@ -1376,21 +880,9 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanNoAuth2_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = new AuthorizeException();
- }};
+ // Disallow Collection WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy)
+ .authorizeAction(context, collection, Constants.WRITE, false);
assertFalse("testCanEditBooleanNoAuth_boolean 0", collectionService.canEditBoolean(context, collection, false));
}
@@ -1400,96 +892,8 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditAuth_0args() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- //TODO: how to check??
- collectionService.canEdit(context, collection);
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth2_0args() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- //TODO: how to check??
- collectionService.canEdit(context, collection);
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth3_0args() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- //TODO: how to check??
- collectionService.canEdit(context, collection);
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth4_0args() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, true);
//TODO: how to check??
collectionService.canEdit(context, collection);
@@ -1500,21 +904,9 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCanEditNoAuth_0args() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
- }};
+ // Disallow Collection WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy)
+ .authorizeAction(context, collection, Constants.WRITE, true);
collectionService.canEdit(context, collection);
fail("Exception expected");
@@ -1525,23 +917,10 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditAuth_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, true);
- //TOO: how to check?
+ //TODO: how to check?
collectionService.canEdit(context, collection, true);
}
@@ -1550,24 +929,11 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditAuth2_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, false);
- //TOO: how to check?
- collectionService.canEdit(context, collection, true);
+ //TODO: how to check?
+ collectionService.canEdit(context, collection, false);
}
/**
@@ -1575,173 +941,17 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditAuth3_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow parent Community WRITE perms (test inheritance to Collection)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, owningCommunity, Constants.WRITE, true);
- //TOO: how to check?
collectionService.canEdit(context, collection, true);
}
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth4_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
- //TOO: how to check?
- collectionService.canEdit(context, collection, true);
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth5_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- //TOO: how to check?
- collectionService.canEdit(context, collection, false);
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth6_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = true;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- //TOO: how to check?
- collectionService.canEdit(context, collection, false);
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth7_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- //TOO: how to check?
- collectionService.canEdit(context, collection, false);
- }
-
- /**
- * Test of canEditBoolean method, of class Collection.
- */
- @Test
- public void testCanEditAuth8_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = false;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
- //TOO: how to check?
- collectionService.canEdit(context, collection, false);
- }
-
/**
* Test of canEditBoolean method, of class Collection.
*/
@Test(expected = AuthorizeException.class)
public void testCanEditNoAuth_boolean() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
- }};
-
- //TOO: how to check?
collectionService.canEdit(context, collection, false);
fail("Exception expected");
}
@@ -1751,23 +961,6 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCanEditNoAuth2_boolean() throws Exception {
- // Test permissions with inheritance turned *OFF*
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, false);
- result = false;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = new AuthorizeException();
- }};
-
- //TOO: how to check?
collectionService.canEdit(context, collection, true);
fail("Exception expected");
}
@@ -1777,15 +970,10 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testDeleteAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class, authorizeService.getClass()) {{
- // Allow manage TemplateItem perms
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = null;
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, anyBoolean);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.WRITE, true);
+ // Allow Collection ADMIN perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADMIN);
UUID id = collection.getID();
collectionService.delete(context, collection);
@@ -1798,35 +986,6 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testDeleteNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class, authorizeService.getClass()) {{
- // Disallow manage TemplateItem perms
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = new AuthorizeException();
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, anyBoolean);
- result = null;
- }};
-
- collectionService.delete(context, collection);
- fail("Exception expected");
- }
-
- /**
- * Test of delete method, of class Collection.
- */
- @Test(expected = AuthorizeException.class)
- public void testDeleteNoAuth2() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class, authorizeService.getClass()) {{
- // Allow manage TemplateItem perms
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = null;
- // Disallow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, anyBoolean);
- result = new AuthorizeException();
- }};
-
collectionService.delete(context, collection);
fail("Exception expected");
}
@@ -1863,13 +1022,13 @@ public class CollectionTest extends AbstractDSpaceObjectTest {
@Test
@SuppressWarnings("ObjectEqualsNull")
public void testEquals() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- }};
+ // create a new collection for testing
+ context.turnOffAuthorisationSystem();
+ Collection newCollection = collectionService.create(context, owningCommunity);
+ context.restoreAuthSystemState();
+
assertFalse("testEquals 0", collection.equals(null));
- assertFalse("testEquals 1", collection.equals(collectionService.create(context, owningCommunity)));
+ assertFalse("testEquals 1", collection.equals(newCollection));
assertTrue("testEquals 2", collection.equals(collection));
}
diff --git a/dspace-api/src/test/java/org/dspace/content/CommunityTest.java b/dspace-api/src/test/java/org/dspace/content/CommunityTest.java
index ace4bb6c14..812060d019 100644
--- a/dspace-api/src/test/java/org/dspace/content/CommunityTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/CommunityTest.java
@@ -16,6 +16,12 @@ 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 static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
@@ -23,16 +29,17 @@ import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
-import mockit.NonStrictExpectations;
import org.apache.logging.log4j.Logger;
-import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authorize.AuthorizeException;
+import org.dspace.authorize.factory.AuthorizeServiceFactory;
+import org.dspace.authorize.service.AuthorizeService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.Group;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit Tests for class Community
@@ -51,6 +58,12 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
private Community c;
+ /**
+ * 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.
@@ -70,6 +83,18 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
this.dspaceObject = c;
//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 both these services use the spy instead of the real service)
+ ReflectionTestUtils.setField(communityService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(collectionService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(itemService, "authorizeService", authorizeServiceSpy);
+ // Also wire into current AuthorizeServiceFactory, as that is used for some checks (e.g. AuthorizeUtil)
+ ReflectionTestUtils.setField(AuthorizeServiceFactory.getInstance(), "authorizeService",
+ authorizeServiceSpy);
} catch (AuthorizeException ex) {
log.error("Authorization Error in init", ex);
fail("Authorization Error in init: " + ex.getMessage());
@@ -89,6 +114,15 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
@After
@Override
public void destroy() {
+ context.turnOffAuthorisationSystem();
+ // Delete community created in init()
+ try {
+ communityService.delete(context, c);
+ } catch (Exception e) {
+ // ignore
+ }
+ context.restoreAuthSystemState();
+
c = null;
super.destroy();
}
@@ -111,20 +145,11 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateAuth() throws Exception {
- //Default to Community-Admin Rights (but not full Admin rights)
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms (needed for addSubCommunity functionality)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow current Community ADD perms (needed to just create community)
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Disallow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = false;
- }};
+ // Below settings default to Community-Admin Rights (but not full Admin rights)
+ // Allow parent Community ADD perms (needed to just create community)
+ when(authorizeServiceSpy.authorizeActionBoolean(context, c, Constants.ADD)).thenReturn(true);
+ // Disallow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
// test that a Community Admin can create a Community with parent (Sub-Community)
Community sub = communityService.create(c, context);
@@ -141,16 +166,9 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateAuth2() throws Exception {
- //Default to Admin Rights, but NOT Community Admin Rights
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Allow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Below settings default to Full Admin Rights (but not Community Admin rights)
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
//Test that a full Admin can create a Community without a parent (Top-Level Community)
Community created = communityService.create(null, context);
@@ -172,42 +190,12 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateNoAuth() throws Exception {
- //Default to NO Admin Rights, and NO Community Admin Rights
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Disallow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = false;
- }};
+ // Disallow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(false);
- // test creating community with no parent (as a non-admin & non-Community Admin)
+ // test creating community with no parent (as a non-admin)
// this should throw an exception
- Community created = communityService.create(null, context);
- fail("Exception expected");
- }
-
- /**
- * Test of create method, of class Community.
- */
- @Test(expected = AuthorizeException.class)
- public void testCreateNoAuth2() throws Exception {
- //Default to Community-Admin Rights (but not full Admin rights)
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Disallow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = false;
- }};
-
- // test creating community with no parent (as a non-admin, but with Community Admin rights)
- // this should throw an exception, as only admins can create Top Level communities
- Community created = communityService.create(null, context);
+ communityService.create(null, context);
fail("Exception expected");
}
@@ -216,16 +204,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateWithValidHandle() throws Exception {
- //Default to Admin Rights, but NOT Community Admin Rights
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Allow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
// test creating community with a specified handle which is NOT already in use
// (this handle should not already be used by system, as it doesn't start with "1234567689" prefix)
@@ -242,23 +222,15 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = IllegalStateException.class)
public void testCreateWithInvalidHandle() throws Exception {
- //Default to Admin Rights, but NOT Community Admin Rights
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Allow full Admin perms
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
//get handle of our default created community
String inUseHandle = c.getHandle();
// test creating community with a specified handle which IS already in use
// This should throw an exception
- Community created = communityService.create(null, context, inUseHandle);
+ communityService.create(null, context, inUseHandle);
fail("Exception expected");
}
@@ -386,21 +358,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testSetLogoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = true;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow current Community WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE);
File f = new File(testProps.get("test.bitstream").toString());
Bitstream logo = communityService.setLogo(context, c, new FileInputStream(f));
@@ -410,117 +369,17 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
assertThat("testSetLogoAuth 1", c.getLogo(), nullValue());
}
- /**
- * Test of setLogo method, of class Community.
- */
- @Test
- public void testSetLogoAuth2() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = true;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- File f = new File(testProps.get("test.bitstream").toString());
- Bitstream logo = communityService.setLogo(context, c, new FileInputStream(f));
- assertThat("testSetLogoAuth2 0", c.getLogo(), equalTo(logo));
-
- c.setLogo(null);
- assertThat("testSetLogoAuth2 1", c.getLogo(), nullValue());
- }
-
- /**
- * Test of setLogo method, of class Community.
- */
- @Test
- public void testSetLogoAuth3() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- File f = new File(testProps.get("test.bitstream").toString());
- Bitstream logo = communityService.setLogo(context, c, new FileInputStream(f));
- assertThat("testSetLogoAuth3 0", c.getLogo(), equalTo(logo));
-
- c.setLogo(null);
- assertThat("testSetLogoAuth3 1", c.getLogo(), nullValue());
- }
-
- /**
- * Test of setLogo method, of class Community.
- */
- @Test
- public void testSetLogoAuth4() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- File f = new File(testProps.get("test.bitstream").toString());
- Bitstream logo = communityService.setLogo(context, c, new FileInputStream(f));
- assertThat("testSetLogoAuth4 0", c.getLogo(), equalTo(logo));
-
- c.setLogo(null);
- assertThat("testSetLogoAuth4 1", c.getLogo(), nullValue());
- }
-
/**
* Test of setLogo method, of class Community.
*/
@Test(expected = AuthorizeException.class)
public void testSetLogoNoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Disallow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = new AuthorizeException();
- }};
+ // Disallow current Community WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE);
File f = new File(testProps.get("test.bitstream").toString());
- Bitstream logo = communityService.setLogo(context, c, new FileInputStream(f));
- fail("EXception expected");
+ communityService.setLogo(context, c, new FileInputStream(f));
+ fail("Exception expected");
}
/**
@@ -528,16 +387,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = new AuthorizeException();
- // Disallow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = new AuthorizeException();
- }};
+ // Disallow current Community WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE);
//TODO: we need to verify the update, how?
communityService.update(context, c);
@@ -549,16 +400,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUpdateAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow current Community WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE);
//TODO: we need to verify the update, how?
communityService.update(context, c);
@@ -569,11 +412,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateAdministratorsAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage AdminGroup perms
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Community) any);
- result = null;
- }};
+ // Allow Community ADMIN perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADMIN);
Group result = communityService.createAdministrators(context, c);
assertThat("testCreateAdministratorsAuth 0", c.getAdministrators(), notNullValue());
@@ -585,14 +425,7 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateAdministratorsNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow manage AdminGroup perms
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Community) any);
- result = new AuthorizeException();
-
- }};
-
- Group result = communityService.createAdministrators(context, c);
+ communityService.createAdministrators(context, c);
fail("Exception should have been thrown");
}
@@ -602,17 +435,14 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveAdministratorsAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage AdminGroup perms (needed to possibly create group first)
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Community) any);
- result = null;
- // Allow remove AdminGroup perms
- AuthorizeUtil.authorizeRemoveAdminGroup((Context) any, (Community) any);
- result = null;
- }};
+ // Allow Full ADMIN perms (Community Admins cannot delete their Admin Group)
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
// Ensure admin group is created first
+ context.turnOffAuthorisationSystem();
Group result = communityService.createAdministrators(context, c);
+ context.restoreAuthSystemState();
+
assertThat("testRemoveAdministratorsAuth 0", c.getAdministrators(), notNullValue());
assertThat("testRemoveAdministratorsAuth 1", c.getAdministrators(), equalTo(result));
communityService.removeAdministrators(context, c);
@@ -624,17 +454,14 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveAdministratorsNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow manage AdminGroup perms (needed to possibly create group first)
- AuthorizeUtil.authorizeManageAdminGroup((Context) any, (Community) any);
- result = null;
- // Disallow remove AdminGroup perms
- AuthorizeUtil.authorizeRemoveAdminGroup((Context) any, (Community) any);
- result = new AuthorizeException();
- }};
+ // Allow Community ADMIN perms (Community Admins cannot delete their Admin Group)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADMIN);
// Ensure admin group is created first
+ context.turnOffAuthorisationSystem();
Group result = communityService.createAdministrators(context, c);
+ context.restoreAuthSystemState();
+
assertThat("testRemoveAdministratorsAuth 0", c.getAdministrators(), notNullValue());
assertThat("testRemoveAdministratorsAuth 1", c.getAdministrators(), equalTo(result));
communityService.removeAdministrators(context, c);
@@ -655,17 +482,6 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetCollections() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
//empty by default
assertThat("testGetCollections 0", c.getCollections(), notNullValue());
assertTrue("testGetCollections 1", c.getCollections().size() == 0);
@@ -697,17 +513,6 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetSubcommunities() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
-
//empty by default
assertThat("testGetSubcommunities 0", c.getSubcommunities(), notNullValue());
assertTrue("testGetSubcommunities 1", c.getSubcommunities().size() == 0);
@@ -739,22 +544,13 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetParentCommunity() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
-
//null by default
assertThat("testGetParentCommunity 0", c.getParentCommunities().size(), equalTo(0));
- //community with parent
+ //community with parent
+ context.turnOffAuthorisationSystem();
Community son = communityService.create(c, context);
+ context.restoreAuthSystemState();
assertThat("testGetParentCommunity 1", son.getParentCommunities().size(), not(0));
assertThat("testGetParentCommunity 2", son.getParentCommunities().get(0), equalTo(c));
}
@@ -764,23 +560,14 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetAllParents() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
-
//empty by default
assertThat("testGetAllParents 0", communityService.getAllParents(context, c), notNullValue());
assertTrue("testGetAllParents 1", communityService.getAllParents(context, c).size() == 0);
- //community with parent
+ //community with parent
+ context.turnOffAuthorisationSystem();
Community son = communityService.create(c, context);
+ context.restoreAuthSystemState();
assertThat("testGetAllParents 2", communityService.getAllParents(context, son), notNullValue());
assertTrue("testGetAllParents 3", communityService.getAllParents(context, son).size() == 1);
assertThat("testGetAllParents 4", communityService.getAllParents(context, son).get(0), equalTo(c));
@@ -791,25 +578,16 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testGetAllCollections() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
-
//empty by default
assertThat("testGetAllCollections 0", communityService.getAllCollections(context, c), notNullValue());
assertTrue("testGetAllCollections 1", communityService.getAllCollections(context, c).size() == 0);
//community has a collection and a subcommunity, subcommunity has a collection
+ context.turnOffAuthorisationSystem();
Collection collOfC = collectionService.create(context, c);
Community sub = communityService.create(c, context);
Collection collOfSub = collectionService.create(context, sub);
+ context.restoreAuthSystemState();
assertThat("testGetAllCollections 2", communityService.getAllCollections(context, c), notNullValue());
assertTrue("testGetAllCollections 3", communityService.getAllCollections(context, c).size() == 2);
assertThat("testGetAllCollections 4", communityService.getAllCollections(context, c).get(0),
@@ -822,13 +600,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateCollectionAuth() throws Exception {
- // Need current Community ADD permissions in order to create a Collection
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- }};
+ // Allow current Community ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADD);
Collection result = collectionService.create(context, c);
assertThat("testCreateCollectionAuth 0", result, notNullValue());
@@ -841,14 +614,10 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateCollectionNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = new AuthorizeException();
- }};
+ // Disallow current Community ADD perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADD);
- Collection result = collectionService.create(context, c);
+ collectionService.create(context, c);
fail("Exception expected");
}
@@ -857,12 +626,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testAddCollectionAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- }};
+ // Allow current Community ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADD);
Collection col = collectionService.create(context, c);
c.addCollection(col);
@@ -875,12 +640,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testAddCollectionNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = new AuthorizeException();
- }};
+ // Disallow current Community ADD perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADD);
Collection col = collectionService.create(context, c);
c.addCollection(col);
@@ -892,16 +653,10 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateSubcommunityAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
+ // Allow current Community ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADD);
+ // Allow parent Community ADD perms
+ when(authorizeServiceSpy.authorizeActionBoolean(context, c, Constants.ADD)).thenReturn(true);
Community result = communityService.createSubcommunity(context, c);
assertThat("testCreateSubcommunityAuth 0", c.getSubcommunities(), notNullValue());
@@ -914,18 +669,10 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateSubcommunityNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = new AuthorizeException();
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
+ // Disallow current Community ADD perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADD);
- Community result = communityService.createSubcommunity(context, c);
+ communityService.createSubcommunity(context, c);
fail("Exception expected");
}
@@ -934,16 +681,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testAddSubcommunityAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
+ // Allow current Community ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.ADD);
// Turn off authorization temporarily to create a new top-level community
context.turnOffAuthorisationSystem();
@@ -961,18 +700,11 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testAddSubcommunityNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = new AuthorizeException();
- // Allow *parent* Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- }};
-
+ // Turn off authorization temporarily to create a new top-level community
+ context.turnOffAuthorisationSystem();
Community result = communityService.create(null, context);
+ context.restoreAuthSystemState();
+
communityService.addSubcommunity(context, c, result);
fail("Exception expected");
}
@@ -982,30 +714,23 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveCollectionAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass(), AuthorizeUtil.class) {{
- // Allow current Community ADD perms (to add Collection)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow current Community REMOVE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.REMOVE);
- result = null;
- // Allow Collection ManageTemplateItem perms (needed to delete Collection)
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = null;
- // Allow Collection WRITE perms (needed to delete Collection)
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
-
+ // Turn off authorization temporarily to create a new Collection
+ context.turnOffAuthorisationSystem();
Collection col = collectionService.create(context, c);
+ context.restoreAuthSystemState();
assertThat("testRemoveCollectionAuth 0", c.getCollections(), notNullValue());
assertTrue("testRemoveCollectionAuth 1", c.getCollections().size() == 1);
assertThat("testRemoveCollectionAuth 2", c.getCollections().get(0), equalTo(col));
- c.removeCollection(col);
+ // Allow current Community REMOVE perms (to remove Collection from Community & delete)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.REMOVE);
+ // Allow collection WRITE perms (needed to remove Logo before Collection can be deleted)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, col, Constants.WRITE,true);
+ // Allow current Community ADMIN perms (to remove Collection from Community & delete)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, col, Constants.ADMIN);
+
+ // Note that this will *also* delete the collection (hence the extra permissions provided above)
+ communityService.removeCollection(context, c, col);
assertThat("testRemoveCollectionAuth 3", c.getCollections(), notNullValue());
assertTrue("testRemoveCollectionAuth 4", c.getCollections().size() == 0);
}
@@ -1015,18 +740,13 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveCollectionNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Disallow current Community REMOVE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.REMOVE);
- result = new AuthorizeException();
- }};
+ // Disallow current Community REMOVE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.REMOVE);
+ // Turn off authorization temporarily to create a new Collection
+ context.turnOffAuthorisationSystem();
Collection col = collectionService.create(context, c);
+ context.restoreAuthSystemState();
assertThat("testRemoveCollectionNoAuth 0", c.getCollections(), notNullValue());
assertTrue("testRemoveCollectionNoAuth 1", c.getCollections().size() == 1);
assertThat("testRemoveCollectionNoAuth 2", c.getCollections().get(0), equalTo(col));
@@ -1040,20 +760,15 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveSubcommunityAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Community ADD perms (in order to add a new subcommunity to parent)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD, true);
- result = null;
- // Allow Community REMOVE perms (needed to unmap/remove subcommunity)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.REMOVE, true);
- result = null;
- // Allow Community DELETE perms (needed to actually delete subcommunity)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.DELETE, true);
- result = null;
- }};
+ // Allow current Community ADD perms (in order to add a new subcommunity to parent)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.ADD), eq(true));
+ // Allow current Community REMOVE perms (needed to unmap/remove subcommunity)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.REMOVE), eq(true));
+ // Allow current Community REMOVE perms (needed to actually delete subcommunity)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.DELETE), eq(true));
// Turn off authorization temporarily to create a new top-level community
context.turnOffAuthorisationSystem();
@@ -1075,24 +790,12 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testDeleteAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms (to create content to be deleted)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow current Community WRITE perms (to create content to be deleted)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- // Allow current Community DELETE perms (needed to delete community)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.DELETE);
- result = null;
- // Disallow *parent* Community REMOVE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.REMOVE);
- result = false;
- }};
+ // Allow current Community WRITE perms (to create content to be deleted)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.WRITE));
+ // Allow current Community DELETE perms (needed to delete community)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.DELETE));
// Turn off authorization temporarily to create a new top-level community
context.turnOffAuthorisationSystem();
@@ -1111,24 +814,12 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testDeleteAuth2() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow current Community ADD perms (to create content to be deleted)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.ADD);
- result = null;
- // Allow current Community WRITE perms (to create content to be deleted)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- // Allow current Community DELETE perms (needed to delete community)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.DELETE);
- result = null;
- // Allow *parent* Community REMOVE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.REMOVE, true);
- result = true;
- }};
+ // Allow current Community WRITE perms
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.WRITE));
+ // Allow current Community DELETE perms (needed to delete community)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.DELETE));
// Turn off authorization temporarily to create a new top-level community
context.turnOffAuthorisationSystem();
@@ -1147,28 +838,27 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testDeleteHierachyAuth() throws Exception {
- System.out.println("testDeleteHierarchyAuth");
- new NonStrictExpectations(authorizeService.getClass(), AuthorizeUtil.class) {{
- // Allow current Community DELETE perms (needed to delete a community)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.DELETE, true);
- result = null;
- // Allow current Community REMOVE perms (needed to remove a sub-community from a community)
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.REMOVE, true);
- result = null;
- // Allow Collection ManageTemplateItem perms (needed to delete a collection)
- AuthorizeUtil.authorizeManageTemplateItem((Context) any, (Collection) any);
- result = null;
- // Allow current Collection DELETE perms (needed to delete a Collection)
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.DELETE, true);
- result = null;
- // Allow current Item WRITE perms (needed to remove identifiers from an Item prior to deletion)
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow current Community DELETE perms (needed to delete a community)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.DELETE), eq(true));
+ // Allow current Community REMOVE perms (needed to remove a sub-community from a community)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class), eq(Constants.REMOVE), eq(true));
+ // Allow current Collection DELETE perms (needed to delete a Collection)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Collection.class), eq(Constants.DELETE), eq(true));
+ // Allow current Collection ADMIN perms (needed to delete a Collection)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Collection.class), eq(Constants.ADMIN));
+ // Allow current Item WRITE perms (needed to remove identifiers from an Item prior to deletion)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Item.class), eq(Constants.WRITE), eq(true));
+ // Allow current Item DELETE perms (needed to delete Item)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Item.class), eq(Constants.DELETE), eq(true));
+ // Allow current Item REMOVE perms (needed to delete Item)
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Item.class), eq(Constants.REMOVE), eq(true));
// Create a dummy Community hierarchy to test delete with
// Turn off authorization temporarily to create some test objects.
@@ -1183,8 +873,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
// Create two separate items
WorkspaceItem wsItem = workspaceItemService.create(context, childCol, false);
Item item = installItemService.installItem(context, wsItem);
- wsItem = workspaceItemService.create(context, childCol, false);
- item = installItemService.installItem(context, wsItem);
+ wsItem = workspaceItemService.create(context, grandchildCol, false);
+ Item item2 = installItemService.installItem(context, wsItem);
// Done creating the objects. Turn auth system back on
context.restoreAuthSystemState();
@@ -1196,6 +886,7 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
UUID childColId = childCol.getID();
UUID grandchildColId = grandchildCol.getID();
UUID itemId = item.getID();
+ UUID item2Id = item2.getID();
// Delete the parent of this entire hierarchy
communityService.delete(context, parent);
@@ -1213,6 +904,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
collectionService.find(context, grandchildColId), nullValue());
assertThat("Item not deleted",
itemService.find(context, itemId), nullValue());
+ assertThat("Item not deleted",
+ itemService.find(context, item2Id), nullValue());
}
/**
@@ -1220,16 +913,10 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testDeleteNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow current Community DELETE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.DELETE);
- result = new AuthorizeException();
- // Disallow *parent* Community REMOVE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.REMOVE);
- result = false;
- }};
+ // Disallow current Community DELETE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Community.class),
+ eq(Constants.DELETE));
communityService.delete(context, c);
fail("Exception expected");
@@ -1241,11 +928,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
@Test
@SuppressWarnings("ObjectEqualsNull")
public void testEquals() throws SQLException, AuthorizeException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow full Admin perms (just to create top-level community)
- authorizeService.isAdmin((Context) any);
- result = true;
- }};
+ // Allow full Admin perms (just to create top-level community)
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
assertFalse("testEquals 0", c.equals(null));
assertFalse("testEquals 1", c.equals(communityService.create(null, context)));
@@ -1266,117 +950,20 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = true;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow current Community WRITE perms
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(context, c, Constants.WRITE);
assertTrue("testCanEditBooleanAuth 0", communityService.canEditBoolean(context, c));
}
- /**
- * Test of canEditBoolean method, of class Community.
- */
- @Test
- public void testCanEditBooleanAuth2() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = true;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth2 0", communityService.canEditBoolean(context, c));
- }
-
- /**
- * Test of canEditBoolean method, of class Community.
- */
- @Test
- public void testCanEditBooleanAuth3() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth3 0", communityService.canEditBoolean(context, c));
- }
-
- /**
- * Test of canEditBoolean method, of class Community.
- */
- @Test
- public void testCanEditBooleanAuth4() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- assertTrue("testCanEditBooleanAuth4 0", communityService.canEditBoolean(context, c));
- }
-
/**
* Test of canEditBoolean method, of class Community.
*/
@Test
public void testCanEditBooleanNoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Disallow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = new AuthorizeException();
- }};
+ // Disallow current Community WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE);
assertFalse("testCanEditBooleanNoAuth 0", communityService.canEditBoolean(context, c));
}
@@ -1386,93 +973,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = true;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- communityService.canEdit(context, c);
- }
-
- /**
- * Test of canEdit method, of class Community.
- */
- @Test
- public void testCanEditAuth1() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Allow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = true;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- communityService.canEdit(context, c);
- }
-
- /**
- * Test of canEdit method, of class Community.
- */
- @Test
- public void testCanEditAuth2() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = true;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
-
- communityService.canEdit(context, c);
- }
-
- /**
- * Test of canEdit method, of class Community.
- */
- @Test
- public void testCanEditAuth3() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Allow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow current Community WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE);
communityService.canEdit(context, c);
}
@@ -1482,21 +984,8 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCanEditNoAuth() throws Exception {
- // Test inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow parent Community ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD);
- result = false;
- // Disallow parent Community WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE);
- result = false;
- // Disallow current Community WRITE perms
- authorizeService.authorizeAction((Context) any, (Community) any,
- Constants.WRITE);
- result = new AuthorizeException();
- }};
+ // Disallow current Community WRITE perms
+ doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c,Constants.WRITE);
communityService.canEdit(context, c);
fail("Exception expected");
@@ -1545,7 +1034,7 @@ public class CommunityTest extends AbstractDSpaceObjectTest {
assertThat("testGetParentObject 1", communityService.getParentObject(context, son), notNullValue());
assertThat("testGetParentObject 2", (Community) communityService.getParentObject(context, son), equalTo(c));
} catch (AuthorizeException ex) {
- fail("Authorize exception catched");
+ throw new AssertionError("AuthorizeException occurred", ex);
}
}
diff --git a/dspace-api/src/test/java/org/dspace/content/DCDateTest.java b/dspace-api/src/test/java/org/dspace/content/DCDateTest.java
index e827fb4434..8ed97bd46f 100644
--- a/dspace-api/src/test/java/org/dspace/content/DCDateTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/DCDateTest.java
@@ -19,7 +19,6 @@ import java.util.Locale;
import java.util.TimeZone;
import org.apache.commons.lang3.time.DateUtils;
-import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -28,11 +27,6 @@ import org.junit.Test;
* @author pvillega
*/
public class DCDateTest {
- /**
- * log4j category
- */
- private static Logger log = org.apache.logging.log4j.LogManager.getLogger(DCDateTest.class);
-
/**
* Object to use in the tests
*/
diff --git a/dspace-api/src/test/java/org/dspace/content/EntityServiceImplTest.java b/dspace-api/src/test/java/org/dspace/content/EntityServiceImplTest.java
index 5aa9d97b79..f4563cebf0 100644
--- a/dspace-api/src/test/java/org/dspace/content/EntityServiceImplTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/EntityServiceImplTest.java
@@ -8,16 +8,14 @@
package org.dspace.content;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
-import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
-import org.dspace.content.dao.RelationshipTypeDAO;
import org.dspace.content.service.EntityTypeService;
import org.dspace.content.service.ItemService;
import org.dspace.content.service.RelationshipService;
@@ -27,7 +25,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
+import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class EntityServiceImplTest {
@@ -60,10 +58,8 @@ public class EntityServiceImplTest {
public void testfindByItemId() throws Exception {
// Declare objects utilized in unit test
Item item = mock(Item.class);
- List
relationshipList = new ArrayList<>();
Relationship relationship = mock(Relationship.class);
relationship.setId(9);
- relationshipList.add(relationship);
// Mock the state of objects utilized in findByItemId() to meet the success criteria of an invocation
when(itemService.find(any(), any())).thenReturn(item);
@@ -79,10 +75,6 @@ public class EntityServiceImplTest {
// Declare objects utilized in unit test
Entity entity = mock(Entity.class);
EntityTypeService entityTypeService = mock(EntityTypeService.class);
- Item item = mock(Item.class);
- List list = new ArrayList<>();
- MetadataValue metadataValue = mock(MetadataValue.class);
- list.add(metadataValue);
EntityType entityType = entityTypeService.findByEntityType(context, "testType");
// The returned EntityType should equal our defined entityType case
@@ -151,11 +143,7 @@ public class EntityServiceImplTest {
@Test
public void testGetAllRelationshipTypes() throws Exception {
// Declare objects utilized for this test
- List list = new ArrayList<>();
- MetadataValue metadataValue = mock(MetadataValue.class);
- list.add(metadataValue);
Item item = mock(Item.class);
- RelationshipTypeDAO relationshipTypeDAO = mock(RelationshipTypeDAO.class);
Entity entity = mock(Entity.class);
RelationshipType relationshipType = mock(RelationshipType.class);
relationshipType.setLeftType(leftType);
@@ -185,7 +173,7 @@ public class EntityServiceImplTest {
RelationshipType relationshipType = mock(RelationshipType.class);
// Currently this unit test will only test one case with one relationshipType
- List relationshipTypeList = new LinkedList<>();
+ List relationshipTypeList = new ArrayList<>();
relationshipTypeList.add(relationshipType);
List metsList = new ArrayList<>();
MetadataValue metadataValue = mock(MetadataValue.class);
@@ -213,7 +201,7 @@ public class EntityServiceImplTest {
RelationshipType relationshipType = mock(RelationshipType.class);
// Currently this unit test will only test one case with one relationshipType
- List relationshipTypeList = new LinkedList<>();
+ List relationshipTypeList = new ArrayList<>();
relationshipTypeList.add(relationshipType);
List metsList = new ArrayList<>();
MetadataValue metadataValue = mock(MetadataValue.class);
@@ -236,7 +224,7 @@ public class EntityServiceImplTest {
@Test
public void testGetRelationshipTypesByTypeName() throws Exception {
// Declare objects utilized in unit test
- List list = new LinkedList<>();
+ List list = new ArrayList<>();
RelationshipType relationshipType = mock(RelationshipType.class);
list.add(relationshipType);
diff --git a/dspace-api/src/test/java/org/dspace/content/EntityTypeServiceImplTest.java b/dspace-api/src/test/java/org/dspace/content/EntityTypeServiceImplTest.java
index 707323deb5..c54f0fc955 100644
--- a/dspace-api/src/test/java/org/dspace/content/EntityTypeServiceImplTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/EntityTypeServiceImplTest.java
@@ -8,7 +8,7 @@
package org.dspace.content;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
@@ -23,7 +23,7 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
+import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class EntityTypeServiceImplTest {
diff --git a/dspace-api/src/test/java/org/dspace/content/FormatIdentifierTest.java b/dspace-api/src/test/java/org/dspace/content/FormatIdentifierTest.java
index 4e0711aac0..1e4854044e 100644
--- a/dspace-api/src/test/java/org/dspace/content/FormatIdentifierTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/FormatIdentifierTest.java
@@ -14,7 +14,6 @@ import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.FileInputStream;
-import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService;
@@ -30,11 +29,6 @@ import org.junit.Test;
*/
public class FormatIdentifierTest extends AbstractUnitTest {
- /**
- * log4j category
- */
- private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(FormatIdentifierTest.class);
-
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance()
.getBitstreamFormatService();
@@ -71,8 +65,8 @@ public class FormatIdentifierTest extends AbstractUnitTest {
@Test
public void testGuessFormat() throws Exception {
File f = new File(testProps.get("test.bitstream").toString());
- Bitstream bs = null;
- BitstreamFormat result = null;
+ Bitstream bs;
+ BitstreamFormat result;
BitstreamFormat pdf = bitstreamFormatService.findByShortDescription(context, "Adobe PDF");
//test null filename
diff --git a/dspace-api/src/test/java/org/dspace/content/ITCommunityCollection.java b/dspace-api/src/test/java/org/dspace/content/ITCommunityCollection.java
index e7f9c29794..ca197e67a9 100644
--- a/dspace-api/src/test/java/org/dspace/content/ITCommunityCollection.java
+++ b/dspace-api/src/test/java/org/dspace/content/ITCommunityCollection.java
@@ -19,7 +19,6 @@ import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;
-import org.apache.logging.log4j.Logger;
import org.dspace.AbstractIntegrationTest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.factory.ContentServiceFactory;
@@ -48,11 +47,6 @@ import org.junit.Test;
* @author tdonohue
*/
public class ITCommunityCollection extends AbstractIntegrationTest {
- /**
- * log4j category
- */
- private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ITCommunityCollection.class);
-
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
@@ -107,8 +101,8 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
//verify it works as expected
assertThat("testCreateTree 0", parent.getParentCommunities().size(), is(0));
assertThat("testCreateTree 1", child1.getParentCommunities().get(0), equalTo(parent));
- assertThat("testCreateTree 2", (Community) collectionService.getParentObject(context, col1), equalTo(child1));
- assertThat("testCreateTree 3", (Community) collectionService.getParentObject(context, col2), equalTo(child1));
+ assertThat("testCreateTree 2", collectionService.getParentObject(context, col1), equalTo(child1));
+ assertThat("testCreateTree 3", collectionService.getParentObject(context, col2), equalTo(child1));
context.turnOffAuthorisationSystem();
communityService.delete(context, parent);
@@ -133,8 +127,8 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
context.restoreAuthSystemState();
//verify it works as expected
- assertThat("testCreateItems 0", (Collection) itemService.getParentObject(context, item1), equalTo(col1));
- assertThat("testCreateItems 1", (Collection) itemService.getParentObject(context, item2), equalTo(col2));
+ assertThat("testCreateItems 0", itemService.getParentObject(context, item1), equalTo(col1));
+ assertThat("testCreateItems 1", itemService.getParentObject(context, item2), equalTo(col2));
context.turnOffAuthorisationSystem();
communityService.delete(context, parent);
@@ -158,8 +152,8 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
// Add same number of items to each collection
for (int count = 0; count < items_per_collection; count++) {
- Item item1 = installItemService.installItem(context, workspaceItemService.create(context, col1, false));
- Item item2 = installItemService.installItem(context, workspaceItemService.create(context, col2, false));
+ installItemService.installItem(context, workspaceItemService.create(context, col1, false));
+ installItemService.installItem(context, workspaceItemService.create(context, col2, false));
}
// Finally, let's throw in a small wrench and add a mapped item
@@ -229,7 +223,6 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
context.setCurrentUser(commAdmin);
// Test deletion of single Bitstream as a Community Admin (delete just flags as deleted)
- UUID bitstreamId = bitstream.getID();
bitstreamService.delete(context, bitstream);
assertTrue("Community Admin unable to flag Bitstream as deleted",
bitstream.isDeleted());
@@ -312,7 +305,6 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
context.setCurrentUser(collAdmin);
// Test deletion of single Bitstream as a Collection Admin (delete just flags as deleted)
- UUID bitstreamId = bitstream2.getID();
bitstreamService.delete(context, bitstream2);
assertTrue("Collection Admin unable to flag Bitstream as deleted",
bitstream2.isDeleted());
@@ -327,7 +319,6 @@ public class ITCommunityCollection extends AbstractIntegrationTest {
// Test deletion of single Item as a Collection Admin
UUID itemId = item.getID();
bundleId = bundle.getID();
- bitstreamId = bitstream.getID();
itemService.delete(context, item);
assertThat("Collection Admin unable to delete sub-Item",
itemService.find(context, itemId), nullValue());
diff --git a/dspace-api/src/test/java/org/dspace/content/ITMetadata.java b/dspace-api/src/test/java/org/dspace/content/ITMetadata.java
index 10afd4d85f..651b712ba3 100644
--- a/dspace-api/src/test/java/org/dspace/content/ITMetadata.java
+++ b/dspace-api/src/test/java/org/dspace/content/ITMetadata.java
@@ -16,7 +16,6 @@ import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
-import org.apache.logging.log4j.Logger;
import org.dspace.AbstractIntegrationTest;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.factory.ContentServiceFactory;
@@ -37,11 +36,6 @@ import org.junit.Test;
* @author pvillega
*/
public class ITMetadata extends AbstractIntegrationTest {
- /**
- * log4j category
- */
- private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(ITMetadata.class);
-
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
diff --git a/dspace-api/src/test/java/org/dspace/content/InProgressSubmissionTest.java b/dspace-api/src/test/java/org/dspace/content/InProgressSubmissionTest.java
index 78be99bb01..1bcac66985 100644
--- a/dspace-api/src/test/java/org/dspace/content/InProgressSubmissionTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/InProgressSubmissionTest.java
@@ -7,7 +7,6 @@
*/
package org.dspace.content;
-import org.apache.logging.log4j.Logger;
import org.dspace.AbstractUnitTest;
import org.junit.After;
import org.junit.Before;
@@ -23,11 +22,6 @@ import org.junit.Test;
*/
public class InProgressSubmissionTest extends AbstractUnitTest {
- /**
- * log4j category
- */
- private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(InProgressSubmissionTest.class);
-
/**
* This method will be run before every test as per @Before. It will
* initialize resources required for the tests.
diff --git a/dspace-api/src/test/java/org/dspace/content/InstallItemTest.java b/dspace-api/src/test/java/org/dspace/content/InstallItemTest.java
index 129727bd14..62d48cbb5d 100644
--- a/dspace-api/src/test/java/org/dspace/content/InstallItemTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/InstallItemTest.java
@@ -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");
}
diff --git a/dspace-api/src/test/java/org/dspace/content/ItemComparatorTest.java b/dspace-api/src/test/java/org/dspace/content/ItemComparatorTest.java
index 73c8bc0eb5..54ff9ce026 100644
--- a/dspace-api/src/test/java/org/dspace/content/ItemComparatorTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/ItemComparatorTest.java
@@ -132,8 +132,8 @@ public class ItemComparatorTest extends AbstractUnitTest {
*/
@Test
public void testCompare() throws SQLException {
- int result = 0;
- ItemComparator ic = null;
+ int result;
+ ItemComparator ic;
//one of the tiems has no value
ic = new ItemComparator("test", "one", Item.ANY, true);
@@ -246,7 +246,7 @@ public class ItemComparatorTest extends AbstractUnitTest {
@SuppressWarnings( {"ObjectEqualsNull", "IncompatibleEquals"})
public void testEquals() {
ItemComparator ic = new ItemComparator("test", "one", Item.ANY, true);
- ItemComparator target = null;
+ ItemComparator target;
assertFalse("testEquals 0", ic.equals(null));
assertFalse("testEquals 1", ic.equals("test one"));
diff --git a/dspace-api/src/test/java/org/dspace/content/ItemTest.java b/dspace-api/src/test/java/org/dspace/content/ItemTest.java
index 4287957c8e..8c3cfa5a04 100644
--- a/dspace-api/src/test/java/org/dspace/content/ItemTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/ItemTest.java
@@ -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.spy;
+import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
@@ -28,15 +33,14 @@ import java.util.Iterator;
import java.util.List;
import java.util.UUID;
-import mockit.NonStrictExpectations;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.Logger;
-import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy;
+import org.dspace.authorize.factory.AuthorizeServiceFactory;
+import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService;
-import org.dspace.content.service.CollectionService;
import org.dspace.content.service.MetadataFieldService;
import org.dspace.content.service.MetadataSchemaService;
import org.dspace.core.Constants;
@@ -46,6 +50,7 @@ import org.dspace.eperson.Group;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.test.util.ReflectionTestUtils;
/**
* Unit Tests for class Item
@@ -70,11 +75,15 @@ public class ItemTest extends AbstractDSpaceObjectTest {
.getBitstreamFormatService();
private MetadataFieldService metadataFieldService = ContentServiceFactory.getInstance().getMetadataFieldService();
- private CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
-
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
@@ -92,14 +101,24 @@ public class ItemTest extends AbstractDSpaceObjectTest {
context.turnOffAuthorisationSystem();
this.owningCommunity = communityService.create(null, context);
this.collection = collectionService.create(context, owningCommunity);
- WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false);
+ WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, true);
this.it = installItemService.installItem(context, workspaceItem);
-
- it.setSubmitter(context.getCurrentUser());
- itemService.update(context, it);
this.dspaceObject = it;
- //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(collectionService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(itemService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(workspaceItemService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(bundleService, "authorizeService", authorizeServiceSpy);
+ ReflectionTestUtils.setField(bitstreamService, "authorizeService", authorizeServiceSpy);
+ // Also wire into current AuthorizeServiceFactory, as that is used for some checks (e.g. AuthorizeUtil)
+ ReflectionTestUtils.setField(AuthorizeServiceFactory.getInstance(), "authorizeService",
+ authorizeServiceSpy);
} catch (AuthorizeException ex) {
log.error("Authorization Error in init", ex);
fail("Authorization Error in init: " + ex.getMessage());
@@ -169,15 +188,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreate() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms (needed to create an Item)
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow Collection WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADD);
+
Item created = createItem();
assertThat("testCreate 0", created, notNullValue());
assertThat("testCreate 1", created.getName(), nullValue());
@@ -239,7 +252,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
Iterator- all = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince(context,
DateUtils.addDays(it.getLastModified(),1));
assertThat("Returned list should not be null", all, notNullValue());
- boolean added = false;
+ boolean added = false;
while (all.hasNext()) {
Item tmp = all.next();
if (tmp.equals(it)) {
@@ -252,7 +265,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
all = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince(context,
DateUtils.addDays(it.getLastModified(),-1));
assertThat("Returned list should not be null", all, notNullValue());
- added = false;
+ added = false;
while (all.hasNext()) {
Item tmp = all.next();
if (tmp.equals(it)) {
@@ -268,7 +281,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
all = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince(context,
DateUtils.addDays(it.getLastModified(),-1));
assertThat("Returned list should not be null", all, notNullValue());
- added = false;
+ added = false;
while (all.hasNext()) {
Item tmp = all.next();
if (tmp.equals(it)) {
@@ -282,7 +295,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
all = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince(context,
DateUtils.addDays(it.getLastModified(),-1));
assertThat("Returned list should not be null", all, notNullValue());
- added = false;
+ added = false;
while (all.hasNext()) {
Item tmp = all.next();
if (tmp.equals(it)) {
@@ -291,7 +304,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
}
// Test 7: We should not find our item in this list
assertFalse("List should not contain non-discoverable items", added);
- }
+ }
+
/**
* Test of findInArchiveOrWithdrawnNonDiscoverableModifiedSince method, of class Item.
*/
@@ -305,7 +319,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
Iterator
- all = itemService.findInArchiveOrWithdrawnNonDiscoverableModifiedSince(context,
DateUtils.addDays(it.getLastModified(),1));
assertThat("Returned list should not be null", all, notNullValue());
- boolean added = false;
+ boolean added = false;
while (all.hasNext()) {
Item tmp = all.next();
if (tmp.equals(it)) {
@@ -318,7 +332,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
all = itemService.findInArchiveOrWithdrawnNonDiscoverableModifiedSince(context,
DateUtils.addDays(it.getLastModified(),-1));
assertThat("Returned list should not be null", all, notNullValue());
- added = false;
+ added = false;
while (all.hasNext()) {
Item tmp = all.next();
if (tmp.equals(it)) {
@@ -333,7 +347,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
all = itemService.findInArchiveOrWithdrawnNonDiscoverableModifiedSince(context,
DateUtils.addDays(it.getLastModified(),-1));
assertThat("Returned list should not be null", all, notNullValue());
- added = false;
+ added = false;
while (all.hasNext()) {
Item tmp = all.next();
if (tmp.equals(it)) {
@@ -787,13 +801,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateBundleAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
-
- }};
+ // Allow Item ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
String name = "bundle";
Bundle created = bundleService.create(context, it, name);
@@ -808,16 +817,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = SQLException.class)
public void testCreateBundleNoName() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
-
- }};
-
- String name = "";
- Bundle created = bundleService.create(context, it, name);
+ bundleService.create(context, it, "");
fail("Exception expected");
}
@@ -825,36 +825,18 @@ public class ItemTest extends AbstractDSpaceObjectTest {
* Test of createBundle method, of class Item.
*/
@Test(expected = SQLException.class)
- public void testCreateBundleNoName2() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
-
- }};
-
- String name = null;
- Bundle created = bundleService.create(context, it, name);
+ public void testCreateBundleNullName() throws Exception {
+ bundleService.create(context, it, null);
fail("Exception expected");
}
-
/**
* Test of createBundle method, of class Item.
*/
@Test(expected = AuthorizeException.class)
public void testCreateBundleNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = new AuthorizeException();
-
- }};
-
String name = "bundle";
- Bundle created = bundleService.create(context, it, name);
+ bundleService.create(context, it, name);
fail("Exception expected");
}
@@ -863,17 +845,13 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testAddBundleAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
-
- }};
+ // Allow Item ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
String name = "bundle";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
+ itemService.addBundle(context, it, created);
assertThat("testAddBundleAuth 0", itemService.getBundles(it, name), notNullValue());
assertTrue("testAddBundleAuth 1", itemService.getBundles(it, name).size() == 1);
@@ -885,19 +863,10 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testAddBundleNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = new AuthorizeException();
-
- }};
-
String name = "bundle";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
-
- it.addBundle(created);
+ itemService.addBundle(context, it, created);
fail("Exception expected");
}
@@ -906,23 +875,18 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveBundleAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD and REMOVE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.DELETE);
- result = null;
- }};
-
+ // First create a bundle for test
+ context.turnOffAuthorisationSystem();
String name = "bundle";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
itemService.addBundle(context, it, created);
+ context.restoreAuthSystemState();
+
+ // Allow Item REMOVE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.REMOVE);
+ // Allow Bundle DELETE
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.DELETE);
itemService.removeBundle(context, it, created);
assertThat("testRemoveBundleAuth 0", itemService.getBundles(it, name), notNullValue());
@@ -934,21 +898,13 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveBundleNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- // Disallow Item REMOVE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = new AuthorizeException();
- }};
-
+ // First create a bundle for test
+ context.turnOffAuthorisationSystem();
String name = "bundle";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
- it.addBundle(created);
+ itemService.addBundle(context, it, created);
+ context.restoreAuthSystemState();
itemService.removeBundle(context, it, created);
fail("Exception expected");
@@ -959,15 +915,15 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateSingleBitstream_InputStream_StringAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Item ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
+ // Allow Item WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE, true);
+ // Allow Bundle ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(any(Context.class), any(Bundle.class), eq(Constants.ADD));
+ // Allow Bitstream WRITE perms
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
String name = "new bundle";
File f = new File(testProps.get("test.bitstream").toString());
@@ -980,17 +936,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateSingleBitstream_InputStream_StringNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = new AuthorizeException();
-
- }};
-
String name = "new bundle";
File f = new File(testProps.get("test.bitstream").toString());
- Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, name);
+ itemService.createSingleBitstream(context, new FileInputStream(f), it, name);
fail("Exception expected");
}
@@ -999,16 +947,16 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCreateSingleBitstream_InputStreamAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE, true);
- result = null;
+ // Allow Item ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.ADD);
+ // Allow Item WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE, true);
+ // Allow Bundle ADD perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(any(Context.class), any(Bundle.class), eq(Constants.ADD));
+ // Allow Bitstream WRITE perms
+ doNothing().when(authorizeServiceSpy)
+ .authorizeAction(any(Context.class), any(Bitstream.class), eq(Constants.WRITE));
- }};
File f = new File(testProps.get("test.bitstream").toString());
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it);
@@ -1020,16 +968,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testCreateSingleBitstream_InputStreamNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = new AuthorizeException();
-
- }};
-
File f = new File(testProps.get("test.bitstream").toString());
- Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it);
+ itemService.createSingleBitstream(context, new FileInputStream(f), it);
fail("Expected exception");
}
@@ -1047,23 +987,17 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveDSpaceLicenseAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD and REMOVE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.DELETE);
- result = null;
- }};
-
+ // First create a bundle for test
+ context.turnOffAuthorisationSystem();
String name = "LICENSE";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
-// it.addBundle(created);
+ context.restoreAuthSystemState();
+
+ // Allow Item REMOVE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.REMOVE);
+ // Allow Bundle DELETE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.DELETE);
itemService.removeDSpaceLicense(context, it);
assertThat("testRemoveDSpaceLicenseAuth 0", itemService.getBundles(it, name), notNullValue());
@@ -1075,20 +1009,12 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveDSpaceLicenseNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- // Disallow Item REMOVE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = new AuthorizeException();
- }};
-
+ // First create a bundle for test
+ context.turnOffAuthorisationSystem();
String name = "LICENSE";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
+ context.restoreAuthSystemState();
itemService.removeDSpaceLicense(context, it);
fail("Exception expected");
@@ -1099,23 +1025,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testRemoveLicensesAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD and REMOVE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- authorizeService.authorizeAction(context, (Bitstream) any,
- Constants.DELETE);
- result = null;
-
- }};
-
+ // First create test content
+ context.turnOffAuthorisationSystem();
String name = "LICENSE";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
@@ -1125,7 +1036,18 @@ public class ItemTest extends AbstractDSpaceObjectTest {
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, bsname);
bitstreamService.setFormat(context, result, bitstreamFormatService.findByShortDescription(context, bsname));
bundleService.addBitstream(context, created, result);
+ context.restoreAuthSystemState();
+ // Allow Item REMOVE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.REMOVE);
+ // Allow Item WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE);
+ // Allow Bundle REMOVE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.REMOVE);
+ // Allow Bundle DELETE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, created, Constants.DELETE);
+ // Allow Bitstream DELETE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, result, Constants.DELETE);
itemService.removeLicenses(context, it);
assertThat("testRemoveLicensesAuth 0", itemService.getBundles(it, name), notNullValue());
@@ -1137,17 +1059,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testRemoveLicensesNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = new AuthorizeException();
- }
- };
-
+ // First create test content
+ context.turnOffAuthorisationSystem();
String name = "LICENSE";
Bundle created = bundleService.create(context, it, name);
created.setName(context, name);
@@ -1157,6 +1070,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
Bitstream result = itemService.createSingleBitstream(context, new FileInputStream(f), it, bsname);
bitstreamService.setFormat(context, result, bitstreamFormatService.findByShortDescription(context, bsname));
bundleService.addBitstream(context, created, result);
+ context.restoreAuthSystemState();
itemService.removeLicenses(context, it);
fail("Exception expected");
@@ -1167,15 +1081,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUpdateAuth() 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, it, Constants.WRITE);
- }};
-
- //TOOD: how to test?
itemService.update(context, it);
}
@@ -1184,32 +1092,14 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testUpdateAuth2() throws Exception {
- // Test permission inheritence
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = new AuthorizeException();
- // Allow parent Community WRITE and ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Disallow parent Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
-
- }};
-
context.turnOffAuthorisationSystem();
Collection c = createCollection();
it.setOwningCollection(c);
context.restoreAuthSystemState();
- //TOOD: how to test?
+ // Allow parent Collection WRITE perms (to test inheritance)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE, false);
+
itemService.update(context, it);
}
@@ -1218,31 +1108,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testUpdateNoAuth() throws Exception {
- // Test permission inheritence
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = new AuthorizeException();
- // Disallow parent Community WRITE or ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, anyBoolean);
- result = false;
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, anyBoolean);
- result = false;
- // Disallow parent Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, anyBoolean);
- result = new AuthorizeException();
- }};
-
context.turnOffAuthorisationSystem();
Collection c = createCollection();
it.setOwningCollection(c);
context.restoreAuthSystemState();
- //TOOD: how to test?
itemService.update(context, it);
}
@@ -1251,18 +1121,10 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testWithdrawAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow Item withdraw permissions
- AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any);
- result = null;
- }};
-
- new NonStrictExpectations(authorizeService.getClass()) {{
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
-
- }};
+ // Allow Item WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE);
+ // Allow Collection ADMIN perms
+ when(authorizeServiceSpy.authorizeActionBoolean(context, collection, Constants.ADMIN)).thenReturn(true);
itemService.withdraw(context, it);
assertTrue("testWithdrawAuth 0", it.isWithdrawn());
@@ -1273,13 +1135,6 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testWithdrawNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Disallow Item withdraw permissions
- AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any);
- result = new AuthorizeException();
-
- }};
-
itemService.withdraw(context, it);
fail("Exception expected");
}
@@ -1289,21 +1144,16 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testReinstateAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any);
- result = null;
- AuthorizeUtil.authorizeReinstateItem((Context) any, (Item) any);
- result = null;
-
- }};
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item withdraw and reinstate permissions
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- }};
+ // Allow Item WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE);
+ // Allow Collection ADD perms (needed to reinstate)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, collection, Constants.ADD);
+ // initialize item as withdrawn
+ context.turnOffAuthorisationSystem();
itemService.withdraw(context, it);
+ context.restoreAuthSystemState();
+
itemService.reinstate(context, it);
assertFalse("testReinstate 0", it.isWithdrawn());
}
@@ -1313,21 +1163,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testReinstateNoAuth() throws Exception {
- new NonStrictExpectations(AuthorizeUtil.class) {{
- // Allow Item withdraw permissions
- AuthorizeUtil.authorizeWithdrawItem((Context) any, (Item) any);
- result = null;
- // Disallow Item reinstate permissions
- AuthorizeUtil.authorizeReinstateItem((Context) any, (Item) any);
- result = new AuthorizeException();
- }};
- new NonStrictExpectations(authorizeService.getClass()) {{
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- }};
-
+ // initialize item as withdrawn
+ context.turnOffAuthorisationSystem();
itemService.withdraw(context, it);
+ context.restoreAuthSystemState();
+
itemService.reinstate(context, it);
fail("Exception expected");
}
@@ -1337,21 +1177,20 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testDeleteAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item REMOVE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE, true);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.DELETE, true);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- }};
+ // create a new item to delete
+ context.turnOffAuthorisationSystem();
+ Item item = createItem();
+ context.restoreAuthSystemState();
- UUID id = it.getID();
- itemService.delete(context, it);
+ // Allow Item REMOVE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.REMOVE, true);
+ // Allow Item DELETE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.DELETE);
+ // Allow Item WRITE perms (required to first delete identifiers)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, item, Constants.WRITE);
+
+ UUID id = item.getID();
+ itemService.delete(context, item);
Item found = itemService.find(context, id);
assertThat("testDeleteAuth 0", found, nullValue());
}
@@ -1361,13 +1200,6 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test(expected = AuthorizeException.class)
public void testDeleteNoAuth() throws Exception {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item REMOVE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = new AuthorizeException();
- }};
-
itemService.delete(context, it);
fail("Exception expected");
}
@@ -1378,30 +1210,21 @@ public class ItemTest extends AbstractDSpaceObjectTest {
@Test
@SuppressWarnings("ObjectEqualsNull")
public void testEquals() throws SQLException, AuthorizeException, IOException, IllegalAccessException {
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item ADD perms (needed to create an Item)
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.ADD);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.REMOVE);
- result = null;
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.DELETE);
- result = null;
-
- }};
-
assertFalse("testEquals 0", it.equals(null));
+
+ // create a new item to test against
+ context.turnOffAuthorisationSystem();
Item item = createItem();
+ context.restoreAuthSystemState();
+
try {
assertFalse("testEquals 1", it.equals(item));
assertTrue("testEquals 2", it.equals(it));
} finally {
+ //delete item we created
+ context.turnOffAuthorisationSystem();
itemService.delete(context, item);
+ context.restoreAuthSystemState();
}
}
@@ -1435,13 +1258,6 @@ public class ItemTest extends AbstractDSpaceObjectTest {
List
newpolicies = new ArrayList();
ResourcePolicy pol1 = resourcePolicyService.create(context);
newpolicies.add(pol1);
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- }
- };
itemService.replaceAllItemPolicies(context, it, newpolicies);
List retrieved = authorizeService.getPolicies(context, it);
@@ -1544,13 +1360,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
context.restoreAuthSystemState();
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE, true);
- result = null;
- }
- };
+ // Allow Item WRITE perms
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, it, Constants.WRITE, true);
itemService.inheritCollectionDefaultPolicies(context, it, c);
@@ -1630,24 +1441,8 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanAuth() throws Exception {
- // Test Inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Allow Item WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Item) any,
- Constants.WRITE);
- result = true;
- // Allow parent Community WRITE and ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = null;
- }};
+ // Allow Item WRITE perms
+ when(authorizeServiceSpy.authorizeActionBoolean(context, it, Constants.WRITE)).thenReturn(true);
assertTrue("testCanEditBooleanAuth 0", itemService.canEdit(context, it));
}
@@ -1657,24 +1452,9 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanAuth2() throws Exception {
- // Test Inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Item) any,
- Constants.WRITE);
- result = false;
- // Allow parent Community WRITE and ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, true);
- result = true;
- // Allow parent Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
+ // Allow parent Community WRITE perms (test inheritance from community)
+ when(authorizeServiceSpy.authorizeActionBoolean(context, owningCommunity, Constants.WRITE, false))
+ .thenReturn(true);
assertTrue("testCanEditBooleanAuth2 0", itemService.canEdit(context, it));
}
@@ -1684,107 +1464,24 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanAuth3() throws Exception {
- // Test Inheritance of permissions for owning collection
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Item) any,
- Constants.WRITE);
- result = false;
- // Allow parent Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, false);
- result = null;
- }};
-
// Create a new Collection and assign it as the owner
context.turnOffAuthorisationSystem();
Collection c = createCollection();
it.setOwningCollection(c);
context.restoreAuthSystemState();
+ // Allow parent Collection WRITE perms (test inheritance from new collection)
+ doNothing().when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE, false);
+
// Ensure person with WRITE perms on the Collection can edit item
assertTrue("testCanEditBooleanAuth3 0", itemService.canEdit(context, it));
}
- /**
- * Test of canEdit method, of class Item.
- */
- @Test
- public void testCanEditBooleanAuth4() throws Exception {
- // Test Inheritance of permissions for Community Admins
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Item) any,
- Constants.WRITE);
- result = false;
- // Allow parent Community WRITE and ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, true);
- result = true;
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, false);
- result = true;
- // Disallow parent Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, true);
- result = new AuthorizeException();
- }};
-
- // Ensure person with WRITE perms on the Collection can edit item
- assertTrue("testCanEditBooleanAuth4 0", itemService.canEdit(context, it));
- }
-
- /**
- * Test of canEdit method, of class Item.
- */
- @Test
- public void testCanEditBooleanAuth5() throws Exception {
- // Test Inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = new AuthorizeException();
- // Allow Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, anyBoolean);
- result = null;
- }};
-
- collectionService.createTemplateItem(context, collection);
- collectionService.update(context, collection);
- assertTrue("testCanEditBooleanNoAuth5 0", itemService.canEdit(context, collection.getTemplateItem()));
- }
-
/**
* Test of canEdit method, of class Item.
*/
@Test
public void testCanEditBooleanNoAuth() throws Exception {
- // Test Inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeActionBoolean((Context) any, (Item) any,
- Constants.WRITE);
- result = false;
- // Disallow parent Community WRITE and ADD perms
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.WRITE, anyBoolean);
- result = false;
- authorizeService.authorizeActionBoolean((Context) any, (Community) any,
- Constants.ADD, anyBoolean);
- result = false;
- // Disallow parent Collection WRITE perms
- authorizeService.authorizeAction((Context) any, (Collection) any,
- Constants.WRITE, anyBoolean);
- result = new AuthorizeException();
- }};
-
- context.turnOffAuthorisationSystem();
- Collection c = createCollection();
- it.setOwningCollection(c);
- context.restoreAuthSystemState();
-
assertFalse("testCanEditBooleanNoAuth 0", itemService.canEdit(context, it));
}
@@ -1793,17 +1490,16 @@ public class ItemTest extends AbstractDSpaceObjectTest {
*/
@Test
public void testCanEditBooleanNoAuth2() throws Exception {
+ // Test that a new Item cannot be edited by default
context.turnOffAuthorisationSystem();
WorkspaceItem wi = workspaceItemService.create(context, collection, true);
context.restoreAuthSystemState();
- // Test Inheritance of permissions
- new NonStrictExpectations(authorizeService.getClass()) {{
- // Disallow Item WRITE perms
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE, anyBoolean);
- result = new AuthorizeException();
- }};
- assertFalse("testCanEditBooleanNoAuth2 0", itemService.canEdit(context, wi.getItem()));
+ Item item = wi.getItem();
+
+ // Disallow Item WRITE perms
+ when(authorizeServiceSpy.authorizeActionBoolean(context, item, Constants.WRITE)).thenReturn(false);
+
+ assertFalse("testCanEditBooleanNoAuth2 0", itemService.canEdit(context, item));
}
/**
@@ -1880,15 +1576,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
assertThat("testFindByMetadataField 0", result, notNullValue());
assertFalse("testFindByMetadataField 1", result.hasNext());
+ // add new metadata to item
+ context.turnOffAuthorisationSystem();
itemService.addMetadata(context, it, schema, element, qualifier, Item.ANY, value);
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- }
- };
itemService.update(context, it);
+ context.restoreAuthSystemState();
result = itemService.findByMetadataField(context, schema, element, qualifier, value);
assertThat("testFindByMetadataField 3", result, notNullValue());
@@ -1929,7 +1621,7 @@ public class ItemTest extends AbstractDSpaceObjectTest {
assertThat("testGetParentObject 1", itemService.getParentObject(context, it), notNullValue());
assertThat("testGetParentObject 2", (Collection) itemService.getParentObject(context, it), equalTo(parent));
} catch (AuthorizeException ex) {
- fail("Authorize exception catched");
+ throw new AssertionError("Authorize Exception occurred", ex);
}
}
@@ -1949,16 +1641,11 @@ public class ItemTest extends AbstractDSpaceObjectTest {
assertThat("testFindByAuthorityValue 0", result, notNullValue());
assertFalse("testFindByAuthorityValue 1", result.hasNext());
+ // add new metadata (with authority) to item
+ context.turnOffAuthorisationSystem();
itemService.addMetadata(context, it, schema, element, qualifier, Item.ANY, value, authority, confidence);
- //Ensure that the current user can update the item
- new NonStrictExpectations(authorizeService.getClass()) {
- {
- authorizeService.authorizeAction((Context) any, (Item) any,
- Constants.WRITE);
- result = null;
- }
- };
itemService.update(context, it);
+ context.restoreAuthSystemState();
result = itemService.findByAuthorityValue(context, schema, element, qualifier, authority);
assertThat("testFindByAuthorityValue 3", result, notNullValue());
diff --git a/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java b/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java
index 25ed724bb9..dbba4366f0 100644
--- a/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/LicenseUtilsTest.java
@@ -104,11 +104,11 @@ public class LicenseUtilsTest extends AbstractUnitTest {
@Test
public void testGetLicenseText_5args() throws SQLException, AuthorizeException, IOException {
//parameters for the test
- Locale locale = null;
- Collection collection = null;
- Item item = null;
- EPerson person = null;
- Map additionalInfo = null;
+ Locale locale;
+ Collection collection;
+ Item item;
+ EPerson person;
+ Map additionalInfo;
// We don't test attribute 4 as this is the date, and the date often differs between when the test
// is executed, and when the LicenceUtils code gets the current date/time which causes the test to fail
@@ -195,10 +195,10 @@ public class LicenseUtilsTest extends AbstractUnitTest {
@Test
public void testGetLicenseText_4args() throws SQLException, AuthorizeException, IOException {
//parameters for the test
- Locale locale = null;
- Collection collection = null;
- Item item = null;
- EPerson person = null;
+ Locale locale;
+ Collection collection;
+ Item item;
+ EPerson person;
String template = "Template license: %1$s %2$s %3$s %5$s %6$s";
String templateResult = "Template license: first name last name testgetlicensetext_4args@email.com ";
diff --git a/dspace-api/src/test/java/org/dspace/content/MetadataFieldTest.java b/dspace-api/src/test/java/org/dspace/content/MetadataFieldTest.java
index edd030a135..1cf7742830 100644
--- a/dspace-api/src/test/java/org/dspace/content/MetadataFieldTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/MetadataFieldTest.java
@@ -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);
diff --git a/dspace-api/src/test/java/org/dspace/content/MetadataSchemaTest.java b/dspace-api/src/test/java/org/dspace/content/MetadataSchemaTest.java
index 30a1a07325..dc7d899f06 100644
--- a/dspace-api/src/test/java/org/dspace/content/MetadataSchemaTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/MetadataSchemaTest.java
@@ -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);
diff --git a/dspace-api/src/test/java/org/dspace/content/NonUniqueMetadataExceptionTest.java b/dspace-api/src/test/java/org/dspace/content/NonUniqueMetadataExceptionTest.java
index b99e44c7f2..89d4df0c68 100644
--- a/dspace-api/src/test/java/org/dspace/content/NonUniqueMetadataExceptionTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/NonUniqueMetadataExceptionTest.java
@@ -9,8 +9,6 @@ package org.dspace.content;
import static org.junit.Assert.assertTrue;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
import org.junit.Test;
/**
@@ -21,12 +19,6 @@ import org.junit.Test;
*/
public class NonUniqueMetadataExceptionTest {
- /**
- * log4j category
- */
- private static final Logger log = LogManager
- .getLogger(NonUniqueMetadataExceptionTest.class);
-
/**
* Dummy test to avoid initialization errors
*/
diff --git a/dspace-api/src/test/java/org/dspace/content/RelationshipMetadataServiceTest.java b/dspace-api/src/test/java/org/dspace/content/RelationshipMetadataServiceTest.java
index 6290d010e0..df12cccc23 100644
--- a/dspace-api/src/test/java/org/dspace/content/RelationshipMetadataServiceTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/RelationshipMetadataServiceTest.java
@@ -463,8 +463,8 @@ public class RelationshipMetadataServiceTest extends AbstractUnitTest {
WorkspaceItem is = workspaceItemService.create(context, col, false);
Item secondItem = installItemService.installItem(context, is);
itemService.addMetadata(context, secondItem, "relationship", "type", null, null, "Publication");
- Relationship secondRelationship = relationshipService.create(context, secondItem, rightItem,
- isAuthorOfPublicationRelationshipType, 0, 0);
+ relationshipService.create(context, secondItem, rightItem,
+ isAuthorOfPublicationRelationshipType, 0, 0);
context.restoreAuthSystemState();
assertThat(relationshipService.findNextRightPlaceByRightItem(context, rightItem), equalTo(2));
@@ -489,8 +489,8 @@ public class RelationshipMetadataServiceTest extends AbstractUnitTest {
itemService.addMetadata(context, secondAuthor, "relationship", "type", null, null, "Author");
itemService.addMetadata(context, secondAuthor, "person", "familyName", null, null, "familyName");
itemService.addMetadata(context, secondAuthor, "person", "givenName", null, null, "firstName");
- Relationship secondRelationship = relationshipService.create(context, leftItem, secondAuthor,
- isAuthorOfPublicationRelationshipType, 0, 0);
+ relationshipService.create(context, leftItem, secondAuthor,
+ isAuthorOfPublicationRelationshipType, 0, 0);
context.restoreAuthSystemState();
assertThat(relationshipService.findNextLeftPlaceByLeftItem(context, leftItem), equalTo(2));
diff --git a/dspace-api/src/test/java/org/dspace/content/RelationshipServiceImplTest.java b/dspace-api/src/test/java/org/dspace/content/RelationshipServiceImplTest.java
index 244f58bc6d..73d80a77c0 100644
--- a/dspace-api/src/test/java/org/dspace/content/RelationshipServiceImplTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/RelationshipServiceImplTest.java
@@ -8,12 +8,11 @@
package org.dspace.content;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
-import java.util.LinkedList;
import java.util.List;
import org.dspace.authorize.service.AuthorizeService;
@@ -28,7 +27,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 {
@@ -137,7 +136,7 @@ public class RelationshipServiceImplTest {
@Test
public void testFindByItemAndRelationshipType() throws Exception {
// Declare objects utilized in unit test
- List relList = new LinkedList<>();
+ List relList = new ArrayList<>();
Item item = mock(Item.class);
RelationshipType testRel = new RelationshipType();
@@ -152,7 +151,7 @@ public class RelationshipServiceImplTest {
@Test
public void testFindByRelationshipType() throws Exception {
// Declare objects utilized in unit test
- List relList = new LinkedList<>();
+ List relList = new ArrayList<>();
RelationshipType testRel = new RelationshipType();
// The Relationship(s) reported should match our our relList
@@ -231,8 +230,6 @@ public class RelationshipServiceImplTest {
public void testDelete() throws Exception {
// Declare objects utilized in unit test
- MetadataValue metVal = mock(MetadataValue.class);
- List metsList = new ArrayList<>();
List leftTypelist = new ArrayList<>();
List rightTypelist = new ArrayList<>();
Item leftItem = mock(Item.class);
@@ -246,7 +243,6 @@ public class RelationshipServiceImplTest {
testRel.setRightwardType("Entitylabel");
testRel.setLeftMinCardinality(0);
testRel.setRightMinCardinality(0);
- metsList.add(metVal);
relationship = getRelationship(leftItem, rightItem, testRel, 0,0);
leftTypelist.add(relationship);
rightTypelist.add(relationship);
diff --git a/dspace-api/src/test/java/org/dspace/content/RelationshipTypeTest.java b/dspace-api/src/test/java/org/dspace/content/RelationshipTypeTest.java
index a5a4562e96..2c57bef96e 100644
--- a/dspace-api/src/test/java/org/dspace/content/RelationshipTypeTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/RelationshipTypeTest.java
@@ -10,15 +10,14 @@ package org.dspace.content;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.util.LinkedList;
+import java.util.ArrayList;
import java.util.List;
import java.util.Random;
-import org.apache.logging.log4j.Logger;
import org.dspace.content.dao.RelationshipTypeDAO;
import org.dspace.core.Context;
import org.junit.Before;
@@ -26,13 +25,10 @@ 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 {
-
- private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(RelationshipTypeTest.class);
-
@InjectMocks
private RelationshipTypeServiceImpl relationshipTypeService;
@@ -102,7 +98,7 @@ public class RelationshipTypeTest {
@Test
public void testRelationshipTypeFindAll() throws Exception {
// Declare objects utilized for this test
- List mockedList = new LinkedList<>();
+ List mockedList = new ArrayList<>();
mockedList.add(firstRelationshipType);
mockedList.add(secondRelationshipType);
@@ -120,7 +116,7 @@ public class RelationshipTypeTest {
@Test
public void testRelationshipTypeFindByLeftOrRightwardType() throws Exception {
// Declare objects utilized for this test
- List mockedList = new LinkedList<>();
+ List mockedList = new ArrayList<>();
mockedList.add(firstRelationshipType);
// Mock DAO to return our mockedList
@@ -138,7 +134,7 @@ public class RelationshipTypeTest {
@Test
public void testRelationshipTypefindByEntityType() throws Exception {
// Declare objects utilized for this test
- List mockedList = new LinkedList<>();
+ List mockedList = new ArrayList<>();
mockedList.add(firstRelationshipType);
// Mock DAO to return our mockedList
diff --git a/dspace-api/src/test/java/org/dspace/content/SiteTest.java b/dspace-api/src/test/java/org/dspace/content/SiteTest.java
index 421ce4b1bc..02e868e19b 100644
--- a/dspace-api/src/test/java/org/dspace/content/SiteTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/SiteTest.java
@@ -58,7 +58,7 @@ public class SiteTest extends AbstractUnitTest {
try {
//we have to create a new community in the database
context.turnOffAuthorisationSystem();
- this.s = (Site) siteService.findSite(context);
+ this.s = siteService.findSite(context);
//we need to commit the changes so we don't block the table for testing
context.restoreAuthSystemState();
} catch (SQLException ex) {
@@ -120,8 +120,7 @@ public class SiteTest extends AbstractUnitTest {
*/
@Test
public void testSiteFind() throws Exception {
- int id = 0;
- Site found = (Site) siteService.findSite(context);
+ Site found = siteService.findSite(context);
assertThat("testSiteFind 0", found, notNullValue());
assertThat("testSiteFind 1", found, equalTo(s));
}
@@ -141,7 +140,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")));
}
}
diff --git a/dspace-api/src/test/java/org/dspace/content/ThumbnailTest.java b/dspace-api/src/test/java/org/dspace/content/ThumbnailTest.java
index 93e231da1d..454def2d25 100644
--- a/dspace-api/src/test/java/org/dspace/content/ThumbnailTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/ThumbnailTest.java
@@ -7,6 +7,7 @@
*/
package org.dspace.content;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -48,11 +49,6 @@ public class ThumbnailTest extends AbstractUnitTest {
*/
private Bitstream orig;
- /**
- * Thumbnail instance for the tests, original copy
- */
- private Thumbnail t;
-
/**
* This method will be run before every test as per @Before. It will
* initialize resources required for the tests.
@@ -69,7 +65,9 @@ public class ThumbnailTest extends AbstractUnitTest {
File f = new File(testProps.get("test.bitstream").toString());
thumb = bitstreamService.create(context, new FileInputStream(f));
orig = bitstreamService.create(context, new FileInputStream(f));
- t = new Thumbnail(thumb, orig);
+ Thumbnail t = new Thumbnail(thumb, orig);
+ assertEquals(orig, t.getOriginal());
+ assertEquals(thumb, t.getThumb());
} catch (IOException ex) {
log.error("IO Error in init", ex);
fail("SQL Error in init: " + ex.getMessage());
@@ -89,9 +87,16 @@ public class ThumbnailTest extends AbstractUnitTest {
@After
@Override
public void destroy() {
- thumb = null;
- orig = null;
- t = null;
+ try {
+ context.turnOffAuthorisationSystem();
+ bitstreamService.delete(context, thumb);
+ bitstreamService.delete(context, orig);
+ context.restoreAuthSystemState();
+ thumb = null;
+ orig = null;
+ } catch (Exception e) {
+ throw new AssertionError("Error in destroy()", e);
+ }
super.destroy();
}
diff --git a/dspace-api/src/test/java/org/dspace/content/VersioningTest.java b/dspace-api/src/test/java/org/dspace/content/VersioningTest.java
index f66619f615..3662e43168 100644
--- a/dspace-api/src/test/java/org/dspace/content/VersioningTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/VersioningTest.java
@@ -25,7 +25,6 @@ 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.ConfigurationManager;
import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService;
import org.dspace.versioning.Version;
@@ -49,7 +48,6 @@ public class VersioningTest extends AbstractUnitTest {
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(VersioningTest.class);
- private String originalHandle;
private Item originalItem;
private Item versionedItem;
private String summary = "Unit test version";
@@ -65,7 +63,7 @@ public class VersioningTest extends AbstractUnitTest {
//A regex that can be used to see if a handle contains the format of handle created by the org.dspace.identifier
// .VersionedHandleIdentifierProvider*
- protected String versionedHandleRegex = ConfigurationManager.getProperty("handle.prefix") + "\\/[0-9]*\\.[0-9]";
+ //protected String versionedHandleRegex = ConfigurationManager.getProperty("handle.prefix") + "\\/[0-9]*\\.[0-9]";
/**
* This method will be run before every test as per @Before. It will
@@ -86,7 +84,6 @@ public class VersioningTest extends AbstractUnitTest {
WorkspaceItem is = workspaceItemService.create(context, col, false);
originalItem = installItemService.installItem(context, is);
- originalHandle = originalItem.getHandle();
Version version = versionService.createNewVersion(context, originalItem, summary);
WorkspaceItem wsi = workspaceItemService.findByItem(context, version.getItem());
diff --git a/dspace-api/src/test/java/org/dspace/content/WorkspaceItemTest.java b/dspace-api/src/test/java/org/dspace/content/WorkspaceItemTest.java
index 250ff35090..77bc170d8a 100644
--- a/dspace-api/src/test/java/org/dspace/content/WorkspaceItemTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/WorkspaceItemTest.java
@@ -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,15 +157,11 @@ 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;
+ boolean template;
+ WorkspaceItem created;
template = false;
created = workspaceItemService.create(context, collection, template);
@@ -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");
}
diff --git a/dspace-api/src/test/java/org/dspace/content/comparator/NameAscendingComparatorTest.java b/dspace-api/src/test/java/org/dspace/content/comparator/NameAscendingComparatorTest.java
index e03ce73ada..09e41e126e 100644
--- a/dspace-api/src/test/java/org/dspace/content/comparator/NameAscendingComparatorTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/comparator/NameAscendingComparatorTest.java
@@ -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 {
diff --git a/dspace-api/src/test/java/org/dspace/content/packager/ITDSpaceAIP.java b/dspace-api/src/test/java/org/dspace/content/packager/ITDSpaceAIP.java
index f13ac56eae..460522a6eb 100644
--- a/dspace-api/src/test/java/org/dspace/content/packager/ITDSpaceAIP.java
+++ b/dspace-api/src/test/java/org/dspace/content/packager/ITDSpaceAIP.java
@@ -22,9 +22,9 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
-import mockit.NonStrictExpectations;
+import com.google.common.base.Splitter;
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 +75,7 @@ import org.junit.rules.TemporaryFolder;
*
* @author Tim Donohue
*/
-public class ITDSpaceAIP extends AbstractUnitTest {
+public class ITDSpaceAIP extends AbstractIntegrationTest {
/**
* log4j category
*/
@@ -295,10 +295,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 +319,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 +368,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 +440,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 +511,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 +544,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 +582,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 +654,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 +707,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 +742,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 +804,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 +875,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 +929,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 +962,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 +1007,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 +1047,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 +1085,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)
@@ -1293,9 +1195,9 @@ public class ITDSpaceAIP extends AbstractUnitTest {
// Get the typeText & name of this object from the values
String info = infoMap.get(key);
- String[] values = info.split(valueseparator);
- String typeText = values[0];
- String name = values[1];
+ List values = Splitter.on(valueseparator).splitToList(info);
+ String typeText = values.get(0);
+ String name = values.get(1);
// Also assert type and name are correct
assertEquals("assertObjectsExist object " + key + " type",
diff --git a/dspace-api/src/test/java/org/dspace/content/virtual/CollectedTest.java b/dspace-api/src/test/java/org/dspace/content/virtual/CollectedTest.java
index 39f64cbe7d..4bf896cd08 100644
--- a/dspace-api/src/test/java/org/dspace/content/virtual/CollectedTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/virtual/CollectedTest.java
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
+import com.google.common.base.Splitter;
import org.dspace.content.Item;
import org.dspace.content.MetadataValue;
import org.dspace.content.service.ItemService;
@@ -22,7 +23,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 {
@@ -85,18 +86,15 @@ public class CollectedTest {
metadataValueList.add(metadataValue);
String s = "dc.title";
list.add(s);
- String[] splittedString = s.split("\\.");
+ List splittedString = Splitter.on('.').splitToList(s);
collected.setFields(list);
valueList.add("TestValue");
// Mock the state of objects utilized in getValues() to meet the success criteria of an invocation
- when(itemService.getMetadata(item, splittedString.length > 0 ? splittedString[0] :
- null,
- splittedString.length > 1 ? splittedString[1] :
- null,
- splittedString.length > 2 ? splittedString[2] :
- null,
- Item.ANY, false)).thenReturn(metadataValueList);
+ when(itemService.getMetadata(item, splittedString.size() > 0 ? splittedString.get(0) : null,
+ splittedString.size() > 1 ? splittedString.get(1) : null,
+ splittedString.size() > 2 ? splittedString.get(2) : null,
+ Item.ANY, false)).thenReturn(metadataValueList);
when(metadataValue.getValue()).thenReturn("TestValue");
// The reported value(s) should match our valueList
diff --git a/dspace-api/src/test/java/org/dspace/content/virtual/ConcatenateTest.java b/dspace-api/src/test/java/org/dspace/content/virtual/ConcatenateTest.java
index 2380ddbe58..52457a23d7 100644
--- a/dspace-api/src/test/java/org/dspace/content/virtual/ConcatenateTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/virtual/ConcatenateTest.java
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
+import com.google.common.base.Splitter;
import org.dspace.content.Item;
import org.dspace.content.MetadataValue;
import org.dspace.content.service.ItemService;
@@ -22,7 +23,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 {
@@ -107,18 +108,15 @@ public class ConcatenateTest {
metadataValueList.add(metadataValue);
String s = "dc.title";
list.add(s);
- String[] splittedString = s.split("\\.");
+ List splittedString = Splitter.on(".").splitToList(s);
concatenate.setFields(list);
valueList.add("TestValue");
// Mock the state of objects utilized in getValues() to meet the success criteria of an invocation
- when(itemService.getMetadata(item, splittedString.length > 0 ? splittedString[0] :
- null,
- splittedString.length > 1 ? splittedString[1] :
- null,
- splittedString.length > 2 ? splittedString[2] :
- null,
- Item.ANY, false)).thenReturn(metadataValueList);
+ when(itemService.getMetadata(item, splittedString.size() > 0 ? splittedString.get(0) : null,
+ splittedString.size() > 1 ? splittedString.get(1) : null,
+ splittedString.size() > 2 ? splittedString.get(2) : null,
+ Item.ANY, false)).thenReturn(metadataValueList);
when(metadataValue.getValue()).thenReturn("TestValue");
diff --git a/dspace-api/src/test/java/org/dspace/content/virtual/EntityTypeToFilterQueryServiceTest.java b/dspace-api/src/test/java/org/dspace/content/virtual/EntityTypeToFilterQueryServiceTest.java
index 8b856dd6c1..1222d65d8d 100644
--- a/dspace-api/src/test/java/org/dspace/content/virtual/EntityTypeToFilterQueryServiceTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/virtual/EntityTypeToFilterQueryServiceTest.java
@@ -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 {
diff --git a/dspace-api/src/test/java/org/dspace/content/virtual/RelatedTest.java b/dspace-api/src/test/java/org/dspace/content/virtual/RelatedTest.java
index d24824fbd9..cb49554d21 100644
--- a/dspace-api/src/test/java/org/dspace/content/virtual/RelatedTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/virtual/RelatedTest.java
@@ -13,7 +13,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
-import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
@@ -29,7 +28,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 {
@@ -150,8 +149,8 @@ public class RelatedTest {
assertEquals("TestGetValues 1", virtualMetadataConfiguration.getValues(context, item),
related.getValues(context, item));
related.setPlace(2);
- // No match should return empty LinkedList
- assertEquals("TestGetValues 2", new LinkedList<>(), related.getValues(context, item));
+ // No match should return empty List
+ assertEquals("TestGetValues 2", new ArrayList<>(), related.getValues(context, item));
}
diff --git a/dspace-api/src/test/java/org/dspace/content/virtual/UUIDValueTest.java b/dspace-api/src/test/java/org/dspace/content/virtual/UUIDValueTest.java
index 4312131997..29aa65cd2d 100644
--- a/dspace-api/src/test/java/org/dspace/content/virtual/UUIDValueTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/virtual/UUIDValueTest.java
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.util.LinkedList;
+import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@@ -21,14 +21,14 @@ 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 UUIDValueTest {
@InjectMocks
- private UUIDValue UUIDValue;
+ private UUIDValue uuidValue;
@Mock
private Context context;
@@ -36,32 +36,32 @@ public class UUIDValueTest {
@Test
public void testGetValues() throws Exception {
// Setup objects utilized in unit test
- List list = new LinkedList<>();
+ List list = new ArrayList<>();
Item item = mock(Item.class);
UUID uuid = UUID.randomUUID();
when(item.getID()).thenReturn(uuid);
list.add(String.valueOf(uuid));
// The reported value(s) should match our defined list
- assertEquals("TestGetValues 0", list, UUIDValue.getValues(context, item));
+ assertEquals("TestGetValues 0", list, uuidValue.getValues(context, item));
}
@Test
public void testSetUseForPlace() {
// Setup objects utilized in unit test
- UUIDValue.setUseForPlace(true);
+ uuidValue.setUseForPlace(true);
// The reported boolean should return true
- assertEquals("TestSetUseForPlace 0", true, UUIDValue.getUseForPlace());
+ assertEquals("TestSetUseForPlace 0", true, uuidValue.getUseForPlace());
}
@Test
public void testGetUseForPlace() {
// Setup objects utilized in unit test
- UUIDValue.setUseForPlace(true);
+ uuidValue.setUseForPlace(true);
// The reported boolean should return true
- assertEquals("TestGetUseForPlace 0", true, UUIDValue.getUseForPlace());
+ assertEquals("TestGetUseForPlace 0", true, uuidValue.getUseForPlace());
}
}
diff --git a/dspace-api/src/test/java/org/dspace/content/virtual/VirtualMetadataPopulatorTest.java b/dspace-api/src/test/java/org/dspace/content/virtual/VirtualMetadataPopulatorTest.java
index 207c677001..2e46e3ab98 100644
--- a/dspace-api/src/test/java/org/dspace/content/virtual/VirtualMetadataPopulatorTest.java
+++ b/dspace-api/src/test/java/org/dspace/content/virtual/VirtualMetadataPopulatorTest.java
@@ -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 {
diff --git a/dspace-api/src/test/java/org/dspace/core/ContextReadOnlyCacheTest.java b/dspace-api/src/test/java/org/dspace/core/ContextReadOnlyCacheTest.java
index b948c63212..5ebab8d90b 100644
--- a/dspace-api/src/test/java/org/dspace/core/ContextReadOnlyCacheTest.java
+++ b/dspace-api/src/test/java/org/dspace/core/ContextReadOnlyCacheTest.java
@@ -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
diff --git a/dspace-api/src/test/java/org/dspace/core/ContextTest.java b/dspace-api/src/test/java/org/dspace/core/ContextTest.java
index e2c5fe4d38..f5697a72dc 100644
--- a/dspace-api/src/test/java/org/dspace/core/ContextTest.java
+++ b/dspace-api/src/test/java/org/dspace/core/ContextTest.java
@@ -10,24 +10,31 @@ package org.dspace.core;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+import java.io.IOException;
import java.sql.SQLException;
import java.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 +45,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.
*/
@@ -53,12 +87,9 @@ public class ContextTest extends AbstractUnitTest {
* Test of setCurrentUser method, of class Context.
*/
@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;
- }};
+ public void testSetCurrentUser() throws SQLException, AuthorizeException, IOException {
+ // Allow full Admin perms
+ when(authorizeServiceSpy.isAdmin(context)).thenReturn(true);
EPerson oldUser = context.getCurrentUser();
@@ -77,6 +108,9 @@ public class ContextTest extends AbstractUnitTest {
// Restore the previous current user
context.setCurrentUser(oldUser);
+
+ // Cleanup our new user
+ ePersonService.delete(context, newUser);
}
/**
@@ -104,7 +138,6 @@ public class ContextTest extends AbstractUnitTest {
*/
@Test
public void testSetCurrentLocale() {
-
//Get previous value
Locale oldLocale = context.getCurrentLocale();
@@ -171,6 +204,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);
}
/**
@@ -225,28 +261,79 @@ public class ContextTest extends AbstractUnitTest {
cleanupContext(instance);
}
+ /**
+ * Test of commit method, of class Context.
+ */
+ @Test
+ public void testCommit() throws SQLException, AuthorizeException, IOException {
+ // To test commit() we need a new Context object
+ Context instance = new Context();
+
+ // By default, we should have a new DB connection, so let's make sure it is there
+ assertThat("HibernateDBConnection should exist", instance.getDBConnection(), notNullValue());
+ assertTrue("Context should be valid", instance.isValid());
+ assertTrue("Transaction should be open", instance.isTransactionAlive());
+
+ // Allow full Admin perms (in new context)
+ when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true);
+
+ // Create a new EPerson (to be committed)
+ String createdEmail = "myfakeemail@example.com";
+ EPerson newUser = ePersonService.create(instance);
+ newUser.setFirstName(instance, "Tim");
+ newUser.setLastName(instance, "Smith");
+ newUser.setEmail(createdEmail);
+ newUser.setCanLogIn(true);
+ newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage());
+
+ // Now, call commit()
+ instance.commit();
+
+ // We expect our DB connection to still exist
+ assertThat("HibernateDBConnection should still be open", instance.getDBConnection(), notNullValue());
+ // We expect the Context to be valid
+ assertTrue("Context should still be valid", instance.isValid());
+ // However, the transaction should now be closed
+ assertFalse("DB transaction should be closed", instance.isTransactionAlive());
+
+ // ReloadEntity and verify changes saved
+ // NOTE: reloadEntity() is required, see commit() method Javadocs
+ newUser = instance.reloadEntity(newUser);
+ assertEquals("New user should be created", newUser.getEmail(), createdEmail);
+
+ // Change the email and commit again (a Context should support multiple commit() calls)
+ String newEmail = "myrealemail@example.com";
+ newUser.setEmail(newEmail);
+ instance.commit();
+
+ // Reload entity and new value should be there.
+ newUser = instance.reloadEntity(newUser);
+ assertEquals("New email address should be saved", newUser.getEmail(), newEmail);
+
+ // Cleanup our new object & context
+ ePersonService.delete(instance, newUser);
+ cleanupContext(instance);
+ }
+
/**
* Test of abort method, of class Context.
*/
@Test
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);
- newUser.setFirstName(context, "Susan");
- newUser.setLastName(context, "Doe");
+ newUser.setFirstName(instance, "Susan");
+ newUser.setLastName(instance, "Doe");
newUser.setEmail(createdEmail);
newUser.setCanLogIn(true);
- newUser.setLanguage(context, I18nUtil.getDefaultLocale().getLanguage());
+ newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage());
// Abort our context
instance.abort();
@@ -268,25 +355,20 @@ 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);
- newUser.setFirstName(context, "Susan");
- newUser.setLastName(context, "Doe");
+ newUser.setFirstName(instance, "Susan");
+ newUser.setLastName(instance, "Doe");
newUser.setEmail(createdEmail);
newUser.setCanLogIn(true);
- newUser.setLanguage(context, I18nUtil.getDefaultLocale().getLanguage());
-
+ newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage());
}
// Open a new context, let's make sure that EPerson isn't there
@@ -410,16 +492,13 @@ public class ContextTest extends AbstractUnitTest {
* Test of getSpecialGroups method, of class Context.
*/
@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;
- }};
-
+ public void testGetSpecialGroups() throws SQLException, AuthorizeException, IOException {
// 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();
@@ -436,7 +515,8 @@ public class ContextTest extends AbstractUnitTest {
assertThat("testGetSpecialGroup 1", specialGroups.get(0), equalTo(group));
assertThat("testGetSpecialGroup 1", specialGroups.get(1), equalTo(adminGroup));
- // Cleanup our context
+ // Cleanup our context & group
+ groupService.delete(instance, group);
cleanupContext(instance);
}
diff --git a/dspace-api/src/test/java/org/dspace/core/HibernateDBConnectionTest.java b/dspace-api/src/test/java/org/dspace/core/HibernateDBConnectionTest.java
new file mode 100644
index 0000000000..093f693d56
--- /dev/null
+++ b/dspace-api/src/test/java/org/dspace/core/HibernateDBConnectionTest.java
@@ -0,0 +1,229 @@
+/**
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://www.dspace.org/license/
+ */
+package org.dspace.core;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.sql.SQLException;
+
+import org.dspace.AbstractUnitTest;
+import org.dspace.eperson.EPerson;
+import org.dspace.utils.DSpace;
+import org.hibernate.Session;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Perform some basic unit tests for HibernateDBConnection
+ *
+ * @author tdonohue
+ */
+public class HibernateDBConnectionTest extends AbstractUnitTest {
+
+ private HibernateDBConnection connection;
+
+ /**
+ * This method will be run before every test as per @Before. It will
+ * initialize resources required for the tests.
+ *
+ * Other methods can be annotated with @Before here or in subclasses
+ * but no execution order is guaranteed
+ */
+ @Before
+ @Override
+ public void init() {
+ super.init();
+ // Get a DB connection to test with
+ connection = new DSpace().getServiceManager()
+ .getServiceByName(null, HibernateDBConnection.class);
+ }
+
+ /**
+ * Test of getSession method
+ */
+ @Test
+ public void testGetSession() throws SQLException {
+ assertNotNull("DB connection should not be null", connection);
+ // Connection should begin with an active transaction
+ assertTrue("A transaction should be open by default", connection.getTransaction().isActive());
+
+ // Rollback current transaction
+ connection.getTransaction().rollback();
+
+ // Transaction should be closed
+ assertFalse("Transaction should be closed after rollback", connection.getTransaction().isActive());
+
+ //Now call getSession(), saving a reference to the session
+ Session currentSession = connection.getSession();
+
+ // New transaction should be initialized
+ assertTrue("New transaction should be open after getSession() call",
+ connection.getTransaction().isActive());
+
+ // Call getSession again. The same Session should still be returned
+ assertEquals("Multiple calls to getSession should return same Session", currentSession,
+ connection.getSession());
+ }
+
+ /**
+ * Test of isTransactionAlive method
+ */
+ @Test
+ public void testIsTransactionAlive() {
+ assertNotNull("DB connection should not be null", connection);
+ assertNotNull("Transaction should not be null", connection.getTransaction());
+ // Connection should begin with a transaction
+ assertTrue("A transaction should be open by default", connection.isTransActionAlive());
+
+ // Rollback current transaction
+ connection.getTransaction().rollback();
+
+ // Transaction should be closed
+ assertFalse("Transaction should be closed after rollback", connection.isTransActionAlive());
+ }
+
+ /**
+ * Test of isSessionAlive method
+ */
+ @Test
+ public void testIsSessionAlive() throws SQLException {
+ assertNotNull("DB connection should not be null", connection);
+ assertNotNull("Session should not be null", connection.getSession());
+ assertTrue("A Session should be alive by default", connection.isSessionAlive());
+
+ // Rollback current transaction, closing it
+ connection.getTransaction().rollback();
+
+ // Session should still be alive even after transaction closes
+ assertTrue("A Session should still be alive if transaction closes", connection.isSessionAlive());
+
+ // NOTE: Because we configure Hibernate Session objects to be bound to a thread
+ // (see 'hibernate.current_session_context_class' in hibernate.cfg.xml), a Session is ALWAYS ALIVE until
+ // the thread closes (at which point Hibernate will clean it up automatically).
+ // This means that essentially isSessionAlive() will always return true, unless the connection is severed
+ // in some unexpected way. See also "testCloseDBConnection()"
+ }
+
+ /**
+ * Test of closeDBConnection method
+ */
+ @Test
+ public void testCloseDBConnection() throws SQLException {
+ // Get a reference to the current Session
+ Session initialSession = connection.getSession();
+
+ // Close the DB connection / Session
+ // NOTE: Because of our Hibernate configuration, Hibernate automatically creates a new Session per thread.
+ // Even though we "close" the connection, Hibernate will reopen a new one immediately. So, all this actually
+ // does is create a *new* Session
+ connection.closeDBConnection();
+
+ Session newSession = connection.getSession();
+ assertNotEquals("New Session expected",initialSession, newSession);
+ }
+
+ /**
+ * Test of commit method
+ */
+ @Test
+ public void testCommit() throws SQLException {
+ // Ensure a transaction exists
+ connection.getSession();
+ assertTrue("Transaction should be active", connection.getTransaction().isActive());
+
+ connection.commit();
+ assertFalse("Commit should close transaction", connection.getTransaction().isActive());
+
+ // A second commit should be a no-op (no error thrown)
+ connection.commit();
+ }
+
+ /**
+ * Test of rollback method
+ */
+ @Test
+ public void testRollback() throws SQLException {
+ // Ensure a transaction exists
+ connection.getSession();
+ assertTrue("Transaction should be active", connection.getTransaction().isActive());
+
+ connection.rollback();
+ assertFalse("Rollback should close transaction", connection.getTransaction().isActive());
+
+ // A second rollback should be a no-op (no error thrown)
+ connection.rollback();
+ }
+
+ /**
+ * Test of reloadEntity method
+ */
+ @Test
+ public void testReloadEntityAfterRollback() throws SQLException {
+ // Get DBConnection associated with DSpace Context
+ HibernateDBConnection dbConnection = (HibernateDBConnection) context.getDBConnection();
+ EPerson person = context.getCurrentUser();
+
+ assertTrue("Current user should be cached in session", dbConnection.getSession()
+ .contains(person));
+
+ dbConnection.rollback();
+ assertFalse("Current user should be gone from cache", dbConnection.getSession()
+ .contains(person));
+
+ person = dbConnection.reloadEntity(person);
+ assertTrue("Current user should be cached back in session", dbConnection.getSession()
+ .contains(person));
+ }
+
+ /**
+ * Test of reloadEntity method
+ */
+ @Test
+ public void testReloadEntityAfterCommit() throws SQLException {
+ // Get DBConnection associated with DSpace Context
+ HibernateDBConnection dbConnection = (HibernateDBConnection) context.getDBConnection();
+ EPerson person = context.getCurrentUser();
+
+ assertTrue("Current user should be cached in session", dbConnection.getSession()
+ .contains(person));
+
+ dbConnection.commit();
+ assertFalse("Current user should be gone from cache", dbConnection.getSession()
+ .contains(person));
+
+ person = dbConnection.reloadEntity(person);
+ assertTrue("Current user should be cached back in session", dbConnection.getSession()
+ .contains(person));
+ }
+
+ /**
+ * Test of uncacheEntity method
+ */
+ @Test
+ public void testUncacheEntity() throws SQLException {
+ // Get DBConnection associated with DSpace Context
+ HibernateDBConnection dbConnection = (HibernateDBConnection) context.getDBConnection();
+ EPerson person = context.getCurrentUser();
+
+ assertTrue("Current user should be cached in session", dbConnection.getSession()
+ .contains(person));
+
+ dbConnection.uncacheEntity(person);
+ assertFalse("Current user should be gone from cache", dbConnection.getSession()
+ .contains(person));
+
+ // Test ability to reload an uncached entity
+ person = dbConnection.reloadEntity(person);
+ assertTrue("Current user should be cached back in session", dbConnection.getSession()
+ .contains(person));
+ }
+}
diff --git a/dspace-api/src/test/java/org/dspace/core/I18nUtilTest.java b/dspace-api/src/test/java/org/dspace/core/I18nUtilTest.java
index 6f9241663e..0000b2046c 100644
--- a/dspace-api/src/test/java/org/dspace/core/I18nUtilTest.java
+++ b/dspace-api/src/test/java/org/dspace/core/I18nUtilTest.java
@@ -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());
diff --git a/dspace-api/src/test/java/org/dspace/core/PathsClassLoaderTest.java b/dspace-api/src/test/java/org/dspace/core/PathsClassLoaderTest.java
index b09437e804..1b337a25ab 100644
--- a/dspace-api/src/test/java/org/dspace/core/PathsClassLoaderTest.java
+++ b/dspace-api/src/test/java/org/dspace/core/PathsClassLoaderTest.java
@@ -7,8 +7,8 @@
*/
package org.dspace.core;
-import static com.sun.org.apache.bcel.internal.Constants.ACC_PUBLIC;
-import static org.junit.Assert.assertTrue;
+import static org.apache.bcel.Const.ACC_PUBLIC;
+import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileOutputStream;
@@ -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;
@@ -136,12 +136,12 @@ public class PathsClassLoaderTest {
jarFile.getCanonicalPath()};
PathsClassLoader instance = new PathsClassLoader(parentCL, classpath);
Class result = instance.findClass(className);
- assertTrue("Should return a Class from file", result instanceof Class);
+ assertNotNull("Should return a Class from file", result);
classpath[0] = jarFile.getCanonicalPath();
instance = new PathsClassLoader(parentCL, classpath);
result = instance.findClass(jarClassName);
- assertTrue("Should return a Class from JAR", result instanceof Class);
+ assertNotNull("Should return a Class from JAR", result);
}
}
diff --git a/dspace-api/src/test/java/org/dspace/core/UtilsTest.java b/dspace-api/src/test/java/org/dspace/core/UtilsTest.java
new file mode 100644
index 0000000000..915c96e209
--- /dev/null
+++ b/dspace-api/src/test/java/org/dspace/core/UtilsTest.java
@@ -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);
+ }
+}
diff --git a/dspace-api/src/test/java/org/dspace/discovery/FullTextContentStreamsTest.java b/dspace-api/src/test/java/org/dspace/discovery/FullTextContentStreamsTest.java
index 50af4f6e6d..f2a759fa09 100644
--- a/dspace-api/src/test/java/org/dspace/discovery/FullTextContentStreamsTest.java
+++ b/dspace-api/src/test/java/org/dspace/discovery/FullTextContentStreamsTest.java
@@ -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 {
diff --git a/dspace-api/src/test/java/org/dspace/discovery/MockIndexEventConsumer.java b/dspace-api/src/test/java/org/dspace/discovery/MockIndexEventConsumer.java
deleted file mode 100644
index d6830a1c80..0000000000
--- a/dspace-api/src/test/java/org/dspace/discovery/MockIndexEventConsumer.java
+++ /dev/null
@@ -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 {
- @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
- }
-}
diff --git a/dspace-api/src/test/java/org/dspace/external/provider/impl/MockDataProvider.java b/dspace-api/src/test/java/org/dspace/external/provider/impl/MockDataProvider.java
index b8dc7b501b..e5a86f1f56 100644
--- a/dspace-api/src/test/java/org/dspace/external/provider/impl/MockDataProvider.java
+++ b/dspace-api/src/test/java/org/dspace/external/provider/impl/MockDataProvider.java
@@ -8,8 +8,8 @@
package org.dspace.external.provider.impl;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashMap;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -28,10 +28,12 @@ public class MockDataProvider implements ExternalDataProvider {
* Generic getter for the sourceIdentifier
* @return the sourceIdentifier value of this MockDataProvider
*/
+ @Override
public String getSourceIdentifier() {
return sourceIdentifier;
}
+ @Override
public Optional getExternalDataObject(String id) {
ExternalDataObject externalDataObject = mockLookupMap.get(id);
if (externalDataObject == null) {
@@ -41,8 +43,9 @@ public class MockDataProvider implements ExternalDataProvider {
}
}
+ @Override
public List searchExternalDataObjects(String query, int start, int limit) {
- List listToReturn = new LinkedList<>();
+ List listToReturn = new ArrayList<>();
for (Map.Entry entry : mockLookupMap.entrySet()) {
if (StringUtils.containsIgnoreCase(entry.getKey(), query)) {
listToReturn.add(entry.getValue());
@@ -72,7 +75,7 @@ public class MockDataProvider implements ExternalDataProvider {
public void init() throws IOException {
mockLookupMap = new HashMap<>();
- List externalDataObjectsToMake = new LinkedList<>();
+ List externalDataObjectsToMake = new ArrayList<>();
externalDataObjectsToMake.add("one");
externalDataObjectsToMake.add("two");
externalDataObjectsToMake.add("three");
@@ -83,7 +86,7 @@ public class MockDataProvider implements ExternalDataProvider {
externalDataObject.setId(id);
externalDataObject.setValue(id);
externalDataObject.setDisplayValue(id);
- List list = new LinkedList<>();
+ List list = new ArrayList<>();
list.add(new MetadataValueDTO("dc", "contributor", "author", null, "Donald, Smith"));
externalDataObject.setMetadata(list);
diff --git a/dspace-api/src/test/java/org/dspace/handle/dao/impl/HandleDAOImplTest.java b/dspace-api/src/test/java/org/dspace/handle/dao/impl/HandleDAOImplTest.java
index 1560a5d04c..938dab44b0 100644
--- a/dspace-api/src/test/java/org/dspace/handle/dao/impl/HandleDAOImplTest.java
+++ b/dspace-api/src/test/java/org/dspace/handle/dao/impl/HandleDAOImplTest.java
@@ -128,12 +128,8 @@ public class HandleDAOImplTest extends AbstractUnitTest {
owningCommunity = context.reloadEntity(owningCommunity);
ContentServiceFactory.getInstance().getCommunityService().delete(context, owningCommunity);
owningCommunity = null;
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (AuthorizeException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
+ } catch (Exception e) {
+ throw new AssertionError("Error occurred in destroy()", e);
}
item1 = null;
item2 = null;
diff --git a/dspace-api/src/test/java/org/dspace/identifier/DOIIdentifierProviderTest.java b/dspace-api/src/test/java/org/dspace/identifier/DOIIdentifierProviderTest.java
index c1c7b8ee7d..d3536c629a 100644
--- a/dspace-api/src/test/java/org/dspace/identifier/DOIIdentifierProviderTest.java
+++ b/dspace-api/src/test/java/org/dspace/identifier/DOIIdentifierProviderTest.java
@@ -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",
diff --git a/dspace-api/src/test/java/org/dspace/identifier/EZIDIdentifierProviderTest.java b/dspace-api/src/test/java/org/dspace/identifier/EZIDIdentifierProviderTest.java
index 038611fe80..12b279ee1c 100644
--- a/dspace-api/src/test/java/org/dspace/identifier/EZIDIdentifierProviderTest.java
+++ b/dspace-api/src/test/java/org/dspace/identifier/EZIDIdentifierProviderTest.java
@@ -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"));
diff --git a/dspace-api/src/test/java/org/dspace/identifier/MockDOIConnector.java b/dspace-api/src/test/java/org/dspace/identifier/MockDOIConnector.java
deleted file mode 100644
index c3a9c84895..0000000000
--- a/dspace-api/src/test/java/org/dspace/identifier/MockDOIConnector.java
+++ /dev/null
@@ -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
- implements org.dspace.identifier.doi.DOIConnector {
-
- public Map reserved;
- public Map registered;
-
- public MockDOIConnector() {
- reserved = new HashMap();
- registered = new HashMap();
- }
-
- 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);
- }
- }
-
-}
diff --git a/dspace-api/src/test/java/org/dspace/scripts/DSpaceCommandLineParameterTest.java b/dspace-api/src/test/java/org/dspace/scripts/DSpaceCommandLineParameterTest.java
index 4e407d2e2e..e9242c6a9a 100644
--- a/dspace-api/src/test/java/org/dspace/scripts/DSpaceCommandLineParameterTest.java
+++ b/dspace-api/src/test/java/org/dspace/scripts/DSpaceCommandLineParameterTest.java
@@ -11,7 +11,7 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-import java.util.LinkedList;
+import java.util.ArrayList;
import java.util.List;
import org.dspace.AbstractUnitTest;
@@ -121,7 +121,7 @@ public class DSpaceCommandLineParameterTest extends AbstractUnitTest {
String value3 = null;
DSpaceCommandLineParameter dSpaceCommandLineParameter3 = new DSpaceCommandLineParameter(key3, value3);
- List dSpaceCommandLineParameterList = new LinkedList<>();
+ List dSpaceCommandLineParameterList = new ArrayList<>();
dSpaceCommandLineParameterList.add(dSpaceCommandLineParameter);
dSpaceCommandLineParameterList.add(dSpaceCommandLineParameter1);
dSpaceCommandLineParameterList.add(dSpaceCommandLineParameter2);
diff --git a/dspace-api/src/test/java/org/dspace/service/impl/ClientInfoServiceImplTest.java b/dspace-api/src/test/java/org/dspace/service/impl/ClientInfoServiceImplTest.java
index 42c78944e1..e3bb4a1590 100644
--- a/dspace-api/src/test/java/org/dspace/service/impl/ClientInfoServiceImplTest.java
+++ b/dspace-api/src/test/java/org/dspace/service/impl/ClientInfoServiceImplTest.java
@@ -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());
}
-}
\ No newline at end of file
+}
diff --git a/dspace-api/src/test/java/org/dspace/statistics/FakeDatabaseReader.java b/dspace-api/src/test/java/org/dspace/statistics/FakeDatabaseReader.java
deleted file mode 100644
index f40a67f54c..0000000000
--- a/dspace-api/src/test/java/org/dspace/statistics/FakeDatabaseReader.java
+++ /dev/null
@@ -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 {
-
- 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 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 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 {
-
- public Builder() {}
-
- /**
- * Fake constructor.
- * @param file ignored.
- */
- @Mock
- public void $init(File file) {
- }
-
- @Mock
- public DatabaseReader build()
- throws IOException {
- return Deencapsulation.newUninitializedInstance(DatabaseReader.class);
- }
- }
-}
diff --git a/dspace-api/src/test/java/org/dspace/statistics/MockSolrLoggerServiceImpl.java b/dspace-api/src/test/java/org/dspace/statistics/MockSolrLoggerServiceImpl.java
index eef9878c18..cca05a12cc 100644
--- a/dspace-api/src/test/java/org/dspace/statistics/MockSolrLoggerServiceImpl.java
+++ b/dspace-api/src/test/java/org/dspace/statistics/MockSolrLoggerServiceImpl.java
@@ -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;
*
* NOTE: this class is overridden by one of the same name
* 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 cityNames = new ArrayList(Collections.singleton("New York"));
+ City city = new City(cityNames, 1, 1, new HashMap());
+
+ List countryNames = new ArrayList(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());
+ }
}
diff --git a/dspace-api/src/test/java/org/dspace/statistics/util/DummyHttpServletRequest.java b/dspace-api/src/test/java/org/dspace/statistics/util/DummyHttpServletRequest.java
index b255db3e04..61325c652c 100644
--- a/dspace-api/src/test/java/org/dspace/statistics/util/DummyHttpServletRequest.java
+++ b/dspace-api/src/test/java/org/dspace/statistics/util/DummyHttpServletRequest.java
@@ -11,11 +11,11 @@ package org.dspace.statistics.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.security.Principal;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
-import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -114,7 +114,7 @@ public class DummyHttpServletRequest implements HttpServletRequest {
* @param headerValue The value of the header
*/
public void addHeader(String headerName, String headerValue) {
- List values = headers.computeIfAbsent(headerName, k -> new LinkedList<>());
+ List values = headers.computeIfAbsent(headerName, k -> new ArrayList<>());
values.add(headerValue);
}
/* (non-Javadoc)
@@ -292,6 +292,7 @@ public class DummyHttpServletRequest implements HttpServletRequest {
* @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
*/
@Override
+ @Deprecated
public boolean isRequestedSessionIdFromUrl() {
// TODO Auto-generated method stub
return false;
@@ -502,6 +503,7 @@ public class DummyHttpServletRequest implements HttpServletRequest {
* @see javax.servlet.ServletRequest#getRealPath(java.lang.String)
*/
@Override
+ @Deprecated
public String getRealPath(String arg0) {
// TODO Auto-generated method stub
return null;
diff --git a/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorServiceImplTest.java b/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorServiceImplTest.java
index 6abda2b13e..039fe31f11 100644
--- a/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorServiceImplTest.java
+++ b/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorServiceImplTest.java
@@ -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 {
- @Mock
- public void $init() {
- }
-
- @Mock
- public void $clinit() {
- }
-
- @Mock
- public boolean isUseProxies() {
- return false;
- }
-
- }
-
}
diff --git a/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorTest.java b/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorTest.java
index 4797f7f1e5..63046b32b6 100644
--- a/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorTest.java
+++ b/dspace-api/src/test/java/org/dspace/statistics/util/SpiderDetectorTest.java
@@ -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 {
- @Mock
- public void $init() {
- }
-
- @Mock
- public void $clinit() {
- }
-
- @Mock
- public boolean isUseProxies() {
- return false;
- }
- }
}
diff --git a/dspace-api/src/test/java/org/dspace/util/MultiFormatDateParserTest.java b/dspace-api/src/test/java/org/dspace/util/MultiFormatDateParserTest.java
index d7157b8b05..b26f36a47f 100644
--- a/dspace-api/src/test/java/org/dspace/util/MultiFormatDateParserTest.java
+++ b/dspace-api/src/test/java/org/dspace/util/MultiFormatDateParserTest.java
@@ -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}
});
}
diff --git a/dspace-api/src/test/java/org/dspace/workflowbasic/BasicWorkflowAuthorizationIT.java b/dspace-api/src/test/java/org/dspace/workflowbasic/BasicWorkflowAuthorizationIT.java
index f79ed3aaf2..7164204d25 100644
--- a/dspace-api/src/test/java/org/dspace/workflowbasic/BasicWorkflowAuthorizationIT.java
+++ b/dspace-api/src/test/java/org/dspace/workflowbasic/BasicWorkflowAuthorizationIT.java
@@ -271,7 +271,7 @@ public class BasicWorkflowAuthorizationIT
Item item = wsi.getItem();
Bundle bundle = bundleService.create(context, item, "ORIGINAL");
File f = new File(AbstractDSpaceTest.testProps.get("test.bitstream").toString());
- Bitstream bs = bitstreamService.create(context, bundle, new FileInputStream(f));
+ bitstreamService.create(context, bundle, new FileInputStream(f));
bundleService.update(context, bundle);
itemService.update(context, item);
workspaceItemService.update(context, wsi);
@@ -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));
}
@@ -323,7 +323,7 @@ public class BasicWorkflowAuthorizationIT
Item item = wsi.getItem();
Bundle bundle = bundleService.create(context, item, "ORIGINAL");
File f = new File(AbstractDSpaceTest.testProps.get("test.bitstream").toString());
- Bitstream bs = bitstreamService.create(context, bundle, new FileInputStream(f));
+ bitstreamService.create(context, bundle, new FileInputStream(f));
bundleService.update(context, bundle);
itemService.update(context, item);
workspaceItemService.update(context, wsi);
@@ -365,7 +365,7 @@ public class BasicWorkflowAuthorizationIT
item.setSubmitter(submitter);
Bundle bundle = bundleService.create(context, item, "ORIGINAL");
File f = new File(AbstractDSpaceTest.testProps.get("test.bitstream").toString());
- Bitstream bs = bitstreamService.create(context, bundle, new FileInputStream(f));
+ bitstreamService.create(context, bundle, new FileInputStream(f));
bundleService.update(context, bundle);
itemService.update(context, item);
workspaceItemService.update(context, wsi);
diff --git a/dspace-api/src/test/java/org/dspace/xmlworkflow/RoleTest.java b/dspace-api/src/test/java/org/dspace/xmlworkflow/RoleTest.java
index 83c23e1e8d..262804f12b 100644
--- a/dspace-api/src/test/java/org/dspace/xmlworkflow/RoleTest.java
+++ b/dspace-api/src/test/java/org/dspace/xmlworkflow/RoleTest.java
@@ -31,49 +31,48 @@ public class RoleTest extends AbstractUnitTest {
@Test
public void defaultWorkflow_RoleReviewer() {
Role role = defaultWorkflow.getRoles().get("Reviewer");
- assertEquals(role.getDescription(),
- "The people responsible for this step are able to edit the metadata of incoming submissions, " +
- "and then accept or reject them.");
- assertEquals(role.getName(), "Reviewer");
- assertEquals(role.getScope(), Role.Scope.COLLECTION);
+ assertEquals("The people responsible for this step are able to edit the metadata of incoming submissions, " +
+ "and then accept or reject them.", role.getDescription());
+ assertEquals("Reviewer", role.getName());
+ assertEquals(Role.Scope.COLLECTION, role.getScope());
}
@Test
public void defaultWorkflow_RoleEditor() {
Role role = defaultWorkflow.getRoles().get("Editor");
- assertEquals(role.getDescription(), "The people responsible for this step are able to edit the " +
- "metadata of incoming submissions, and then accept or reject them.");
- assertEquals(role.getName(), "Editor");
- assertEquals(role.getScope(), Role.Scope.COLLECTION);
+ assertEquals("The people responsible for this step are able to edit the " +
+ "metadata of incoming submissions, and then accept or reject them.", role.getDescription());
+ assertEquals("Editor", role.getName());
+ assertEquals(Role.Scope.COLLECTION, role.getScope());
}
@Test
public void defaultWorkflow_RoleFinalEditor() {
Role role = defaultWorkflow.getRoles().get("Final Editor");
- assertEquals(role.getDescription(), "The people responsible for this step are able to edit the " +
- "metadata of incoming submissions, but will not be able to reject them.");
- assertEquals(role.getName(), "Final Editor");
- assertEquals(role.getScope(), Role.Scope.COLLECTION);
+ assertEquals("The people responsible for this step are able to edit the " +
+ "metadata of incoming submissions, but will not be able to reject them.", role.getDescription());
+ assertEquals("Final Editor", role.getName());
+ assertEquals(Role.Scope.COLLECTION, role.getScope());
}
@Test
public void selectSingleReviewer_RoleReviewManagers() {
Role role = selectSingleReviewer.getRoles().get("ReviewManagers");
- assertEquals(role.getName(), "ReviewManagers");
- assertEquals(role.getScope(), Role.Scope.REPOSITORY);
+ assertEquals("ReviewManagers", role.getName());
+ assertEquals(Role.Scope.REPOSITORY, role.getScope());
}
@Test
public void selectSingleReviewer_RoleReviewer() {
Role role = selectSingleReviewer.getRoles().get("Reviewer");
- assertEquals(role.getName(), "Reviewer");
- assertEquals(role.getScope(), Role.Scope.ITEM);
+ assertEquals("Reviewer", role.getName());
+ assertEquals(Role.Scope.ITEM, role.getScope());
}
@Test
public void scoreReview_RoleScoreReviewers() {
Role role = scoreReview.getRoles().get("ScoreReviewers");
- assertEquals(role.getName(), "ScoreReviewers");
- assertEquals(role.getScope(), Role.Scope.COLLECTION);
+ assertEquals("ScoreReviewers", role.getName());
+ assertEquals(Role.Scope.COLLECTION, role.getScope());
}
}
diff --git a/dspace-api/src/test/java/org/dspace/xmlworkflow/XmlWorkflowFactoryTest.java b/dspace-api/src/test/java/org/dspace/xmlworkflow/XmlWorkflowFactoryTest.java
index ddcf764d5b..676285a2b2 100644
--- a/dspace-api/src/test/java/org/dspace/xmlworkflow/XmlWorkflowFactoryTest.java
+++ b/dspace-api/src/test/java/org/dspace/xmlworkflow/XmlWorkflowFactoryTest.java
@@ -25,6 +25,7 @@ import org.dspace.utils.DSpace;
import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
import org.dspace.xmlworkflow.state.Workflow;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -42,6 +43,8 @@ public class XmlWorkflowFactoryTest extends AbstractUnitTest {
= new DSpace().getServiceManager().getServiceByName("xmlWorkflowFactory",
XmlWorkflowFactoryImpl.class);
private Community owningCommunity;
+ private Collection mappedCollection;
+ private Collection nonMappedCollection;
/**
* log4j category
@@ -63,6 +66,9 @@ public class XmlWorkflowFactoryTest extends AbstractUnitTest {
//we have to create a new community in the database
context.turnOffAuthorisationSystem();
this.owningCommunity = communityService.create(null, context);
+ this.mappedCollection =
+ this.collectionService.create(context, owningCommunity, "123456789/workflow-test-1");
+ this.nonMappedCollection = this.collectionService.create(context, owningCommunity, "123456789/999");
//we need to commit the changes so we don't block the table for testing
context.restoreAuthSystemState();
} catch (SQLException e) {
@@ -74,38 +80,46 @@ public class XmlWorkflowFactoryTest extends AbstractUnitTest {
}
}
+ /**
+ * This method will be run after every test as per @After. It will
+ * clean resources initialized by the @Before methods.
+ *
+ * Other methods can be annotated with @After here or in subclasses
+ * but no execution order is guaranteed
+ */
+ @After
+ @Override
+ public void destroy() {
+ context.turnOffAuthorisationSystem();
+
+ try {
+ this.collectionService.delete(context, this.nonMappedCollection);
+ this.collectionService.delete(context, this.mappedCollection);
+ this.communityService.delete(context, this.owningCommunity);
+ } catch (Exception e) {
+ log.error("Error in destroy", e);
+ }
+
+ context.restoreAuthSystemState();
+ this.owningCommunity = null;
+ this.nonMappedCollection = null;
+ this.mappedCollection = null;
+ try {
+ super.destroy();
+ } catch (Exception e) {
+ log.error("Error in destroy", e);
+ }
+ }
+
@Test
public void workflowMapping_NonMappedCollection() throws WorkflowConfigurationException {
- Collection collection = this.findOrCreateCollectionWithHandle("123456789/6");
- Workflow workflow = xmlWorkflowFactory.getWorkflow(collection);
+ Workflow workflow = xmlWorkflowFactory.getWorkflow(this.nonMappedCollection);
assertEquals(workflow.getID(), "defaultWorkflow");
}
@Test
public void workflowMapping_MappedCollection() throws WorkflowConfigurationException {
- Collection collection = this.findOrCreateCollectionWithHandle("123456789/1000000");
- Workflow workflow = xmlWorkflowFactory.getWorkflow(collection);
+ Workflow workflow = xmlWorkflowFactory.getWorkflow(this.mappedCollection);
assertEquals(workflow.getID(), "selectSingleReviewer");
}
-
- private Collection findOrCreateCollectionWithHandle(String handle) {
- try {
- context.turnOffAuthorisationSystem();
- for (Collection collection : this.collectionService.findAll(context)) {
- if (collection.getHandle().equalsIgnoreCase(handle)) {
- return collection;
- }
- }
- Collection collection = this.collectionService.create(context, owningCommunity, handle);
- context.restoreAuthSystemState();
- return collection;
- } catch (SQLException e) {
- log.error("SQL Error in findOrCreateCollectionWithHandle", e);
- fail("SQL Error in findOrCreateCollectionWithHandle: " + e.getMessage());
- } catch (AuthorizeException e) {
- log.error("Authorization Error in findOrCreateCollectionWithHandle", e);
- fail("Authorization Error in findOrCreateCollectionWithHandle: " + e.getMessage());
- }
- return null;
- }
}
diff --git a/dspace-api/src/test/java/org/dspace/xmlworkflow/state/StepTest.java b/dspace-api/src/test/java/org/dspace/xmlworkflow/state/StepTest.java
index b14210b432..def0239e68 100644
--- a/dspace-api/src/test/java/org/dspace/xmlworkflow/state/StepTest.java
+++ b/dspace-api/src/test/java/org/dspace/xmlworkflow/state/StepTest.java
@@ -7,8 +7,9 @@
*/
package org.dspace.xmlworkflow.state;
-import static junit.framework.TestCase.assertEquals;
-import static junit.framework.TestCase.assertNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.List;
@@ -35,70 +36,70 @@ public class StepTest extends AbstractUnitTest {
@Test
public void defaultWorkflow_ReviewStep() throws WorkflowConfigurationException {
Step step = defaultWorkflow.getStep("reviewstep");
- assertEquals(step.getUserSelectionMethod().getId(), "claimaction");
- assertEquals(step.getRole().getName(), "Reviewer");
+ assertEquals("claimaction", step.getUserSelectionMethod().getId());
+ assertEquals("Reviewer", step.getRole().getName());
List actions = step.getActions();
- assert (this.containsActionNamed(actions, "reviewaction"));
- assertEquals(step.getNextStep(0).getId(), "editstep");
+ assertTrue(this.containsActionNamed(actions, "reviewaction"));
+ assertEquals("editstep", step.getNextStep(0).getId());
}
@Test
public void defaultWorkflow_EditStep() throws WorkflowConfigurationException {
Step step = defaultWorkflow.getStep("editstep");
- assertEquals(step.getUserSelectionMethod().getId(), "claimaction");
- assertEquals(step.getRole().getName(), "Editor");
+ assertEquals("claimaction", step.getUserSelectionMethod().getId());
+ assertEquals("Editor", step.getRole().getName());
List actions = step.getActions();
- assert (this.containsActionNamed(actions, "editaction"));
- assertEquals(step.getNextStep(0).getId(), "finaleditstep");
+ assertTrue(this.containsActionNamed(actions, "editaction"));
+ assertEquals("finaleditstep", step.getNextStep(0).getId());
}
@Test
public void defaultWorkflow_FinalEditStep() throws WorkflowConfigurationException {
Step step = defaultWorkflow.getStep("finaleditstep");
- assertEquals(step.getUserSelectionMethod().getId(), "claimaction");
- assertEquals(step.getRole().getName(), "Final Editor");
+ assertEquals("claimaction", step.getUserSelectionMethod().getId());
+ assertEquals("Final Editor", step.getRole().getName());
List actions = step.getActions();
- assert (this.containsActionNamed(actions, "finaleditaction"));
+ assertTrue(this.containsActionNamed(actions, "finaleditaction"));
assertNull(step.getNextStep(0));
}
@Test
public void selectSingleReviewer_SelectReviewerStep() throws WorkflowConfigurationException {
Step step = selectSingleReviewer.getStep("selectReviewerStep");
- assertEquals(step.getUserSelectionMethod().getId(), "claimaction");
- assertEquals(step.getRole().getName(), "ReviewManagers");
+ assertEquals("claimaction", step.getUserSelectionMethod().getId());
+ assertEquals("ReviewManagers", step.getRole().getName());
List actions = step.getActions();
- assert (this.containsActionNamed(actions, "selectrevieweraction"));
- assertEquals(step.getNextStep(0).getId(), "singleUserReviewStep");
+ assertTrue(this.containsActionNamed(actions, "selectrevieweraction"));
+ assertEquals("singleUserReviewStep", step.getNextStep(0).getId());
}
@Test
public void selectSingleReviewer_SingleUserReviewStep() throws WorkflowConfigurationException {
Step step = selectSingleReviewer.getStep("singleUserReviewStep");
- assertEquals(step.getUserSelectionMethod().getId(), "autoassignAction");
- assert (step.getRole().getName().equals("Reviewer"));
+ assertEquals("autoassignAction", step.getUserSelectionMethod().getId());
+ assertEquals("Reviewer", step.getRole().getName());
List actions = step.getActions();
- assert (this.containsActionNamed(actions, "singleuserreviewaction"));
- assertEquals(step.getNextStep(1).getId(), "selectReviewerStep");
+ assertTrue(this.containsActionNamed(actions, "singleuserreviewaction"));
+ assertEquals("selectReviewerStep", step.getNextStep(1).getId());
}
@Test
public void scoreReview_ScoreReviewStep() throws WorkflowConfigurationException {
Step step = scoreReview.getStep("scoreReviewStep");
- assertEquals(step.getUserSelectionMethod().getId(), "claimaction");
- assertEquals(step.getRole().getName(), "ScoreReviewers");
+ assertEquals("claimaction", step.getUserSelectionMethod().getId());
+ assertEquals("ScoreReviewers", step.getRole().getName());
List actions = step.getActions();
- assert (this.containsActionNamed(actions, "scorereviewaction"));
- assertEquals(step.getNextStep(0).getId(), "evaluationStep");
- assertEquals(step.getRequiredUsers(), 2);
+ assertTrue(this.containsActionNamed(actions, "scorereviewaction"));
+ assertEquals("evaluationStep", step.getNextStep(0).getId());
+ assertEquals(2, step.getRequiredUsers());
}
@Test
public void scoreReview_EvaluationStep() throws WorkflowConfigurationException {
Step step = scoreReview.getStep("evaluationStep");
- assertEquals(step.getUserSelectionMethod().getId(), "noUserSelectionAction");
+ assertEquals("noUserSelectionAction", step.getUserSelectionMethod().getId());
List actions = step.getActions();
- assert (this.containsActionNamed(actions, "evaluationaction"));
+ assertTrue(this.containsActionNamed(actions, "evaluationaction"));
assertNull(step.getNextStep(0));
}
diff --git a/dspace-api/src/test/java/org/dspace/xmlworkflow/state/WorkflowTest.java b/dspace-api/src/test/java/org/dspace/xmlworkflow/state/WorkflowTest.java
index dc988696f4..85182a6440 100644
--- a/dspace-api/src/test/java/org/dspace/xmlworkflow/state/WorkflowTest.java
+++ b/dspace-api/src/test/java/org/dspace/xmlworkflow/state/WorkflowTest.java
@@ -7,7 +7,8 @@
*/
package org.dspace.xmlworkflow.state;
-import static junit.framework.TestCase.assertEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.util.List;
@@ -31,30 +32,30 @@ public class WorkflowTest extends AbstractUnitTest {
@Test
public void defaultWorkflow() {
- assertEquals(defaultWorkflow.getFirstStep().getId(), "reviewstep");
+ assertEquals("reviewstep", defaultWorkflow.getFirstStep().getId());
List steps = defaultWorkflow.getSteps();
- assertEquals(steps.size(), 3);
- assert (this.containsStepNamed(steps, "reviewstep"));
- assert (this.containsStepNamed(steps, "editstep"));
- assert (this.containsStepNamed(steps, "finaleditstep"));
+ assertEquals(3, steps.size());
+ assertTrue(this.containsStepNamed(steps, "reviewstep"));
+ assertTrue(this.containsStepNamed(steps, "editstep"));
+ assertTrue(this.containsStepNamed(steps, "finaleditstep"));
}
@Test
public void selectSingleReviewer() {
- assertEquals(selectSingleReviewer.getFirstStep().getId(), "selectReviewerStep");
+ assertEquals("selectReviewerStep", selectSingleReviewer.getFirstStep().getId());
List steps = selectSingleReviewer.getSteps();
- assertEquals(steps.size(), 2);
- assert (this.containsStepNamed(steps, "selectReviewerStep"));
- assert (this.containsStepNamed(steps, "singleUserReviewStep"));
+ assertEquals(2, steps.size());
+ assertTrue(this.containsStepNamed(steps, "selectReviewerStep"));
+ assertTrue(this.containsStepNamed(steps, "singleUserReviewStep"));
}
@Test
public void scoreReview() {
- assertEquals(scoreReview.getFirstStep().getId(), "scoreReviewStep");
+ assertEquals("scoreReviewStep", scoreReview.getFirstStep().getId());
List steps = scoreReview.getSteps();
- assertEquals(steps.size(), 2);
- assert (this.containsStepNamed(steps, "scoreReviewStep"));
- assert (this.containsStepNamed(steps, "evaluationStep"));
+ assertEquals(2, steps.size());
+ assertTrue(this.containsStepNamed(steps, "scoreReviewStep"));
+ assertTrue(this.containsStepNamed(steps, "evaluationStep"));
}
private boolean containsStepNamed(List steps, String stepName) {
diff --git a/dspace-api/src/test/resources/test-config.properties b/dspace-api/src/test/resources/test-config.properties
index 273d93c968..49aaa9bb10 100644
--- a/dspace-api/src/test/resources/test-config.properties
+++ b/dspace-api/src/test/resources/test-config.properties
@@ -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
diff --git a/dspace-oai/pom.xml b/dspace-oai/pom.xml
index 183bf62fd7..4caec1c3b2 100644
--- a/dspace-oai/pom.xml
+++ b/dspace-oai/pom.xml
@@ -15,7 +15,7 @@
${basedir}/..
- 3.2.11
+ 3.3.0
5.87.0.RELEASE
@@ -89,7 +89,7 @@
org.apache.commons
commons-lang3
-
+
log4j
log4j
@@ -103,6 +103,11 @@
org.codehaus.woodstox
wstx-asl
+
+
+ org.dom4j
+ dom4j
+
diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/config/DSpaceConfigurationService.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/config/DSpaceConfigurationService.java
index f010808531..bb4cb6dc58 100644
--- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/config/DSpaceConfigurationService.java
+++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/config/DSpaceConfigurationService.java
@@ -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);
}
}
diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/solr/DSpaceSolrServerResolver.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/solr/DSpaceSolrServerResolver.java
index 6cdd59bd75..c544ec1659 100644
--- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/solr/DSpaceSolrServerResolver.java
+++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/solr/DSpaceSolrServerResolver.java
@@ -26,11 +26,12 @@ public class DSpaceSolrServerResolver implements SolrServerResolver {
@Override
public SolrClient getServer() throws SolrServerException {
if (server == null) {
+ String serverUrl = configurationService.getProperty("oai.solr.url");
try {
- server = new HttpSolrClient.Builder(configurationService.getProperty("oai", "solr.url")).build();
- log.debug("Solr Server Initialized");
+ server = new HttpSolrClient.Builder(serverUrl).build();
+ log.debug("OAI Solr Server Initialized");
} catch (Exception e) {
- log.error(e.getMessage(), e);
+ log.error("Could not initialize OAI Solr Server at " + serverUrl , e);
}
}
return server;
diff --git a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java
index fe7fbdbfd0..2a000f43ea 100644
--- a/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java
+++ b/dspace-oai/src/main/java/org/dspace/xoai/services/impl/xoai/DSpaceRepositoryConfiguration.java
@@ -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 getDescription() {
List result = new ArrayList();
- String descriptionFile = configurationService.getProperty("oai", "description.file");
+ String descriptionFile = configurationService.getProperty("oai.description.file");
if (descriptionFile == null) {
// Try indexed
boolean stop = false;
List descriptionFiles = new ArrayList();
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);
diff --git a/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java b/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java
index 3c92ea667e..99c071c6b9 100644
--- a/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java
+++ b/dspace-oai/src/main/java/org/dspace/xoai/solr/DSpaceSolrServer.java
@@ -30,12 +30,12 @@ public class DSpaceSolrServer {
public static SolrClient getServer() throws SolrServerException {
if (_server == null) {
+ String serverUrl = ConfigurationManager.getProperty("oai.solr.url");
try {
- _server = new HttpSolrClient.Builder(
- ConfigurationManager.getProperty("oai", "solr.url")).build();
- log.debug("Solr Server Initialized");
+ _server = new HttpSolrClient.Builder(serverUrl).build();
+ log.debug("OAI Solr Server Initialized");
} catch (Exception e) {
- log.error(e.getMessage(), e);
+ log.error("Could not initialize OAI Solr Server at " + serverUrl , e);
}
}
return _server;
diff --git a/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java b/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java
index 5169b5523f..c2369bce23 100644
--- a/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java
+++ b/dspace-oai/src/main/java/org/dspace/xoai/util/ItemUtils.java
@@ -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);
diff --git a/dspace-rdf/src/main/java/org/dspace/rdf/providing/DataProviderServlet.java b/dspace-rdf/src/main/java/org/dspace/rdf/providing/DataProviderServlet.java
index 526f138a71..007f865fb7 100644
--- a/dspace-rdf/src/main/java/org/dspace/rdf/providing/DataProviderServlet.java
+++ b/dspace-rdf/src/main/java/org/dspace/rdf/providing/DataProviderServlet.java
@@ -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;
}
diff --git a/dspace-rest/README.md b/dspace-rest/README.md
index 353b249931..07d71d66ed 100644
--- a/dspace-rest/README.md
+++ b/dspace-rest/README.md
@@ -1,7 +1,9 @@
-#DSpace REST API (Jersey)
+#DSpace REST API (Jersey) - DEPRECATED
A RESTful web services API for DSpace, built using JAX-RS1 JERSEY.
+_This REST API has been deprecated and will be removed in v8. Please use the Server API (/server) webapp instead._
+
##Getting Started
This REST API is integrated directly into the DSpace codebase.
diff --git a/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java b/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java
index c09e924536..26b1150229 100644
--- a/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java
+++ b/dspace-rest/src/main/java/org/dspace/rest/RestIndex.java
@@ -59,7 +59,9 @@ public class RestIndex {
// TODO Better graphics, add arguments to all methods. (limit, offset, item and so on)
return "DSpace REST - index " +
""
- + "DSpace REST API " +
+ + "DSpace REST API (Deprecated) " +
+ "This REST API is deprecated and will be removed in v8." +
+ " Please use the new Server API webapp instead. " +
"Server path: " + servletContext.getContextPath() +
"Index " +
"" +
diff --git a/dspace-rest/src/main/webapp/WEB-INF/web.xml b/dspace-rest/src/main/webapp/WEB-INF/web.xml
index 1b33aac885..34d74d9630 100644
--- a/dspace-rest/src/main/webapp/WEB-INF/web.xml
+++ b/dspace-rest/src/main/webapp/WEB-INF/web.xml
@@ -35,7 +35,7 @@
- DSpace REST API
+ DSpace REST API (Deprecated)
org.glassfish.jersey.servlet.ServletContainer
@@ -47,7 +47,7 @@
- DSpace REST API
+ DSpace REST API (Deprecated)
/*
@@ -59,7 +59,7 @@
- DSpace REST API
+ DSpace REST API (Deprecated)
/*
diff --git a/dspace-server-webapp/pom.xml b/dspace-server-webapp/pom.xml
index 49d32e25d8..c85ee73d90 100644
--- a/dspace-server-webapp/pom.xml
+++ b/dspace-server-webapp/pom.xml
@@ -51,7 +51,6 @@
install of DSpace, against which Tests can be run. -->
maven-dependency-plugin
- 2.8
${project.build.directory}/testing
@@ -95,7 +94,6 @@
org.codehaus.gmaven
groovy-maven-plugin
- 2.0
setproperty
@@ -350,11 +348,6 @@
json-path-assert
test
-
- org.jmockit
- jmockit
- test
-
junit
junit
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamRestController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamRestController.java
index ba2c66c734..7149996d4d 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamRestController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/BitstreamRestController.java
@@ -27,7 +27,6 @@ import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.model.BitstreamRest;
import org.dspace.app.rest.model.hateoas.BitstreamResource;
-import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.MultipartFileSender;
import org.dspace.app.rest.utils.Utils;
@@ -243,7 +242,7 @@ public class BitstreamRestController {
context.commit();
- BitstreamRest bitstreamRest = converter.toRest(context.reloadEntity(bitstream), Projection.DEFAULT);
+ BitstreamRest bitstreamRest = converter.toRest(context.reloadEntity(bitstream), utils.obtainProjection());
return converter.toResource(bitstreamRest);
}
}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionItemtemplateController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionItemtemplateController.java
index eef1d3eec0..8b87df6b06 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionItemtemplateController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionItemtemplateController.java
@@ -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 {
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionLogoController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionLogoController.java
index 76dec0555e..c0b78cdec0 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionLogoController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/CollectionLogoController.java
@@ -65,7 +65,7 @@ public class CollectionLogoController {
/**
* This method will add a logo to the collection.
*
- * curl -X POST http:///api/core/collections/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
+ * curl -X POST http:///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:
*
* {@code
- * curl -X POST http:///api/core/collections/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
+ * curl -X POST http:///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"
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/CommunityLogoController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/CommunityLogoController.java
index 4b11320f97..78b59730c8 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/CommunityLogoController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/CommunityLogoController.java
@@ -66,7 +66,7 @@ public class CommunityLogoController {
/**
* This method will add a logo to the community.
*
- * curl -X POST http:///api/core/communities/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
+ * curl -X POST http:///api/core/communities/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
* -XPOST -H 'Content-Type: multipart/form-data' \
* -H 'Authorization: Bearer eyJhbGciOiJI...' \
* -F "file=@Downloads/test.png"
@@ -74,7 +74,7 @@ public class CommunityLogoController {
* Example:
*
* {@code
- * curl -X POST http:///api/core/communities/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
+ * curl -X POST http:///api/core/communities/1c11f3f1-ba1f-4f36-908a-3f1ea9a557eb/logo' \
* -XPOST -H 'Content-Type: multipart/form-data' \
* -H 'Authorization: Bearer eyJhbGciOiJI...' \
* -F "file=@Downloads/test.png"
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ExternalSourcesRestController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ExternalSourcesRestController.java
index 0295aae877..db016218a9 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ExternalSourcesRestController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ExternalSourcesRestController.java
@@ -44,7 +44,7 @@ public class ExternalSourcesRestController {
* This method will retrieve all the ExternalSourceEntries for the ExternalSource for the given externalSourceName
* param
*
- * curl -X GET http:///api/integration/externalsources/orcidV2/entries
+ * curl -X GET http:///api/integration/externalsources/orcidV2/entries
*
* @param externalSourceName The externalSourceName that defines which ExternalDataProvider is used
* @param query The query used in the lookup
@@ -74,7 +74,7 @@ public class ExternalSourcesRestController {
* This method will retrieve one ExternalSourceEntryResource based on the ExternalSource for the given
* externalSourceName and with the given entryId
*
- * curl -X GET http:///api/integration/externalsources/orcidV2/entries/0000-0000-0000-0000
+ * curl -X GET http:///api/integration/externalsources/orcidV2/entries/0000-0000-0000-0000
*
* @param externalSourceName The externalSourceName that defines which ExternalDataProvider is used
* @param entryId The entryId used for the lookup
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemAddBundleController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemAddBundleController.java
index 0532ff2d29..12e8e057f9 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemAddBundleController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemAddBundleController.java
@@ -22,7 +22,6 @@ import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.model.BundleRest;
import org.dspace.app.rest.model.ItemRest;
import org.dspace.app.rest.model.hateoas.BundleResource;
-import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.repository.ItemRestRepository;
import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
@@ -108,7 +107,7 @@ public class ItemAddBundleController {
}
Bundle bundle = itemRestRepository.addBundleToItem(context, item, bundleRest);
- BundleResource bundleResource = converter.toResource(converter.toRest(bundle, Projection.DEFAULT));
+ BundleResource bundleResource = converter.toResource(converter.toRest(bundle, utils.obtainProjection()));
return ControllerUtils.toResponseEntity(HttpStatus.CREATED, new HttpHeaders(), bundleResource);
}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemOwningCollectionUpdateRestController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemOwningCollectionUpdateRestController.java
index 67aca95c10..b06360ee1d 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemOwningCollectionUpdateRestController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemOwningCollectionUpdateRestController.java
@@ -21,7 +21,6 @@ import org.dspace.app.rest.converter.ConverterService;
import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.exception.UnprocessableEntityException;
import org.dspace.app.rest.model.CollectionRest;
-import org.dspace.app.rest.projection.Projection;
import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
import org.dspace.authorize.AuthorizeException;
@@ -97,7 +96,7 @@ public class ItemOwningCollectionUpdateRestController {
if (targetCollection == null) {
return null;
}
- return converter.toRest(targetCollection, Projection.DEFAULT);
+ return converter.toRest(targetCollection, utils.obtainProjection());
}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemtemplateRestController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemtemplateRestController.java
index 0bece5ea88..fb77967b15 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemtemplateRestController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/ItemtemplateRestController.java
@@ -12,16 +12,17 @@ import static org.dspace.app.rest.utils.RegexUtils.REGEX_REQUESTMAPPING_IDENTIFI
import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;
-
import javax.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.databind.JsonNode;
+import org.dspace.app.rest.converter.ConverterService;
+import org.dspace.app.rest.exception.DSpaceBadRequestException;
import org.dspace.app.rest.exception.UnprocessableEntityException;
-import org.dspace.app.rest.model.ItemRest;
-import org.dspace.app.rest.model.hateoas.ItemResource;
-import org.dspace.app.rest.projection.Projection;
-import org.dspace.app.rest.repository.ItemRestRepository;
+import org.dspace.app.rest.model.TemplateItemRest;
+import org.dspace.app.rest.model.hateoas.TemplateItemResource;
+import org.dspace.app.rest.model.wrapper.TemplateItem;
import org.dspace.app.rest.repository.ItemTemplateItemOfLinkRepository;
+import org.dspace.app.rest.repository.TemplateItemRestRepository;
import org.dspace.app.rest.utils.ContextUtil;
import org.dspace.app.rest.utils.Utils;
import org.dspace.authorize.AuthorizeException;
@@ -57,7 +58,10 @@ public class ItemtemplateRestController {
private ItemService itemService;
@Autowired
- private ItemRestRepository itemRestRepository;
+ private TemplateItemRestRepository templateItemRestRepository;
+
+ @Autowired
+ private ConverterService converter;
@Autowired
private ItemTemplateItemOfLinkRepository itemTemplateItemOfLinkRepository;
@@ -75,24 +79,20 @@ public class ItemtemplateRestController {
*
* @param request
* @param uuid A UUID of a template item
- * @return The template item corresponding to the UUID above
+ * @return The template item corresponding to the UUID above
*/
@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) {
Context context = ContextUtil.obtainContext(request);
- ItemRest templateItem = itemRestRepository.findOne(context, uuid);
+ TemplateItemRest templateItem = templateItemRestRepository.findOne(context, uuid);
if (templateItem == null) {
throw new ResourceNotFoundException("Item with id: " + uuid + " not found");
}
- if (itemTemplateItemOfLinkRepository.getTemplateItemOf(request, uuid, null, Projection.DEFAULT) == null) {
- throw new ResourceNotFoundException("The item with id " + uuid + " is not a template item");
- }
-
- return new ItemResource(templateItem, utils);
+ return converter.toResource(templateItem);
}
/**
@@ -116,23 +116,23 @@ public class ItemtemplateRestController {
* @param request
* @param uuid The UUID of the template item to be modified
* @param jsonNode The data as shown above
- * @return The modified item
+ * @return The modified item
* @throws SQLException
* @throws AuthorizeException
*/
@PreAuthorize("hasPermission(#uuid, 'ITEM', 'WRITE')")
@RequestMapping(method = RequestMethod.PATCH)
- public ResponseEntity replaceTemplateItem(HttpServletRequest request, @PathVariable UUID uuid,
- @RequestBody(required = true) JsonNode jsonNode)
+ public ResponseEntity patch(HttpServletRequest request, @PathVariable UUID uuid,
+ @RequestBody(required = true) JsonNode jsonNode)
throws SQLException, AuthorizeException {
Context context = ContextUtil.obtainContext(request);
- Item item = getTemplateItem(context, uuid);
- ItemRest templateItem = itemRestRepository.patchTemplateItem(item, jsonNode);
+ TemplateItem templateItem = getTemplateItem(context, uuid);
+ TemplateItemRest templateItemRest = templateItemRestRepository.patchTemplateItem(templateItem, jsonNode);
context.commit();
return ControllerUtils.toResponseEntity(HttpStatus.OK, new HttpHeaders(),
- new ItemResource(templateItem, utils));
+ converter.toResource(templateItemRest));
}
/**
@@ -148,7 +148,7 @@ public class ItemtemplateRestController {
*
* @param request
* @param uuid
- * @return Status code 204 is returned if the deletion was successful
+ * @return Status code 204 is returned if the deletion was successful
* @throws SQLException
* @throws AuthorizeException
* @throws IOException
@@ -159,22 +159,27 @@ public class ItemtemplateRestController {
throws SQLException, AuthorizeException, IOException {
Context context = ContextUtil.obtainContext(request);
- Item item = getTemplateItem(context, uuid);
- itemRestRepository.removeTemplateItem(context, item);
+ TemplateItem item = getTemplateItem(context, uuid);
+ templateItemRestRepository.removeTemplateItem(context, item);
context.commit();
return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT);
}
- private Item getTemplateItem(Context context, UUID uuid) throws SQLException {
+ private TemplateItem getTemplateItem(Context context, UUID uuid) throws SQLException {
Item item = itemService.find(context, uuid);
if (item == null) {
throw new ResourceNotFoundException(
"The given uuid did not resolve to an item on the server: " + uuid);
}
if (item.getTemplateItemOf() == null) {
+ throw new DSpaceBadRequestException("This given uuid does not resolve to a TemplateItem");
+ }
+
+ try {
+ return new TemplateItem(item);
+ } catch (IllegalArgumentException e) {
throw new UnprocessableEntityException("The item with id " + uuid + " is not a template item");
}
- return item;
}
}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/MappedCollectionRestController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/MappedCollectionRestController.java
index 3b993d582b..4681fea1a3 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/MappedCollectionRestController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/MappedCollectionRestController.java
@@ -60,14 +60,14 @@ public class MappedCollectionRestController {
* This method will add an Item to a Collection. The Collection object is encapsulated in the request due to the
* text/uri-list consumer and the Item UUID comes from the path in the URL
*
- * curl -X POST http:///api/core/item/{uuid}/mappedCollections
+ * curl -X POST http:///api/core/item/{uuid}/mappedCollections
* -H "Content-Type:text/uri-list"
* --data $'https://{url}/rest/api/core/collections/{uuid}'
*
* Example:
*
* {@code
- * curl -X POST http:///api/core/item/{uuid}/mappedCollections
+ * curl -X POST http:///api/core/item/{uuid}/mappedCollections
* -H "Content-Type:text/uri-list"
* --data $'https://{url}/rest/api/core/collections/506a7e54-8d7c-4d5b-8636-d5f6411483de'
* }
@@ -116,12 +116,12 @@ public class MappedCollectionRestController {
* This method will delete a Collection to Item relation. It will remove an Item with UUID given in the request
* URL from the Collection with UUID given in the request URL.
*
- * curl -X DELETE http:///api/core/item/{uuid}/mappedCollections/{collectionUuid}
+ * curl -X DELETE http:///api/core/item/{uuid}/mappedCollections/{collectionUuid}
*
* Example:
*
* {@code
- * curl -X DELETE http:///api/core/item/{uuid}/mappedCollections/{collectionUuid}
+ * curl -X DELETE http:///api/core/item/{uuid}/mappedCollections/{collectionUuid}
* }
*
*
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/RestResourceController.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/RestResourceController.java
index 4113469e7a..ec36721fc0 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/RestResourceController.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/RestResourceController.java
@@ -648,8 +648,7 @@ public class RestResourceController implements InitializingBean {
@RequestMapping(method = RequestMethod.PATCH, value = REGEX_REQUESTMAPPING_IDENTIFIER_AS_DIGIT)
public ResponseEntity patch(HttpServletRequest request, @PathVariable String apiCategory,
@PathVariable String model, @PathVariable Integer id,
- @RequestBody(required = true) JsonNode jsonNode)
- throws HttpRequestMethodNotSupportedException {
+ @RequestBody(required = true) JsonNode jsonNode) {
return patchInternal(request, apiCategory, model, id, jsonNode);
}
@@ -671,8 +670,7 @@ public class RestResourceController implements InitializingBean {
public ResponseEntity patch(HttpServletRequest request, @PathVariable String apiCategory,
@PathVariable String model,
@PathVariable(name = "uuid") UUID id,
- @RequestBody(required = true) JsonNode jsonNode)
- throws HttpRequestMethodNotSupportedException {
+ @RequestBody(required = true) JsonNode jsonNode) {
return patchInternal(request, apiCategory, model, id, jsonNode);
}
@@ -690,8 +688,7 @@ public class RestResourceController implements InitializingBean {
public ResponseEntity patchInternal(HttpServletRequest request,
String apiCategory,
String model, ID id,
- JsonNode jsonNode)
- throws HttpRequestMethodNotSupportedException {
+ JsonNode jsonNode) {
checkModelPluralForm(apiCategory, model);
DSpaceRestRepository repository = utils.getResourceRepository(apiCategory, model);
RestAddressableModel modelObject = null;
@@ -1058,12 +1055,12 @@ public class RestResourceController implements InitializingBean {
/**
* Execute a PUT request for an entity with id of type UUID;
*
- * curl -X PUT http:///api/{apiCategory}/{model}/{uuid}
+ * curl -X PUT http:///api/{apiCategory}/{model}/{uuid}
*
* Example:
*
* {@code
- * curl -X PUT http:///api/core/collection/8b632938-77c2-487c-81f0-e804f63e68e6
+ * curl -X PUT http:///api/core/collection/8b632938-77c2-487c-81f0-e804f63e68e6
* }
*
*
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowDefinitionCollectionsLinkRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowDefinitionCollectionsLinkRepository.java
new file mode 100644
index 0000000000..9496e32738
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowDefinitionCollectionsLinkRepository.java
@@ -0,0 +1,82 @@
+/**
+ * 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.rest;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.annotation.Nullable;
+import javax.servlet.http.HttpServletRequest;
+
+import org.dspace.app.rest.converter.ConverterService;
+import org.dspace.app.rest.model.CollectionRest;
+import org.dspace.app.rest.model.WorkflowDefinitionRest;
+import org.dspace.app.rest.projection.Projection;
+import org.dspace.app.rest.repository.AbstractDSpaceRestRepository;
+import org.dspace.app.rest.repository.LinkRestRepository;
+import org.dspace.app.rest.utils.Utils;
+import org.dspace.content.Collection;
+import org.dspace.core.Context;
+import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.rest.webmvc.ResourceNotFoundException;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.stereotype.Component;
+
+/**
+ * Link repository for "collections" subresource of an individual workflow definition.
+ *
+ * @author Maria Verdonck (Atmire) on 11/12/2019
+ */
+@Component(WorkflowDefinitionRest.CATEGORY + "." + WorkflowDefinitionRest.NAME + "."
+ + WorkflowDefinitionRest.COLLECTIONS_MAPPED_TO)
+public class WorkflowDefinitionCollectionsLinkRepository extends AbstractDSpaceRestRepository
+ implements LinkRestRepository {
+
+ @Autowired
+ protected XmlWorkflowFactory xmlWorkflowFactory;
+
+ @Autowired
+ protected ConverterService converter;
+
+ @Autowired
+ protected Utils utils;
+
+ /**
+ * GET endpoint that returns the list of collections that make an explicit use of the workflow-definition.
+ * If a collection doesn't specify the workflow-definition to be used, the default mapping applies,
+ * but this collection is not included in the list returned by this method.
+ *
+ * @param request The request object
+ * @param workflowName Name of workflow we want the collections of that are mapped to is
+ * @return List of collections mapped to the requested workflow
+ */
+ @PreAuthorize("hasAuthority('AUTHENTICATED')")
+ public Page getCollections(@Nullable HttpServletRequest request,
+ String workflowName,
+ @Nullable Pageable optionalPageable,
+ Projection projection) {
+ if (xmlWorkflowFactory.workflowByThisNameExists(workflowName)) {
+ Context context = obtainContext();
+ List collectionsMappedToWorkflow = new ArrayList<>();
+ if (xmlWorkflowFactory.isDefaultWorkflow(workflowName)) {
+ collectionsMappedToWorkflow.addAll(xmlWorkflowFactory.getAllNonMappedCollectionsHandles(context));
+ }
+ collectionsMappedToWorkflow.addAll(xmlWorkflowFactory.getCollectionHandlesMappedToWorklow(context,
+ workflowName));
+ Pageable pageable = optionalPageable != null ? optionalPageable : new PageRequest(0, 20);
+ return converter.toRestPage(utils.getPage(collectionsMappedToWorkflow, pageable),
+ projection);
+ } else {
+ throw new ResourceNotFoundException("No workflow with name " + workflowName + " is configured");
+ }
+ }
+
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowDefinitionStepsLinkRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowDefinitionStepsLinkRepository.java
new file mode 100644
index 0000000000..fe05a4c1d0
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowDefinitionStepsLinkRepository.java
@@ -0,0 +1,63 @@
+/**
+ * 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.rest;
+
+import java.util.List;
+import javax.annotation.Nullable;
+import javax.servlet.http.HttpServletRequest;
+
+import org.dspace.app.rest.model.WorkflowDefinitionRest;
+import org.dspace.app.rest.model.WorkflowStepRest;
+import org.dspace.app.rest.projection.Projection;
+import org.dspace.app.rest.repository.AbstractDSpaceRestRepository;
+import org.dspace.app.rest.repository.LinkRestRepository;
+import org.dspace.xmlworkflow.WorkflowConfigurationException;
+import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
+import org.dspace.xmlworkflow.state.Step;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.rest.webmvc.ResourceNotFoundException;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.stereotype.Component;
+
+/**
+ * Link repository for "steps" subresource of an individual workflow definition.
+ *
+ * @author Maria Verdonck (Atmire) on 24/02/2020
+ */
+@Component(WorkflowDefinitionRest.CATEGORY + "." + WorkflowDefinitionRest.NAME + "."
+ + WorkflowDefinitionRest.STEPS)
+public class WorkflowDefinitionStepsLinkRepository extends AbstractDSpaceRestRepository
+ implements LinkRestRepository {
+
+ @Autowired
+ protected XmlWorkflowFactory xmlWorkflowFactory;
+
+ /**
+ * GET endpoint that returns the list of steps of a workflow-definition.
+ *
+ * @param request The request object
+ * @param workflowName Name of workflow we want the steps from
+ * @return List of steps of the requested workflow
+ */
+ @PreAuthorize("hasAuthority('AUTHENTICATED')")
+ public Page getSteps(@Nullable HttpServletRequest request,
+ String workflowName,
+ @Nullable Pageable optionalPageable,
+ Projection projection) {
+ try {
+ List steps = xmlWorkflowFactory.getWorkflowByName(workflowName).getSteps();
+ Pageable pageable = optionalPageable != null ? optionalPageable : new PageRequest(0, 20);
+ return converter.toRestPage(utils.getPage(steps, pageable), projection);
+ } catch (WorkflowConfigurationException e) {
+ throw new ResourceNotFoundException("No workflow with name " + workflowName + " is configured");
+ }
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowStepActionsLinkRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowStepActionsLinkRepository.java
new file mode 100644
index 0000000000..b11dd929d5
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/WorkflowStepActionsLinkRepository.java
@@ -0,0 +1,57 @@
+/**
+ * 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.rest;
+
+import java.util.List;
+import javax.annotation.Nullable;
+import javax.servlet.http.HttpServletRequest;
+
+import org.dspace.app.rest.model.WorkflowActionRest;
+import org.dspace.app.rest.model.WorkflowStepRest;
+import org.dspace.app.rest.projection.Projection;
+import org.dspace.app.rest.repository.AbstractDSpaceRestRepository;
+import org.dspace.app.rest.repository.LinkRestRepository;
+import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
+import org.dspace.xmlworkflow.state.actions.WorkflowActionConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.stereotype.Component;
+
+/**
+ * Link repository for "actions" subresource of an individual workflow step.
+ *
+ * @author Maria Verdonck (Atmire) on 24/02/2020
+ */
+@Component(WorkflowStepRest.CATEGORY + "." + WorkflowStepRest.NAME + "."
+ + WorkflowStepRest.ACTIONS)
+public class WorkflowStepActionsLinkRepository extends AbstractDSpaceRestRepository
+ implements LinkRestRepository {
+
+ @Autowired
+ protected XmlWorkflowFactory xmlWorkflowFactory;
+
+ /**
+ * GET endpoint that returns the list of actions of a workflow step.
+ *
+ * @param request The request object
+ * @param workflowStepName Name of workflow step we want the actions from
+ * @return List of actions of the requested workflow step
+ */
+ @PreAuthorize("hasAuthority('AUTHENTICATED')")
+ public Page getActions(@Nullable HttpServletRequest request,
+ String workflowStepName,
+ @Nullable Pageable optionalPageable,
+ Projection projection) {
+ List actions = xmlWorkflowFactory.getStepByName(workflowStepName).getActions();
+ Pageable pageable = optionalPageable != null ? optionalPageable : new PageRequest(0, 20);
+ return converter.toRestPage(utils.getPage(actions, pageable), projection);
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ConverterService.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ConverterService.java
index 9e4f6c00f1..295634599b 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ConverterService.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ConverterService.java
@@ -32,6 +32,7 @@ import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
+import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@@ -155,9 +156,30 @@ public class ConverterService {
* @throws ClassCastException if the resource type is not compatible with the inferred return type.
*/
public T toResource(RestModel restObject) {
+ return toResource(restObject, new Link[] {});
+ }
+
+ /**
+ * Converts the given rest object to a {@link HALResource} object.
+ *
+ * If the rest object is a {@link RestAddressableModel}, the projection returned by
+ * {@link RestAddressableModel#getProjection()} will be used to determine which optional
+ * embeds and links will be added, and {@link Projection#transformResource(HALResource)}
+ * will be automatically called before returning the final, fully converted resource.
+ *
+ * In all cases, the {@link HalLinkService} will be used immediately after the resource is constructed,
+ * to ensure all {@link HalLinkFactory}s have had a chance to add links as needed.
+ *
+ *
+ * @param restObject the input rest object.
+ * @param oldLinks The old links fo the Resource Object
+ * @param the return type, a subclass of {@link HALResource}.
+ * @return the fully converted resource, with all automatic links and embeds applied.
+ */
+ public T toResource(RestModel restObject, Link... oldLinks) {
T halResource = getResource(restObject);
if (restObject instanceof RestAddressableModel) {
- utils.embedOrLinkClassLevelRels(halResource);
+ utils.embedOrLinkClassLevelRels(halResource, oldLinks);
halLinkService.addLinks(halResource);
Projection projection = ((RestAddressableModel) restObject).getProjection();
return projection.transformResource(halResource);
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ResourcePolicyConverter.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ResourcePolicyConverter.java
index 1e7834d7ed..ab8694874c 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ResourcePolicyConverter.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/ResourcePolicyConverter.java
@@ -26,12 +26,6 @@ public class ResourcePolicyConverter implements DSpaceConverter {
+
+ @Autowired
+ ConverterService converter;
+
+ @Autowired
+ private ItemService itemService;
+
+ @Override
+ public TemplateItemRest convert(TemplateItem templateItem, Projection projection) {
+ TemplateItemRest templateItemRest = new TemplateItemRest();
+ templateItemRest.setProjection(projection);
+ if (templateItem.getID() != null) {
+ templateItemRest.setId(templateItem.getID());
+ templateItemRest.setUuid(templateItem.getID());
+ }
+
+ templateItemRest.setLastModified(templateItem.getLastModified());
+ Collection templateItemOf = templateItem.getTemplateItemOf();
+ if (templateItemOf != null) {
+ templateItemRest.setTemplateItemOf(converter.toRest(templateItemOf, projection));
+ }
+
+ List fullList =
+ itemService.getMetadata(templateItem.getItem(), Item.ANY, Item.ANY, Item.ANY, Item.ANY, true);
+ MetadataValueList metadataValues = new MetadataValueList(fullList);
+ templateItemRest.setMetadata(converter.toRest(metadataValues, projection));
+
+ return templateItemRest;
+ }
+
+ @Override
+ public Class getModelClass() {
+ return TemplateItem.class;
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowActionConverter.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowActionConverter.java
new file mode 100644
index 0000000000..ee6479433e
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowActionConverter.java
@@ -0,0 +1,36 @@
+/**
+ * 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.rest.converter;
+
+import org.dspace.app.rest.model.WorkflowActionRest;
+import org.dspace.app.rest.projection.Projection;
+import org.dspace.xmlworkflow.state.actions.WorkflowActionConfig;
+import org.springframework.stereotype.Component;
+
+/**
+ * Converter to translate {@link WorkflowActionConfig} to a {@link WorkflowActionRest} object
+ *
+ * @author Maria Verdonck (Atmire) on 06/01/2020
+ */
+@Component
+public class WorkflowActionConverter implements DSpaceConverter {
+
+ @Override
+ public WorkflowActionRest convert(WorkflowActionConfig modelObject, Projection projection) {
+ WorkflowActionRest restModel = new WorkflowActionRest();
+ restModel.setProjection(projection);
+ restModel.setId(modelObject.getId());
+ restModel.setOptions(modelObject.getOptions());
+ return restModel;
+ }
+
+ @Override
+ public Class getModelClass() {
+ return WorkflowActionConfig.class;
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowDefinitionConverter.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowDefinitionConverter.java
new file mode 100644
index 0000000000..04af851e8b
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowDefinitionConverter.java
@@ -0,0 +1,50 @@
+/**
+ * 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.rest.converter;
+
+import java.util.stream.Collectors;
+
+import org.dspace.app.rest.model.WorkflowDefinitionRest;
+import org.dspace.app.rest.model.WorkflowStepRest;
+import org.dspace.app.rest.projection.Projection;
+import org.dspace.xmlworkflow.factory.XmlWorkflowFactory;
+import org.dspace.xmlworkflow.state.Workflow;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Converter to translate Workflow to a Workflow Definition
+ *
+ * @author Maria Verdonck (Atmire) on 11/12/2019
+ */
+@Component
+public class WorkflowDefinitionConverter implements DSpaceConverter {
+
+ @Autowired
+ protected XmlWorkflowFactory xmlWorkflowFactory;
+
+ @Autowired
+ ConverterService converter;
+
+ @Override
+ public WorkflowDefinitionRest convert(Workflow modelObject, Projection projection) {
+ WorkflowDefinitionRest restModel = new WorkflowDefinitionRest();
+ restModel.setName(modelObject.getID());
+ restModel.setIsDefault(xmlWorkflowFactory.isDefaultWorkflow(modelObject.getID()));
+ restModel.setProjection(projection);
+ restModel.setSteps(modelObject.getSteps().stream()
+ .map(x -> (WorkflowStepRest) converter.toRest(x, projection))
+ .collect(Collectors.toList()));
+ return restModel;
+ }
+
+ @Override
+ public Class getModelClass() {
+ return Workflow.class;
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowStepConverter.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowStepConverter.java
new file mode 100644
index 0000000000..e1809f2cc4
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/converter/WorkflowStepConverter.java
@@ -0,0 +1,45 @@
+/**
+ * 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.rest.converter;
+
+import java.util.stream.Collectors;
+
+import org.dspace.app.rest.model.WorkflowActionRest;
+import org.dspace.app.rest.model.WorkflowStepRest;
+import org.dspace.app.rest.projection.Projection;
+import org.dspace.xmlworkflow.state.Step;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Converter to translate {@link Step} to a {@link WorkflowStepRest} object
+ *
+ * @author Maria Verdonck (Atmire) on 10/01/2020
+ */
+@Component
+public class WorkflowStepConverter implements DSpaceConverter {
+
+ @Autowired
+ ConverterService converter;
+
+ @Override
+ public WorkflowStepRest convert(Step modelObject, Projection projection) {
+ WorkflowStepRest restModel = new WorkflowStepRest();
+ restModel.setProjection(projection);
+ restModel.setId(modelObject.getId());
+ restModel.setWorkflowactions(modelObject.getActions().stream()
+ .map(x -> (WorkflowActionRest) converter.toRest(x, projection))
+ .collect(Collectors.toList()));
+ return restModel;
+ }
+
+ @Override
+ public Class getModelClass() {
+ return Step.class;
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/exception/DSpaceApiExceptionControllerAdvice.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/exception/DSpaceApiExceptionControllerAdvice.java
index a0b033d8c6..e0b3a86d18 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/exception/DSpaceApiExceptionControllerAdvice.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/exception/DSpaceApiExceptionControllerAdvice.java
@@ -92,34 +92,37 @@ public class DSpaceApiExceptionControllerAdvice extends ResponseEntityExceptionH
HttpStatus.UNPROCESSABLE_ENTITY.value());
}
- @ExceptionHandler( {MissingParameterException.class, QueryMethodParameterConversionException.class})
+ @ExceptionHandler(QueryMethodParameterConversionException.class)
protected void ParameterConversionException(HttpServletRequest request, HttpServletResponse response, Exception ex)
throws IOException {
-
- //422 is not defined in HttpServletResponse. Its meaning is "Unprocessable Entity".
- //Using the value from HttpStatus.
- //Since this is a handled exception case, the stack trace will not be returned.
+ // we want the 400 status for missing parameters, see https://jira.lyrasis.org/browse/DS-4428
sendErrorResponse(request, response, null,
ex.getMessage(),
- HttpStatus.UNPROCESSABLE_ENTITY.value());
+ HttpStatus.BAD_REQUEST.value());
+ }
+
+ @ExceptionHandler(MissingParameterException.class)
+ protected void MissingParameterException(HttpServletRequest request, HttpServletResponse response, Exception ex)
+ throws IOException {
+ // we want the 400 status for missing parameters, see https://jira.lyrasis.org/browse/DS-4428
+ sendErrorResponse(request, response, null,
+ ex.getMessage(),
+ HttpStatus.BAD_REQUEST.value());
}
@Override
protected ResponseEntity handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
HttpHeaders headers, HttpStatus status,
WebRequest request) {
- // we want the 422 status for missing parameter as it seems to be the common behavior for REST application, see
- // https://stackoverflow.com/questions/3050518/what-http-status-response-code-should-i-use-if-the-request-is-missing-a-required
- return super.handleMissingServletRequestParameter(ex, headers, HttpStatus.UNPROCESSABLE_ENTITY, request);
+ // we want the 400 status for missing parameters, see https://jira.lyrasis.org/browse/DS-4428
+ return super.handleMissingServletRequestParameter(ex, headers, HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
- // we want the 422 status for type mismatch on parameters as it seems to be the common behavior for REST
- // application, see
- // https://stackoverflow.com/questions/3050518/what-http-status-response-code-should-i-use-if-the-request-is-missing-a-required
- return super.handleTypeMismatch(ex, headers, HttpStatus.UNPROCESSABLE_ENTITY, request);
+ // we want the 400 status for missing parameters, see https://jira.lyrasis.org/browse/DS-4428
+ return super.handleTypeMismatch(ex, headers, HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler(Exception.class)
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/link/process/ProcessResourceHalLinkFactory.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/link/process/ProcessResourceHalLinkFactory.java
index 4bbf77ff97..8325080861 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/link/process/ProcessResourceHalLinkFactory.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/link/process/ProcessResourceHalLinkFactory.java
@@ -28,7 +28,7 @@ public class ProcessResourceHalLinkFactory extends HalLinkFactory list) throws Exception {
- String dspaceRestUrl = configurationService.getProperty("dspace.restUrl");
+ String dspaceRestUrl = configurationService.getProperty("dspace.server.url");
list.add(
buildLink("script", dspaceRestUrl + "/api/system/scripts/" + halResource.getContent().getScriptName()));
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CollectionRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CollectionRest.java
index b577de7327..ac248f435b 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CollectionRest.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CollectionRest.java
@@ -26,6 +26,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@LinkRest(
name = CollectionRest.MAPPED_ITEMS,
method = "getMappedItems"
+ ),
+ @LinkRest(
+ name = CollectionRest.PARENT_COMMUNITY,
+ method = "getParentCommunity"
)
})
public class CollectionRest extends DSpaceObjectRest {
@@ -37,6 +41,7 @@ public class CollectionRest extends DSpaceObjectRest {
public static final String LICENSE = "license";
public static final String LOGO = "logo";
public static final String MAPPED_ITEMS = "mappedItems";
+ public static final String PARENT_COMMUNITY = "parentCommunity";
@Override
public String getCategory() {
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CommunityRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CommunityRest.java
index c5097662c7..ee80c9633b 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CommunityRest.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/CommunityRest.java
@@ -26,6 +26,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@LinkRest(
name = CommunityRest.SUBCOMMUNITIES,
method = "getSubcommunities"
+ ),
+ @LinkRest(
+ name = CommunityRest.PARENT_COMMUNITY,
+ method = "getParentCommunity"
)
})
public class CommunityRest extends DSpaceObjectRest {
@@ -36,6 +40,8 @@ public class CommunityRest extends DSpaceObjectRest {
public static final String COLLECTIONS = "collections";
public static final String LOGO = "logo";
public static final String SUBCOMMUNITIES = "subcommunities";
+ public static final String PARENT_COMMUNITY = "parentCommunity";
+
@Override
public String getCategory() {
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/MetadataRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/MetadataRest.java
index 23474e793e..d1367c8fea 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/MetadataRest.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/MetadataRest.java
@@ -14,6 +14,7 @@ import java.util.TreeMap;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* Rest representation of a map of metadata keys to ordered lists of values.
@@ -66,4 +67,11 @@ public class MetadataRest {
public boolean equals(Object object) {
return object instanceof MetadataRest && ((MetadataRest) object).getMap().equals(map);
}
-}
\ No newline at end of file
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(7, 37)
+ .append(this.getMap())
+ .toHashCode();
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ResourcePolicyRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ResourcePolicyRest.java
index 606bd8c273..656d9049fa 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ResourcePolicyRest.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/ResourcePolicyRest.java
@@ -8,7 +8,6 @@
package org.dspace.app.rest.model;
import java.util.Date;
-import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -34,12 +33,6 @@ public class ResourcePolicyRest extends BaseObjectRest {
private String description;
- @JsonInclude(Include.NON_NULL)
- private UUID groupUUID;
-
- @JsonInclude(Include.NON_NULL)
- private UUID epersonUUID;
-
@JsonIgnore
private EPersonRest eperson;
@@ -55,14 +48,6 @@ public class ResourcePolicyRest extends BaseObjectRest {
private Date endDate;
- public UUID getGroupUUID() {
- return groupUUID;
- }
-
- public void setGroupUUID(UUID groupUuid) {
- this.groupUUID = groupUuid;
- }
-
public Date getEndDate() {
return endDate;
}
@@ -111,14 +96,6 @@ public class ResourcePolicyRest extends BaseObjectRest {
this.description = description;
}
- public UUID getEpersonUUID() {
- return epersonUUID;
- }
-
- public void setEpersonUUID(UUID epersonUUID) {
- this.epersonUUID = epersonUUID;
- }
-
public EPersonRest getEperson() {
return eperson;
}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubmissionVisibilityRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubmissionVisibilityRest.java
index 40f71a97f4..d7a35b7760 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubmissionVisibilityRest.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/SubmissionVisibilityRest.java
@@ -10,6 +10,8 @@ package org.dspace.app.rest.model;
import java.util.Objects;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
/**
* The SubmissionVisibility REST Resource. It is not addressable directly, only
* used as inline object in the SubmissionPanel resource and SubmissionForm's fields
@@ -49,4 +51,12 @@ public class SubmissionVisibilityRest {
}
return super.equals(obj);
}
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(5, 31)
+ .append(this.getMain())
+ .append(this.getOther())
+ .toHashCode();
+ }
}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/TemplateItemRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/TemplateItemRest.java
new file mode 100644
index 0000000000..cc6b11d12a
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/TemplateItemRest.java
@@ -0,0 +1,83 @@
+/**
+ * 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.rest.model;
+
+import java.util.Date;
+import java.util.UUID;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.dspace.app.rest.RestResourceController;
+
+/**
+ * The TemplateItem REST Resource
+ */
+public class TemplateItemRest extends BaseObjectRest {
+ private UUID uuid;
+
+ public static final String NAME = "itemtemplate";
+ public static final String CATEGORY = RestAddressableModel.CORE;
+ @JsonIgnore
+ private CollectionRest templateItemOf;
+ MetadataRest metadata = new MetadataRest();
+ private Date lastModified = new Date();
+
+ public Date getLastModified() {
+ return lastModified;
+ }
+
+ public void setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ }
+
+ public CollectionRest getTemplateItemOf() {
+ return templateItemOf;
+ }
+
+ public void setTemplateItemOf(CollectionRest templateItemOf) {
+ this.templateItemOf = templateItemOf;
+ }
+
+ public void setMetadata(MetadataRest metadata) {
+ this.metadata = metadata;
+ }
+
+ public MetadataRest getMetadata() {
+ return this.metadata;
+ }
+
+ @Override
+ public String getCategory() {
+ return CATEGORY;
+ }
+
+ @Override
+ public Class getController() {
+ return RestResourceController.class;
+ }
+
+ @Override
+ @JsonProperty(access = JsonProperty.Access.READ_ONLY)
+ public String getType() {
+ return NAME;
+ }
+
+ @Override
+ public UUID getId() {
+ return uuid;
+ }
+
+ public UUID getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(UUID uuid) {
+ this.uuid = uuid;
+ }
+
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/UploadBitstreamAccessConditionDTO.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/UploadBitstreamAccessConditionDTO.java
new file mode 100644
index 0000000000..120cb6a9d2
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/UploadBitstreamAccessConditionDTO.java
@@ -0,0 +1,101 @@
+/**
+ * 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.rest.model;
+
+import java.util.Date;
+import java.util.UUID;
+
+import org.dspace.app.rest.model.step.UploadBitstreamRest;
+
+/**
+ * The UploadAccessConditionDTO is a partial representation of the DSpace
+ * {@link ResourcePolicyRest} as used in the patch payload for the upload
+ * submission section (see {@link UploadBitstreamRest}. The main reason for this
+ * class is to have a DTO to use serialize/deserialize the REST model, that
+ * include reference to the GroupRest and EPersonRest object, in the upload
+ * section data in a simpler way where such reference are just UUID. Indeed, due
+ * to the fact that the RestModel class are serialized according to the HAL
+ * format and the reference are only exposed in the _links section of the
+ * RestResource it was not possible to use the {@link ResourcePolicyRest} class
+ * directly in the upload section
+ *
+ * @author Mykhaylo Boychuk (mykhaylo.boychuk at 4science.it)
+ */
+public class UploadBitstreamAccessConditionDTO {
+
+ private Integer id;
+
+ private UUID groupUUID;
+
+ private UUID epersonUUID;
+
+ private String name;
+
+ private String description;
+
+ private Date startDate;
+
+ private Date endDate;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public UUID getGroupUUID() {
+ return groupUUID;
+ }
+
+ public void setGroupUUID(UUID groupUUID) {
+ this.groupUUID = groupUUID;
+ }
+
+ public UUID getEpersonUUID() {
+ return epersonUUID;
+ }
+
+ public void setEpersonUUID(UUID epersonUUID) {
+ this.epersonUUID = epersonUUID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getStartDate() {
+ return startDate;
+ }
+
+ public void setStartDate(Date startDate) {
+ this.startDate = startDate;
+ }
+
+ public Date getEndDate() {
+ return endDate;
+ }
+
+ public void setEndDate(Date endDate) {
+ this.endDate = endDate;
+ }
+
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowActionRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowActionRest.java
new file mode 100644
index 0000000000..e998df6bc2
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowActionRest.java
@@ -0,0 +1,59 @@
+/**
+ * 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.rest.model;
+
+import java.util.List;
+
+import org.dspace.app.rest.RestResourceController;
+
+/**
+ * The rest resource used for workflow actions
+ *
+ * @author Maria Verdonck (Atmire) on 06/01/2020
+ */
+public class WorkflowActionRest extends BaseObjectRest {
+
+ public static final String CATEGORY = "config";
+ public static final String NAME = "workflowaction";
+ public static final String NAME_PLURAL = "workflowactions";
+
+ private List options;
+
+ @Override
+ public String getCategory() {
+ return CATEGORY;
+ }
+
+ @Override
+ public Class getController() {
+ return RestResourceController.class;
+ }
+
+ @Override
+ public String getType() {
+ return NAME;
+ }
+
+ /**
+ * Generic getter for the options
+ *
+ * @return the options value of this WorkflowActionRest
+ */
+ public List getOptions() {
+ return options;
+ }
+
+ /**
+ * Generic setter for the options
+ *
+ * @param options The options to be set on this WorkflowActionRest
+ */
+ public void setOptions(List options) {
+ this.options = options;
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowDefinitionRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowDefinitionRest.java
new file mode 100644
index 0000000000..7c2de7071b
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowDefinitionRest.java
@@ -0,0 +1,88 @@
+/**
+ * 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.rest.model;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.dspace.app.rest.RestResourceController;
+
+/**
+ * The rest resource used for workflow definitions
+ *
+ * @author Maria Verdonck (Atmire) on 11/12/2019
+ */
+@LinksRest(links = {
+ @LinkRest(
+ name = WorkflowDefinitionRest.COLLECTIONS_MAPPED_TO,
+ method = "getCollections"
+ ),
+ @LinkRest(
+ name = WorkflowDefinitionRest.STEPS,
+ method = "getSteps"
+ )
+})
+public class WorkflowDefinitionRest extends BaseObjectRest {
+
+ public static final String CATEGORY = "config";
+ public static final String NAME = "workflowdefinition";
+ public static final String NAME_PLURAL = "workflowdefinitions";
+
+ public static final String COLLECTIONS_MAPPED_TO = "collections";
+ public static final String STEPS = "steps";
+
+ private String name;
+ private boolean isDefault;
+ private List steps;
+
+ @Override
+ public String getCategory() {
+ return CATEGORY;
+ }
+
+ @Override
+ public Class getController() {
+ return RestResourceController.class;
+ }
+
+ @Override
+ public String getType() {
+ return NAME;
+ }
+
+ @Override
+ @JsonIgnore
+ public String getId() {
+ return name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public boolean getIsDefault() {
+ return isDefault;
+ }
+
+ public void setIsDefault(boolean isDefault) {
+ this.isDefault = isDefault;
+ }
+
+ @JsonIgnore
+ public List getSteps() {
+ return steps;
+ }
+
+ public void setSteps(List steps) {
+ this.steps = steps;
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowStepRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowStepRest.java
new file mode 100644
index 0000000000..648cffbca8
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/WorkflowStepRest.java
@@ -0,0 +1,59 @@
+/**
+ * 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.rest.model;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.dspace.app.rest.RestResourceController;
+
+/**
+ * The rest resource used for workflow steps
+ *
+ * @author Maria Verdonck (Atmire) on 10/01/2020
+ */
+@LinksRest(links = {
+ @LinkRest(
+ name = WorkflowStepRest.ACTIONS,
+ method = "getActions"
+ ),
+})
+public class WorkflowStepRest extends BaseObjectRest {
+
+ public static final String CATEGORY = "config";
+ public static final String NAME = "workflowstep";
+ public static final String NAME_PLURAL = "workflowsteps";
+
+ public static final String ACTIONS = "workflowactions";
+
+ private List workflowactions;
+
+ @Override
+ public String getCategory() {
+ return CATEGORY;
+ }
+
+ @Override
+ public Class getController() {
+ return RestResourceController.class;
+ }
+
+ @Override
+ public String getType() {
+ return NAME;
+ }
+
+ @JsonIgnore
+ public List getWorkflowactions() {
+ return workflowactions;
+ }
+
+ public void setWorkflowactions(List actions) {
+ this.workflowactions = actions;
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/TemplateItemResource.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/TemplateItemResource.java
new file mode 100644
index 0000000000..d9a5db4f0b
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/TemplateItemResource.java
@@ -0,0 +1,25 @@
+/**
+ * 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.rest.model.hateoas;
+
+import org.dspace.app.rest.model.TemplateItemRest;
+import org.dspace.app.rest.model.hateoas.annotations.RelNameDSpaceResource;
+import org.dspace.app.rest.utils.Utils;
+
+/**
+ * TemplateItem Rest HAL Resource. The HAL Resource wraps the REST Resource
+ * adding support for the links and embedded resources
+ *
+ */
+@RelNameDSpaceResource(TemplateItemRest.NAME)
+public class TemplateItemResource extends DSpaceResource {
+
+ public TemplateItemResource(TemplateItemRest data, Utils utils) {
+ super(data, utils);
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowActionResource.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowActionResource.java
new file mode 100644
index 0000000000..373c6a35ac
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowActionResource.java
@@ -0,0 +1,25 @@
+/**
+ * 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.rest.model.hateoas;
+
+import org.dspace.app.rest.model.WorkflowActionRest;
+import org.dspace.app.rest.model.hateoas.annotations.RelNameDSpaceResource;
+import org.dspace.app.rest.utils.Utils;
+
+/**
+ * {@link WorkflowActionRest} HAL Resource. The HAL Resource wraps the REST Resource
+ * adding support for the links and embedded resources
+ *
+ * @author Maria Verdonck (Atmire) on 06/01/2020
+ */
+@RelNameDSpaceResource(WorkflowActionRest.NAME)
+public class WorkflowActionResource extends DSpaceResource {
+ public WorkflowActionResource(WorkflowActionRest data, Utils utils) {
+ super(data, utils);
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowDefinitionResource.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowDefinitionResource.java
new file mode 100644
index 0000000000..9247749e9d
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowDefinitionResource.java
@@ -0,0 +1,24 @@
+/**
+ * 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.rest.model.hateoas;
+
+import org.dspace.app.rest.model.WorkflowDefinitionRest;
+import org.dspace.app.rest.model.hateoas.annotations.RelNameDSpaceResource;
+import org.dspace.app.rest.utils.Utils;
+
+/**
+ * WorkflowDefinition Rest HAL Resource. The HAL Resource wraps the REST Resource
+ * adding support for the links and embedded resources
+ * @author Maria Verdonck (Atmire) on 11/12/2019
+ */
+@RelNameDSpaceResource(WorkflowDefinitionRest.NAME)
+public class WorkflowDefinitionResource extends DSpaceResource {
+ public WorkflowDefinitionResource(WorkflowDefinitionRest data, Utils utils) {
+ super(data, utils);
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowStepResource.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowStepResource.java
new file mode 100644
index 0000000000..6128c984a0
--- /dev/null
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/hateoas/WorkflowStepResource.java
@@ -0,0 +1,25 @@
+/**
+ * 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.rest.model.hateoas;
+
+import org.dspace.app.rest.model.WorkflowStepRest;
+import org.dspace.app.rest.model.hateoas.annotations.RelNameDSpaceResource;
+import org.dspace.app.rest.utils.Utils;
+
+/**
+ * {@link WorkflowStepRest} HAL Resource. The HAL Resource wraps the REST Resource
+ * adding support for the links and embedded resources
+ *
+ * @author Maria Verdonck (Atmire) on 10/01/2020
+ */
+@RelNameDSpaceResource(WorkflowStepRest.NAME)
+public class WorkflowStepResource extends DSpaceResource {
+ public WorkflowStepResource(WorkflowStepRest data, Utils utils) {
+ super(data, utils);
+ }
+}
diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/step/UploadBitstreamRest.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/step/UploadBitstreamRest.java
index 80e36fdb59..7024e5cdb1 100644
--- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/step/UploadBitstreamRest.java
+++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/model/step/UploadBitstreamRest.java
@@ -8,6 +8,7 @@
package org.dspace.app.rest.model.step;
import java.util.ArrayList;
+
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -16,13 +17,19 @@ import java.util.UUID;
import org.dspace.app.rest.model.BitstreamFormatRest;
import org.dspace.app.rest.model.CheckSumRest;
import org.dspace.app.rest.model.MetadataValueRest;
-import org.dspace.app.rest.model.ResourcePolicyRest;
+import org.dspace.app.rest.model.UploadBitstreamAccessConditionDTO;
+/**
+ * This Java Bean is used to represent a single bitstream with all its metadata
+ * and access conditions ({@link UploadBitstreamAccessConditionDTO}) inside an
+ * upload submission section ({@link DataUpload}
+ *
+ */
public class UploadBitstreamRest extends UploadStatusResponse {
private UUID uuid;
private Map> metadata = new HashMap<>();
- private List