70906: Implement community feedback

This commit is contained in:
Yana De Pauw
2020-08-20 17:23:56 +02:00
parent 0e5263e06f
commit 7d793ec2d9
14 changed files with 307 additions and 358 deletions

View File

@@ -25,9 +25,9 @@ import org.springframework.beans.factory.annotation.Autowired;
/** /**
* Class to receive usage events and send corresponding data to IRUS * Class to receive usage events and send corresponding data to IRUS
*/ */
public class ExportUsageEventListener extends AbstractUsageEventListener { public class IrusExportUsageEventListener extends AbstractUsageEventListener {
/* Log4j logger*/ /* Log4j logger*/
private static Logger log = Logger.getLogger(ExportUsageEventListener.class); private static Logger log = Logger.getLogger(IrusExportUsageEventListener.class);
@Autowired @Autowired
ConfigurationService configurationService; ConfigurationService configurationService;

View File

@@ -21,7 +21,6 @@ import org.dspace.utils.DSpace;
*/ */
public class RetryFailedOpenUrlTracker extends DSpaceRunnable<RetryFailedOpenUrlTrackerScriptConfiguration> { public class RetryFailedOpenUrlTracker extends DSpaceRunnable<RetryFailedOpenUrlTrackerScriptConfiguration> {
private Context context = null;
private String lineToAdd = null; private String lineToAdd = null;
private boolean help = false; private boolean help = false;
private boolean retryFailed = false; private boolean retryFailed = false;
@@ -39,6 +38,7 @@ public class RetryFailedOpenUrlTracker extends DSpaceRunnable<RetryFailedOpenUrl
printHelp(); printHelp();
return; return;
} }
Context context = new Context();
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
if (StringUtils.isNotBlank(lineToAdd)) { if (StringUtils.isNotBlank(lineToAdd)) {
@@ -50,11 +50,7 @@ public class RetryFailedOpenUrlTracker extends DSpaceRunnable<RetryFailedOpenUrl
openUrlService.reprocessFailedQueue(context); openUrlService.reprocessFailedQueue(context);
} }
context.restoreAuthSystemState(); context.restoreAuthSystemState();
try { context.complete();
context.complete();
} catch (Exception e) {
handler.logError(e.getMessage());
}
} }
public RetryFailedOpenUrlTrackerScriptConfiguration getScriptConfiguration() { public RetryFailedOpenUrlTrackerScriptConfiguration getScriptConfiguration() {
@@ -68,7 +64,6 @@ public class RetryFailedOpenUrlTracker extends DSpaceRunnable<RetryFailedOpenUrl
* @throws ParseException * @throws ParseException
*/ */
public void setup() throws ParseException { public void setup() throws ParseException {
context = new Context();
openUrlService = OpenURLTrackerLoggerServiceFactory.getInstance().getOpenUrlService(); openUrlService = OpenURLTrackerLoggerServiceFactory.getInstance().getOpenUrlService();
if (!(commandLine.hasOption('a') || commandLine.hasOption('r') || commandLine.hasOption('h'))) { if (!(commandLine.hasOption('a') || commandLine.hasOption('r') || commandLine.hasOption('h'))) {

View File

@@ -17,13 +17,18 @@ import org.dspace.content.Bitstream;
import org.dspace.content.Bundle; import org.dspace.content.Bundle;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
import org.dspace.statistics.util.SpiderDetector; import org.dspace.statistics.util.SpiderDetector;
/** /**
* Processor that handles Bitstream events from the ExportUsageEventListener * Processor that handles Bitstream events from the IrusExportUsageEventListener
*/ */
public class BitstreamEventProcessor extends ExportEventProcessor { public class BitstreamEventProcessor extends ExportEventProcessor {
private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
private Item item; private Item item;
private Bitstream bitstream; private Bitstream bitstream;

View File

@@ -27,7 +27,6 @@ import org.dspace.content.Item;
import org.dspace.content.MetadataValue; import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.EntityService; import org.dspace.content.service.EntityService;
import org.dspace.content.service.EntityTypeService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Utils; import org.dspace.core.Utils;
@@ -38,37 +37,23 @@ import org.dspace.statistics.export.service.OpenUrlService;
/** /**
* Abstract export event processor that contains all shared logic to handle both Items and Bitstreams * Abstract export event processor that contains all shared logic to handle both Items and Bitstreams
* from the ExportUsageEventListener * from the IrusExportUsageEventListener
*/ */
public abstract class ExportEventProcessor { public abstract class ExportEventProcessor {
private static Logger log = Logger.getLogger(ExportEventProcessor.class); private static Logger log = Logger.getLogger(ExportEventProcessor.class);
/* The metadata field which is to be checked for */
protected String trackerTypeMetadataField;
/* A list of entity types that will be processed */
protected List<String> entityTypes;
protected static final String ENTITY_TYPE_DEFAULT = "Publication"; protected static final String ENTITY_TYPE_DEFAULT = "Publication";
/* A list of values the type might have */
protected List<String> trackerTypeMetadataValues;
/* The base url of the tracker */
protected String baseUrl;
protected String trackerUrlVersion;
protected static final String ITEM_VIEW = "Investigation"; protected static final String ITEM_VIEW = "Investigation";
protected static final String BITSTREAM_DOWNLOAD = "Request"; protected static final String BITSTREAM_DOWNLOAD = "Request";
protected final static String UTF_8 = CharEncoding.UTF_8; protected final static String UTF_8 = CharEncoding.UTF_8;
protected ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
protected EntityTypeService entityTypeService = ContentServiceFactory.getInstance().getEntityTypeService(); private EntityService entityService = ContentServiceFactory.getInstance().getEntityService();
protected EntityService entityService = ContentServiceFactory.getInstance().getEntityService(); private ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService(); private OpenUrlService openUrlService = OpenURLTrackerLoggerServiceFactory.getInstance().getOpenUrlService();
protected OpenUrlService openUrlService = OpenURLTrackerLoggerServiceFactory.getInstance().getOpenUrlService();
protected Context context; protected Context context;
@@ -83,7 +68,6 @@ public abstract class ExportEventProcessor {
ExportEventProcessor(Context context, HttpServletRequest request) { ExportEventProcessor(Context context, HttpServletRequest request) {
this.context = context; this.context = context;
this.request = request; this.request = request;
initProperties();
} }
/** /**
@@ -102,6 +86,12 @@ public abstract class ExportEventProcessor {
* @throws SQLException * @throws SQLException
*/ */
protected void processObject(String urlParameters) throws IOException, SQLException { protected void processObject(String urlParameters) throws IOException, SQLException {
String baseUrl;
if (StringUtils.equals(configurationService.getProperty("stats.tracker.environment"), "production")) {
baseUrl = configurationService.getProperty("stats.tracker.produrl");
} else {
baseUrl = configurationService.getProperty("stats.tracker.testurl");
}
openUrlService.processUrl(context, baseUrl + "?" + urlParameters); openUrlService.processUrl(context, baseUrl + "?" + urlParameters);
} }
@@ -136,7 +126,8 @@ public abstract class ExportEventProcessor {
//Start adding our data //Start adding our data
StringBuilder data = new StringBuilder(); StringBuilder data = new StringBuilder();
data.append(URLEncoder.encode("url_ver", UTF_8) + "=" + URLEncoder.encode(trackerUrlVersion, UTF_8)); data.append(URLEncoder.encode("url_ver", UTF_8) + "=" +
URLEncoder.encode(configurationService.getProperty("stats.tracker.urlversion"), UTF_8));
data.append("&").append(URLEncoder.encode("req_id", UTF_8)).append("=") data.append("&").append(URLEncoder.encode("req_id", UTF_8)).append("=")
.append(URLEncoder.encode(clientIP, UTF_8)); .append(URLEncoder.encode(clientIP, UTF_8));
data.append("&").append(URLEncoder.encode("req_dat", UTF_8)).append("=") data.append("&").append(URLEncoder.encode("req_dat", UTF_8)).append("=")
@@ -203,6 +194,15 @@ public abstract class ExportEventProcessor {
Entity entity = entityService.findByItemId(context, item.getID()); Entity entity = entityService.findByItemId(context, item.getID());
EntityType type = entityService.getType(context, entity); EntityType type = entityService.getType(context, entity);
String[] entityTypeStrings = configurationService.getArrayProperty("stats.tracker.entity-types");
List<String> entityTypes = new ArrayList<>();
if (entityTypeStrings.length != 0) {
entityTypes.addAll(Arrays.asList(entityTypeStrings));
} else {
entityTypes.add(ENTITY_TYPE_DEFAULT);
}
if (type != null && entityTypes.contains(type.getLabel())) { if (type != null && entityTypes.contains(type.getLabel())) {
return true; return true;
} }
@@ -216,6 +216,18 @@ public abstract class ExportEventProcessor {
* @return whether the item should be processed * @return whether the item should be processed
*/ */
protected boolean shouldProcessItemType(Item item) { protected boolean shouldProcessItemType(Item item) {
String trackerTypeMetadataField = configurationService.getProperty("stats.tracker.type-field");
String[] metadataValues = configurationService.getArrayProperty("stats.tracker.type-value");
List<String> trackerTypeMetadataValues;
if (metadataValues.length > 0) {
trackerTypeMetadataValues = new ArrayList<>();
for (String metadataValue : metadataValues) {
trackerTypeMetadataValues.add(metadataValue.toLowerCase());
}
} else {
trackerTypeMetadataValues = null;
}
if (trackerTypeMetadataField != null && trackerTypeMetadataValues != null) { if (trackerTypeMetadataField != null && trackerTypeMetadataValues != null) {
// Contains the schema, element and if present qualifier of the metadataField // Contains the schema, element and if present qualifier of the metadataField
@@ -243,46 +255,4 @@ public abstract class ExportEventProcessor {
return true; return true;
} }
} }
/**
* Initializes services and params obtained from DSpace config
*/
private void initProperties() {
try {
if (trackerTypeMetadataField == null) {
trackerTypeMetadataField = configurationService.getProperty("stats.tracker.type-field");
String[] metadataValues = configurationService.getArrayProperty("stats.tracker.type-value");
if (metadataValues.length > 0) {
trackerTypeMetadataValues = new ArrayList<>();
for (String metadataValue : metadataValues) {
trackerTypeMetadataValues.add(metadataValue.toLowerCase());
}
} else {
trackerTypeMetadataValues = null;
}
if (StringUtils.equals(configurationService.getProperty("stats.tracker.environment"), "production")) {
baseUrl = configurationService.getProperty("stats.tracker.produrl");
} else {
baseUrl = configurationService.getProperty("stats.tracker.testurl");
}
trackerUrlVersion = configurationService.getProperty("stats.tracker.urlversion");
String[] entityTypeStrings = configurationService.getArrayProperty("stats.tracker.entity-types");
entityTypes = new ArrayList<>();
if (entityTypeStrings.length != 0) {
entityTypes.addAll(Arrays.asList(entityTypeStrings));
} else {
entityTypes.add(ENTITY_TYPE_DEFAULT);
}
}
} catch (Exception e) {
log.error("Unknown error resolving configuration for the export usage event.", e);
trackerTypeMetadataField = null;
trackerTypeMetadataValues = null;
baseUrl = null;
trackerUrlVersion = null;
}
}
} }

View File

@@ -15,17 +15,22 @@ import javax.servlet.http.HttpServletRequest;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory;
/** /**
* Processor that handles Item events from the ExportUsageEventListener * Processor that handles Item events from the IrusExportUsageEventListener
*/ */
public class ItemEventProcessor extends ExportEventProcessor { public class ItemEventProcessor extends ExportEventProcessor {
private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
private Item item; private Item item;
/** /**
* Creates a new ItemEventProcessor that will set the params * Creates a new ItemEventProcessor that will set the params
*
* @param context * @param context
* @param request * @param request
* @param item * @param item
@@ -39,6 +44,7 @@ public class ItemEventProcessor extends ExportEventProcessor {
* Process the event * Process the event
* Check if the item should be processed * Check if the item should be processed
* Create the url to be transmitted based on item data * Create the url to be transmitted based on item data
*
* @throws SQLException * @throws SQLException
* @throws IOException * @throws IOException
*/ */
@@ -52,6 +58,7 @@ public class ItemEventProcessor extends ExportEventProcessor {
/** /**
* Adds additional item data to the url * Adds additional item data to the url
*
* @param string to which the additional data needs to be added * @param string to which the additional data needs to be added
* @param item * @param item
* @return the string with additional data * @return the string with additional data
@@ -69,6 +76,7 @@ public class ItemEventProcessor extends ExportEventProcessor {
/** /**
* Get Item info used for the url * Get Item info used for the url
*
* @param item * @param item
* @return item info * @return item info
*/ */

View File

@@ -65,7 +65,11 @@ public class OpenUrlServiceImpl implements OpenUrlService {
URL url = new URL(urlStr); URL url = new URL(urlStr);
conn = url.openConnection(); conn = url.openConnection();
return ((HttpURLConnection) conn).getResponseCode(); HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
int responseCode = httpURLConnection.getResponseCode();
httpURLConnection.disconnect();
return responseCode;
} }
/** /**

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<!-- Irus statistics tracking -->
<bean class="org.dspace.statistics.export.IrusExportUsageEventListener">
<property name="eventService" ref="org.dspace.services.EventService"/>
</bean>
</beans>

View File

@@ -89,6 +89,10 @@ public class ItemBuilder extends AbstractDSpaceObjectBuilder<Item> {
return addMetadataValue(item, "relationship", "type", null, relationshipType); return addMetadataValue(item, "relationship", "type", null, relationshipType);
} }
public ItemBuilder withType(final String type) {
return addMetadataValue(item, "dc", "type", null, type);
}
public ItemBuilder withPublicationIssueNumber(final String issueNumber) { public ItemBuilder withPublicationIssueNumber(final String issueNumber) {
return addMetadataValue(item, "publicationissue", "issueNumber", null, issueNumber); return addMetadataValue(item, "publicationissue", "issueNumber", null, issueNumber);
} }

View File

@@ -7,10 +7,9 @@
*/ */
package org.dspace.statistics.export; package org.dspace.statistics.export;
import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@@ -26,8 +25,13 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.CharEncoding;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.AbstractIntegrationTest; import org.dspace.AbstractIntegrationTestWithDatabase;
import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeException;
import org.dspace.builder.BitstreamBuilder;
import org.dspace.builder.CollectionBuilder;
import org.dspace.builder.CommunityBuilder;
import org.dspace.builder.EntityTypeBuilder;
import org.dspace.builder.ItemBuilder;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
@@ -54,17 +58,14 @@ import org.dspace.usage.UsageEvent;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
/** /**
* Test class for the ExportUsageEventListener * Test class for the IrusExportUsageEventListener
*/ */
@RunWith(MockitoJUnitRunner.class) //@RunWith(MockitoJUnitRunner.class)
public class ITExportUsageEventListener extends AbstractIntegrationTest { public class ITIrusExportUsageEventListener extends AbstractIntegrationTestWithDatabase {
private static Logger log = Logger.getLogger(ITExportUsageEventListener.class); private static Logger log = Logger.getLogger(ITIrusExportUsageEventListener.class);
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService(); protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
@@ -85,8 +86,11 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
.getServiceByName("testProcessedUrls", .getServiceByName("testProcessedUrls",
ArrayList.class); ArrayList.class);
@Spy private IrusExportUsageEventListener exportUsageEventListener =
ExportUsageEventListener exportUsageEventListener; DSpaceServicesFactory.getInstance()
.getServiceManager()
.getServicesByType(IrusExportUsageEventListener.class)
.get(0);
private Item item; private Item item;
private Item itemNotToBeProcessed; private Item itemNotToBeProcessed;
@@ -104,8 +108,8 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
* Initializes the test by setting up all objects needed to create a test item * Initializes the test by setting up all objects needed to create a test item
*/ */
@Before() @Before()
public void init() { public void setUp() throws Exception {
super.init(); super.setUp();
configurationService.setProperty("stats.tracker.enabled", true); configurationService.setProperty("stats.tracker.enabled", true);
configurationService.setProperty("stats.tracker.type-field", "dc.type"); configurationService.setProperty("stats.tracker.type-field", "dc.type");
@@ -114,26 +118,25 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
try { try {
exportUsageEventListener.configurationService = configurationService;
entityType = entityTypeService.create(context, "Publication"); entityType = EntityTypeBuilder.createEntityTypeBuilder(context, "Publication").build();
community = communityService.create(null, context); community = CommunityBuilder.createCommunity(context).build();
collection = collectionService.create(context, community); collection = CollectionBuilder.createCollection(context, community).build();
item = installItemService.installItem(context, workspaceItemService.create(context, collection, false)); item = ItemBuilder.createItem(context, collection)
itemService.addMetadata(context, item, "relationship", "type", null, null, "Publication"); .withRelationshipType(entityType.getLabel())
.build();
File f = new File(testProps.get("test.bitstream").toString()); File f = new File(testProps.get("test.bitstream").toString());
bitstream = itemService.createSingleBitstream(context, new FileInputStream(f), item); bitstream = BitstreamBuilder.createBitstream(context, item, new FileInputStream(f)).build();
itemService.update(context, item);
itemNotToBeProcessed = installItemService itemNotToBeProcessed = ItemBuilder.createItem(context, collection)
.installItem(context, workspaceItemService.create(context, collection, false)); .withRelationshipType(entityType.getLabel())
itemService.addMetadata(context, itemNotToBeProcessed, "relationship", "type", null, null, "Publication"); .withType("Excluded type")
itemService.addMetadata(context, itemNotToBeProcessed, "dc", "type", null, null, "Excluded type"); .build();
File itemNotToBeProcessedFile = new File(testProps.get("test.bitstream").toString()); File itemNotToBeProcessedFile = new File(testProps.get("test.bitstream").toString());
bitstreamNotToBeProcessed = itemService.createSingleBitstream(context, bitstreamNotToBeProcessed = BitstreamBuilder
new FileInputStream(itemNotToBeProcessedFile), .createBitstream(context, itemNotToBeProcessed, new FileInputStream(itemNotToBeProcessedFile))
itemNotToBeProcessed); .build();
itemService.update(context, itemNotToBeProcessed);
String dspaceUrl = configurationService.getProperty("dspace.server.url"); String dspaceUrl = configurationService.getProperty("dspace.server.url");
encodedUrl = URLEncoder.encode(dspaceUrl, CharEncoding.UTF_8); encodedUrl = URLEncoder.encode(dspaceUrl, CharEncoding.UTF_8);
@@ -154,26 +157,15 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
* Empty the database table where the failed urls are logged * Empty the database table where the failed urls are logged
*/ */
@After @After
public void destroy() { public void destroy() throws Exception {
try { try {
context.turnOffAuthorisationSystem(); context.turnOffAuthorisationSystem();
itemService.delete(context, item);
collectionService.delete(context, collection);
communityService.delete(context, community);
entityTypeService.delete(context, entityType);
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
for (OpenURLTracker tracker : all) { for (OpenURLTracker tracker : all) {
failedOpenURLTrackerService.remove(context, tracker); failedOpenURLTrackerService.remove(context, tracker);
} }
entityType = null;
community = null;
collection = null;
item = null;
// Clear the list of processedUrls // Clear the list of processedUrls
testProcessedUrls.clear(); testProcessedUrls.clear();
@@ -203,7 +195,6 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
when(usageEvent.getRequest()).thenReturn(request); when(usageEvent.getRequest()).thenReturn(request);
when(usageEvent.getContext()).thenReturn(new Context()); when(usageEvent.getContext()).thenReturn(new Context());
doCallRealMethod().when(exportUsageEventListener).receiveEvent(usageEvent);
exportUsageEventListener.receiveEvent(usageEvent); exportUsageEventListener.receiveEvent(usageEvent);
@@ -218,9 +209,9 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
boolean isMatch = matchesString(String.valueOf(testProcessedUrls.get(0)), regex); boolean isMatch = matchesString(String.valueOf(testProcessedUrls.get(0)), regex);
assertThat(testProcessedUrls.size(), is(1)); assertEquals(1, testProcessedUrls.size());
assertThat(isMatch, is(true)); assertTrue(isMatch);
assertThat(all.size(), is(0)); assertEquals(0, all.size());
} }
@@ -239,7 +230,6 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
when(usageEvent.getRequest()).thenReturn(request); when(usageEvent.getRequest()).thenReturn(request);
when(usageEvent.getContext()).thenReturn(new Context()); when(usageEvent.getContext()).thenReturn(new Context());
doCallRealMethod().when(exportUsageEventListener).receiveEvent(usageEvent);
exportUsageEventListener.receiveEvent(usageEvent); exportUsageEventListener.receiveEvent(usageEvent);
@@ -253,10 +243,10 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
boolean isMatch = matchesString(all.get(0).getUrl(), regex); boolean isMatch = matchesString(all.get(0).getUrl(), regex);
assertThat(testProcessedUrls.size(), is(0)); assertEquals(0, testProcessedUrls.size());
assertThat(all.size(), is(1)); assertEquals(1, all.size());
assertThat(isMatch, is(true)); assertTrue(isMatch);
} }
/** /**
@@ -279,14 +269,14 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
doCallRealMethod().when(exportUsageEventListener).receiveEvent(usageEvent); // doCallRealMethod().when(IrusExportUsageEventListener).receiveEvent(usageEvent);
exportUsageEventListener.receiveEvent(usageEvent); exportUsageEventListener.receiveEvent(usageEvent);
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
assertThat(testProcessedUrls.size(), is(0)); assertEquals(0, testProcessedUrls.size());
assertThat(all.size(), is(0)); assertEquals(0, all.size());
} }
/** /**
@@ -303,7 +293,6 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
when(usageEvent.getRequest()).thenReturn(request); when(usageEvent.getRequest()).thenReturn(request);
when(usageEvent.getContext()).thenReturn(new Context()); when(usageEvent.getContext()).thenReturn(new Context());
doCallRealMethod().when(exportUsageEventListener).receiveEvent(usageEvent);
exportUsageEventListener.receiveEvent(usageEvent); exportUsageEventListener.receiveEvent(usageEvent);
String regex = "https://irus.jisc.ac.uk/counter/test/\\?url_ver=Z39.88-2004&req_id=" + String regex = "https://irus.jisc.ac.uk/counter/test/\\?url_ver=Z39.88-2004&req_id=" +
@@ -314,11 +303,11 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
boolean isMatch = matchesString(String.valueOf(testProcessedUrls.get(0)), regex); boolean isMatch = matchesString(String.valueOf(testProcessedUrls.get(0)), regex);
assertThat(testProcessedUrls.size(), is(1)); assertEquals(1, testProcessedUrls.size());
assertThat(isMatch, is(true)); assertTrue(isMatch);
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
assertThat(all.size(), is(0)); assertEquals(0, all.size());
} }
/** /**
@@ -336,7 +325,6 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
when(usageEvent.getRequest()).thenReturn(request); when(usageEvent.getRequest()).thenReturn(request);
when(usageEvent.getContext()).thenReturn(new Context()); when(usageEvent.getContext()).thenReturn(new Context());
doCallRealMethod().when(exportUsageEventListener).receiveEvent(usageEvent);
exportUsageEventListener.receiveEvent(usageEvent); exportUsageEventListener.receiveEvent(usageEvent);
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
@@ -350,9 +338,9 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
boolean isMatch = matchesString(all.get(0).getUrl(), regex); boolean isMatch = matchesString(all.get(0).getUrl(), regex);
assertThat(all.size(), is(1)); assertEquals(1, all.size());
assertThat(isMatch, is(true)); assertEquals(true, isMatch);
assertThat(testProcessedUrls.size(), is(0)); assertEquals(0, testProcessedUrls.size());
} }
@@ -377,14 +365,13 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
context.restoreAuthSystemState(); context.restoreAuthSystemState();
doCallRealMethod().when(exportUsageEventListener).receiveEvent(usageEvent);
exportUsageEventListener.receiveEvent(usageEvent); exportUsageEventListener.receiveEvent(usageEvent);
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
assertThat(all.size(), is(0)); assertEquals(0, all.size());
assertThat(testProcessedUrls.size(), is(0)); assertEquals(0, testProcessedUrls.size());
} }
@@ -400,14 +387,13 @@ public class ITExportUsageEventListener extends AbstractIntegrationTest {
when(usageEvent.getObject()).thenReturn(community); when(usageEvent.getObject()).thenReturn(community);
when(usageEvent.getContext()).thenReturn(new Context()); when(usageEvent.getContext()).thenReturn(new Context());
doCallRealMethod().when(exportUsageEventListener).receiveEvent(usageEvent);
exportUsageEventListener.receiveEvent(usageEvent); exportUsageEventListener.receiveEvent(usageEvent);
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
assertThat(all.size(), is(0)); assertEquals(0, all.size());
assertThat(testProcessedUrls.size(), is(0)); assertEquals(0, testProcessedUrls.size());
} }

View File

@@ -7,8 +7,7 @@
*/ */
package org.dspace.statistics.export; package org.dspace.statistics.export;
import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -94,9 +93,9 @@ public class ITRetryFailedOpenUrlTracker extends AbstractIntegrationTest {
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
assertThat(testProcessedUrls.size(), is(0)); assertEquals(0, testProcessedUrls.size());
assertThat(all.size(), is(1)); assertEquals(1, all.size());
assertThat(all.get(0).getUrl(), is(urlToAdd)); assertEquals(urlToAdd, all.get(0).getUrl());
} }
/** /**
@@ -126,12 +125,12 @@ public class ITRetryFailedOpenUrlTracker extends AbstractIntegrationTest {
List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context); List<OpenURLTracker> all = failedOpenURLTrackerService.findAll(context);
assertThat(testProcessedUrls.size(), is(3)); assertEquals(3, testProcessedUrls.size());
assertThat(testProcessedUrls.contains("test-url-1"), is(true)); assertEquals(true, testProcessedUrls.contains("test-url-1"));
assertThat(testProcessedUrls.contains("test-url-2"), is(true)); assertEquals(true, testProcessedUrls.contains("test-url-2"));
assertThat(testProcessedUrls.contains("test-url-3"), is(true)); assertEquals(true, testProcessedUrls.contains("test-url-3"));
assertThat(all.size(), is(0)); assertEquals(0, all.size());
} }
/** /**
@@ -169,14 +168,14 @@ public class ITRetryFailedOpenUrlTracker extends AbstractIntegrationTest {
storedTrackerUrls.add(tracker.getUrl()); storedTrackerUrls.add(tracker.getUrl());
} }
assertThat(testProcessedUrls.size(), is(2)); assertEquals(2, testProcessedUrls.size());
assertThat(testProcessedUrls.contains("test-url-1"), is(true)); assertEquals(true, testProcessedUrls.contains("test-url-1"));
assertThat(testProcessedUrls.contains("test-url-5"), is(true)); assertEquals(true, testProcessedUrls.contains("test-url-5"));
assertThat(all.size(), is(3)); assertEquals(3, all.size());
assertThat(storedTrackerUrls.contains("test-url-2-fail"), is(true)); assertEquals(true, storedTrackerUrls.contains("test-url-2-fail"));
assertThat(storedTrackerUrls.contains("test-url-3-fail"), is(true)); assertEquals(true, storedTrackerUrls.contains("test-url-3-fail"));
assertThat(storedTrackerUrls.contains("test-url-4-fail"), is(true)); assertEquals(true, storedTrackerUrls.contains("test-url-4-fail"));
} }

View File

@@ -9,43 +9,43 @@ package org.dspace.statistics.export.processor;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.UUID; import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.CharEncoding;
import org.dspace.AbstractDSpaceTest; import org.dspace.AbstractIntegrationTestWithDatabase;
import org.dspace.builder.BitstreamBuilder;
import org.dspace.builder.CollectionBuilder;
import org.dspace.builder.CommunityBuilder;
import org.dspace.builder.ItemBuilder;
import org.dspace.content.Bitstream; import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/** /**
* Test class for the BitstreamEventProcessor * Test class for the BitstreamEventProcessor
*/ */
public class BitstreamEventProcessorTest extends AbstractDSpaceTest { public class BitstreamEventProcessorTest extends AbstractIntegrationTestWithDatabase {
@Mock
private Bitstream bitstream = mock(Bitstream.class);
private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
@InjectMocks
BitstreamEventProcessor bitstreamEventProcessor = mock(BitstreamEventProcessor.class, CALLS_REAL_METHODS);
private String encodedUrl; private String encodedUrl;
@Before @Before
public void setUp() { public void setUp() throws Exception {
super.setUp();
configurationService.setProperty("stats.tracker.enabled", true); configurationService.setProperty("stats.tracker.enabled", true);
String dspaceUrl = configurationService.getProperty("dspace.server.url"); String dspaceUrl = configurationService.getProperty("dspace.server.url");
@@ -61,17 +61,26 @@ public class BitstreamEventProcessorTest extends AbstractDSpaceTest {
/** /**
* Test the method that adds data based on the object types * Test the method that adds data based on the object types
*/ */
public void testAddObectSpecificData() throws UnsupportedEncodingException { public void testAddObectSpecificData() throws Exception {
bitstreamEventProcessor.configurationService = configurationService; HttpServletRequest request = mock(HttpServletRequest.class);
when(bitstream.getID()).thenReturn(UUID.fromString("455bd3cf-31d3-40db-b283-4106c47fc025")); context.turnOffAuthorisationSystem();
Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).build();
File f = new File(testProps.get("test.bitstream").toString());
Bitstream bitstream = BitstreamBuilder.createBitstream(context, item, new FileInputStream(f)).build();
context.restoreAuthSystemState();
BitstreamEventProcessor bitstreamEventProcessor = new BitstreamEventProcessor(context, request, bitstream);
String result = bitstreamEventProcessor.addObjectSpecificData("existing-string", bitstream); String result = bitstreamEventProcessor.addObjectSpecificData("existing-string", bitstream);
assertThat(result, assertThat(result,
is("existing-string&svc_dat=" + encodedUrl + "%2Fapi%2Fcore%2Fbitstreams%2F455bd3cf-31d3-40db" + is("existing-string&svc_dat=" + encodedUrl + "%2Fapi%2Fcore%2Fbitstreams%2F" + bitstream.getID()
"-b283-4106c47fc025%2Fcontent&rft_dat=Request")); + "%2Fcontent&rft_dat=Request"));
} }

View File

@@ -7,63 +7,66 @@
*/ */
package org.dspace.statistics.export.processor; package org.dspace.statistics.export.processor;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.dspace.AbstractDSpaceTest; import org.apache.commons.codec.CharEncoding;
import org.dspace.content.Entity; import org.dspace.AbstractIntegrationTestWithDatabase;
import org.dspace.builder.CollectionBuilder;
import org.dspace.builder.CommunityBuilder;
import org.dspace.builder.EntityTypeBuilder;
import org.dspace.builder.ItemBuilder;
import org.dspace.builder.WorkspaceItemBuilder;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.EntityType; import org.dspace.content.EntityType;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.content.MetadataValue; import org.dspace.content.WorkspaceItem;
import org.dspace.content.service.EntityService;
import org.dspace.content.service.ItemService;
import org.dspace.core.Context;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
/** /**
* Test for the ExportEventProcessor class * Test for the ExportEventProcessor class
*/ */
@RunWith(MockitoJUnitRunner.class) public class ExportEventProcessorTest extends AbstractIntegrationTestWithDatabase {
public class ExportEventProcessorTest extends AbstractDSpaceTest {
@Mock
private Context context = mock(Context.class);
@Mock @Mock
private HttpServletRequest request = mock(HttpServletRequest.class); private HttpServletRequest request = mock(HttpServletRequest.class);
@Mock
private Item item = mock(Item.class);
private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
@Mock
private ItemService itemService = mock(ItemService.class);
@Mock
private EntityService entityService = mock(EntityService.class);
private EntityType publication;
@InjectMocks private EntityType otherEntity;
ExportEventProcessor exportEventProcessor = mock(ExportEventProcessor.class); private final String excluded_type = "Excluded type";
@Before @Before
public void setUp() { public void setUp() throws Exception {
super.setUp();
configurationService.setProperty("stats.tracker.urlversion", "Z39.88-2004");
configurationService.setProperty("stats.tracker.enabled", true); configurationService.setProperty("stats.tracker.enabled", true);
configurationService.setProperty("stats.tracker.type-field", "dc.type");
configurationService.setProperty("stats.tracker.type-value", "Excluded type");
context.turnOffAuthorisationSystem();
publication = EntityTypeBuilder.createEntityTypeBuilder(context, "Publication").build();
otherEntity = EntityTypeBuilder.createEntityTypeBuilder(context, "Other").build();
context.restoreAuthSystemState();
} }
@Test @Test
@@ -71,25 +74,25 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the getBaseParameters method * Test the getBaseParameters method
*/ */
public void testGetBaseParameters() throws UnsupportedEncodingException { public void testGetBaseParameters() throws UnsupportedEncodingException {
exportEventProcessor.context = context;
exportEventProcessor.request = request;
exportEventProcessor.configurationService = configurationService;
exportEventProcessor.trackerUrlVersion = "Z39.88-2004";
when(exportEventProcessor.getCurrentDateString()).thenReturn("2020-01-24T13:24:33Z"); context.turnOffAuthorisationSystem();
Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).build();
String encodedHandle = URLEncoder.encode(item.getHandle(), CharEncoding.UTF_8);
context.restoreAuthSystemState();
ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
when(request.getRemoteAddr()).thenReturn("test-client-ip"); when(request.getRemoteAddr()).thenReturn("test-client-ip");
when(request.getHeader("USER-AGENT")).thenReturn("test-user-agent"); when(request.getHeader("USER-AGENT")).thenReturn("test-user-agent");
when(request.getHeader("referer")).thenReturn("test-referer"); when(request.getHeader("referer")).thenReturn("test-referer");
when(item.getHandle()).thenReturn("123456/1");
when(exportEventProcessor.getBaseParameters(item)).thenCallRealMethod();
String result = exportEventProcessor.getBaseParameters(item); String result = exportEventProcessor.getBaseParameters(item);
String expected = "url_ver=Z39.88-2004&req_id=test-client-ip&req_dat=test-user-agent&rft.artnum=" + String expected = "url_ver=Z39.88-2004&req_id=test-client-ip&req_dat=test-user-agent&rft.artnum=" +
"oai%3Alocalhost%3A123456%2F1&rfr_dat=test-referer&rfr_id=localhost&url_tim=2020-01-24T13%3A24%3A33Z"; "oai%3Alocalhost%3A" + encodedHandle + "&rfr_dat=test-referer&rfr_id=localhost&url_tim=";
assertThat(result, is(expected)); assertThat(result, startsWith(expected));
} }
@@ -99,10 +102,8 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the ShouldProcessItem method where the item is null * Test the ShouldProcessItem method where the item is null
*/ */
public void testShouldProcessItemWhenNull() throws SQLException { public void testShouldProcessItemWhenNull() throws SQLException {
exportEventProcessor.itemService = itemService; ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, null);
exportEventProcessor.context = context;
when(exportEventProcessor.shouldProcessItem(null)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessItem(null); boolean result = exportEventProcessor.shouldProcessItem(null);
assertThat(result, is(false)); assertThat(result, is(false));
} }
@@ -112,14 +113,16 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the ShouldProcessItem method where the item is not archived * Test the ShouldProcessItem method where the item is not archived
*/ */
public void testShouldProcessItemWhenNotArchived() throws SQLException { public void testShouldProcessItemWhenNotArchived() throws SQLException {
exportEventProcessor.itemService = itemService; context.turnOffAuthorisationSystem();
exportEventProcessor.context = context; Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
WorkspaceItem workspaceItem = WorkspaceItemBuilder.createWorkspaceItem(context, collection).build();
context.restoreAuthSystemState();
when(item.isArchived()).thenReturn(false); ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, workspaceItem.getItem());
when(exportEventProcessor.shouldProcessItem(item)).thenCallRealMethod(); boolean result = exportEventProcessor.shouldProcessItem(workspaceItem.getItem());
boolean result = exportEventProcessor.shouldProcessItem(item); assertFalse(result);
assertThat(result, is(false));
} }
@Test @Test
@@ -127,16 +130,17 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the ShouldProcessItem method where the item can be edit by the current user * Test the ShouldProcessItem method where the item can be edit by the current user
*/ */
public void testShouldProcessItemWhenCanEdit() throws SQLException { public void testShouldProcessItemWhenCanEdit() throws SQLException {
exportEventProcessor.itemService = itemService; context.turnOffAuthorisationSystem();
exportEventProcessor.context = context; Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).withRelationshipType(otherEntity.getLabel()).build();
context.restoreAuthSystemState();
when(item.isArchived()).thenReturn(true); context.setCurrentUser(admin);
ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
when(itemService.canEdit(context, item)).thenReturn(true);
when(exportEventProcessor.shouldProcessItem(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessItem(item); boolean result = exportEventProcessor.shouldProcessItem(item);
assertThat(result, is(false)); assertFalse(result);
} }
@@ -144,17 +148,22 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
/** /**
* Test the ShouldProcessItem method where the item type should be excluded * Test the ShouldProcessItem method where the item type should be excluded
*/ */
public void testShouldProcessItemWhenShouldNotProcessType() throws SQLException { public void testShouldProcessItemWhenShouldNotProcessType() throws Exception {
exportEventProcessor.itemService = itemService;
exportEventProcessor.context = context;
when(item.isArchived()).thenReturn(true); context.turnOffAuthorisationSystem();
when(itemService.canEdit(context, item)).thenReturn(false); Community community = CommunityBuilder.createCommunity(context).build();
when(exportEventProcessor.shouldProcessItemType(item)).thenReturn(false); Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection)
.withType("Excluded type")
.withRelationshipType(publication.getLabel())
.build();
context.restoreAuthSystemState();
ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
when(exportEventProcessor.shouldProcessItem(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessItem(item); boolean result = exportEventProcessor.shouldProcessItem(item);
assertThat(result, is(false)); assertFalse(result);
} }
@@ -163,18 +172,16 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the ShouldProcessItem method where the item entity type should not be processed * Test the ShouldProcessItem method where the item entity type should not be processed
*/ */
public void testShouldProcessItemWhenShouldNotProcessEntity() throws SQLException { public void testShouldProcessItemWhenShouldNotProcessEntity() throws SQLException {
exportEventProcessor.itemService = itemService; context.turnOffAuthorisationSystem();
exportEventProcessor.context = context; Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).withRelationshipType(otherEntity.getLabel()).build();
context.restoreAuthSystemState();
when(item.isArchived()).thenReturn(true); ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
when(itemService.canEdit(context, item)).thenReturn(false);
when(exportEventProcessor.shouldProcessItemType(item)).thenReturn(true);
when(exportEventProcessor.shouldProcessEntityType(item)).thenReturn(false);
when(exportEventProcessor.shouldProcessItem(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessItem(item); boolean result = exportEventProcessor.shouldProcessItem(item);
assertThat(result, is(false)); assertFalse(result);
} }
@@ -183,18 +190,16 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the ShouldProcessItem method where all conditions are met * Test the ShouldProcessItem method where all conditions are met
*/ */
public void testShouldProcessItem() throws SQLException { public void testShouldProcessItem() throws SQLException {
exportEventProcessor.itemService = itemService; context.turnOffAuthorisationSystem();
exportEventProcessor.context = context; Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).withRelationshipType(publication.getLabel()).build();
context.restoreAuthSystemState();
when(item.isArchived()).thenReturn(true); ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
when(itemService.canEdit(context, item)).thenReturn(false);
when(exportEventProcessor.shouldProcessItemType(item)).thenReturn(true);
when(exportEventProcessor.shouldProcessEntityType(item)).thenReturn(true);
when(exportEventProcessor.shouldProcessItem(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessItem(item); boolean result = exportEventProcessor.shouldProcessItem(item);
assertThat(result, is(true)); assertTrue(result);
} }
@@ -204,31 +209,17 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the ShouldProcessEntityType method where all conditions are met * Test the ShouldProcessEntityType method where all conditions are met
*/ */
public void testShouldProcessEntityType() throws SQLException { public void testShouldProcessEntityType() throws SQLException {
exportEventProcessor.entityService = entityService; context.turnOffAuthorisationSystem();
Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).withRelationshipType(publication.getLabel()).build();
context.restoreAuthSystemState();
ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
String entityType1 = "entityType1";
String entityType2 = "entityType2";
Entity entity = mock(Entity.class);
EntityType itemEntityType = mock(EntityType.class);
List<String> entityTypeList = new ArrayList<>();
entityTypeList.add(entityType1);
entityTypeList.add(entityType2);
exportEventProcessor.entityTypes = entityTypeList;
when(item.getID()).thenReturn(UUID.fromString("e22a97f0-f320-4277-aff6-fdb254a751ce"));
when(entityService.findByItemId(any(Context.class), any(UUID.class)))
.thenReturn(entity);
when(entityService.getType(any(Context.class), any(Entity.class))).thenReturn(itemEntityType);
when(itemEntityType.getLabel()).thenReturn(entityType1);
when(exportEventProcessor.shouldProcessEntityType(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessEntityType(item); boolean result = exportEventProcessor.shouldProcessEntityType(item);
assertThat(result, is(true)); assertTrue(result);
} }
@Test @Test
@@ -236,32 +227,17 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the ShouldProcessEntityType method where the item entity type is not present in the configured list * Test the ShouldProcessEntityType method where the item entity type is not present in the configured list
*/ */
public void testShouldProcessEntityTypeWhenNotInList() throws SQLException { public void testShouldProcessEntityTypeWhenNotInList() throws SQLException {
exportEventProcessor.entityService = entityService; context.turnOffAuthorisationSystem();
Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).withRelationshipType(otherEntity.getLabel()).build();
context.restoreAuthSystemState();
ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
String entityType1 = "entityType1";
String entityType2 = "entityType2";
String entityType3 = "entityType3";
Entity entity = mock(Entity.class);
EntityType itemEntityType = mock(EntityType.class);
List<String> entityTypeList = new ArrayList<>();
entityTypeList.add(entityType1);
entityTypeList.add(entityType2);
exportEventProcessor.entityTypes = entityTypeList;
when(item.getID()).thenReturn(UUID.fromString("e22a97f0-f320-4277-aff6-fdb254a751ce"));
when(entityService.findByItemId(any(Context.class), any(UUID.class)))
.thenReturn(entity);
when(entityService.getType(any(Context.class), any(Entity.class))).thenReturn(itemEntityType);
when(itemEntityType.getLabel()).thenReturn(entityType3);
when(exportEventProcessor.shouldProcessEntityType(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessEntityType(item); boolean result = exportEventProcessor.shouldProcessEntityType(item);
assertThat(result, is(false)); assertFalse(result);
} }
@@ -271,28 +247,16 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the shouldProcessItemType method where the item type is present in the list of excluded types * Test the shouldProcessItemType method where the item type is present in the list of excluded types
*/ */
public void testShouldProcessItemTypeInExcludeTrackerTypeList() { public void testShouldProcessItemTypeInExcludeTrackerTypeList() {
exportEventProcessor.itemService = itemService; context.turnOffAuthorisationSystem();
Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).withType(excluded_type).build();
context.restoreAuthSystemState();
String itemField = "dc.type"; ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
exportEventProcessor.trackerTypeMetadataField = itemField;
List<String> typeList = new ArrayList<>();
typeList.add("type1");
typeList.add("type2");
exportEventProcessor.trackerTypeMetadataValues = typeList;
MetadataValue metadataValue = mock(MetadataValue.class);
when(metadataValue.getValue()).thenReturn("type2");
List<MetadataValue> values = new ArrayList<>();
values.add(metadataValue);
doReturn(values).when(itemService).getMetadata(item, "dc", "type", null, Item.ANY);
when(exportEventProcessor.shouldProcessItemType(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessItemType(item); boolean result = exportEventProcessor.shouldProcessItemType(item);
assertThat(result, is(false)); assertFalse(result);
} }
@@ -301,28 +265,16 @@ public class ExportEventProcessorTest extends AbstractDSpaceTest {
* Test the shouldProcessItemType method where the item type is not present in the list of excluded types * Test the shouldProcessItemType method where the item type is not present in the list of excluded types
*/ */
public void testShouldProcessItemTypeNotInExcludeTrackerTypeList() { public void testShouldProcessItemTypeNotInExcludeTrackerTypeList() {
exportEventProcessor.itemService = itemService; context.turnOffAuthorisationSystem();
Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).withType("Not excluded type").build();
context.restoreAuthSystemState();
String itemField = "dc.type"; ExportEventProcessor exportEventProcessor = new ItemEventProcessor(context, request, item);
exportEventProcessor.trackerTypeMetadataField = itemField;
List<String> typeList = new ArrayList<>();
typeList.add("type1");
typeList.add("type2");
exportEventProcessor.trackerTypeMetadataValues = typeList;
MetadataValue metadataValue = mock(MetadataValue.class);
when(metadataValue.getValue()).thenReturn("type3");
List<MetadataValue> values = new ArrayList<>();
values.add(metadataValue);
doReturn(values).when(itemService).getMetadata(item, "dc", "type", null, Item.ANY);
when(exportEventProcessor.shouldProcessItemType(item)).thenCallRealMethod();
boolean result = exportEventProcessor.shouldProcessItemType(item); boolean result = exportEventProcessor.shouldProcessItemType(item);
assertThat(result, is(true)); assertTrue(result);
} }

View File

@@ -9,40 +9,36 @@ package org.dspace.statistics.export.processor;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.CharEncoding;
import org.dspace.AbstractDSpaceTest; import org.dspace.AbstractIntegrationTestWithDatabase;
import org.dspace.builder.CollectionBuilder;
import org.dspace.builder.CommunityBuilder;
import org.dspace.builder.ItemBuilder;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.services.ConfigurationService; import org.dspace.services.ConfigurationService;
import org.dspace.services.factory.DSpaceServicesFactory; import org.dspace.services.factory.DSpaceServicesFactory;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
/** /**
* Test class for the ItemEventProcessor * Test class for the ItemEventProcessor
*/ */
public class ItemEventProcessorTest extends AbstractDSpaceTest { public class ItemEventProcessorTest extends AbstractIntegrationTestWithDatabase {
@Mock
private Item item = mock(Item.class);
private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService(); private ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
@InjectMocks
ItemEventProcessor itemEventProcessor = mock(ItemEventProcessor.class, CALLS_REAL_METHODS);
private String encodedUrl; private String encodedUrl;
@Before @Before
public void setUp() { public void setUp() throws Exception {
super.setUp();
configurationService.setProperty("stats.tracker.enabled", true); configurationService.setProperty("stats.tracker.enabled", true);
String dspaceUrl = configurationService.getProperty("dspace.ui.url"); String dspaceUrl = configurationService.getProperty("dspace.ui.url");
@@ -51,6 +47,7 @@ public class ItemEventProcessorTest extends AbstractDSpaceTest {
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new AssertionError("Error occurred in setup()", e); throw new AssertionError("Error occurred in setup()", e);
} }
} }
@Test @Test
@@ -58,14 +55,20 @@ public class ItemEventProcessorTest extends AbstractDSpaceTest {
* Test the method that adds data based on the object types * Test the method that adds data based on the object types
*/ */
public void testAddObectSpecificData() throws UnsupportedEncodingException { public void testAddObectSpecificData() throws UnsupportedEncodingException {
itemEventProcessor.configurationService = configurationService; context.turnOffAuthorisationSystem();
Community community = CommunityBuilder.createCommunity(context).build();
Collection collection = CollectionBuilder.createCollection(context, community).build();
Item item = ItemBuilder.createItem(context, collection).build();
context.restoreAuthSystemState();
when(item.getHandle()).thenReturn("123456789/1"); String encodedHandle = URLEncoder.encode(item.getHandle(), CharEncoding.UTF_8);
ItemEventProcessor itemEventProcessor = new ItemEventProcessor(context, null, item);
String result = itemEventProcessor.addObjectSpecificData("existing-string", item); String result = itemEventProcessor.addObjectSpecificData("existing-string", item);
assertThat(result, assertThat(result,
is("existing-string&svc_dat=" + encodedUrl + "%2Fhandle%2F123456789%2F1&rft_dat=Investigation")); is("existing-string&svc_dat=" + encodedUrl + "%2Fhandle%2F" + encodedHandle +
"&rft_dat=Investigation"));
} }

View File

@@ -22,7 +22,7 @@
</bean> </bean>
<!-- Irus statistics tracking --> <!-- Irus statistics tracking -->
<bean class="org.dspace.statistics.export.ExportUsageEventListener"> <bean class="org.dspace.statistics.export.IrusExportUsageEventListener">
<property name="eventService" ref="org.dspace.services.EventService"/> <property name="eventService" ref="org.dspace.services.EventService"/>
</bean> </bean>