Fix dspace-oai module per new code style

This commit is contained in:
Tim Donohue
2018-02-12 16:13:51 -06:00
parent de4e8bc3d1
commit 739d598f14
99 changed files with 1447 additions and 1499 deletions

View File

@@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>dspace-oai</artifactId> <artifactId>dspace-oai</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
@@ -104,8 +105,8 @@
<artifactId>xml-apis</artifactId> <artifactId>xml-apis</artifactId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
@@ -156,8 +157,8 @@
<artifactId>javassist</artifactId> <artifactId>javassist</artifactId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>

View File

@@ -16,17 +16,13 @@ import org.dspace.app.util.AbstractDSpaceWebapp;
* @author Christian Scheible (christian.scheible at uni-konstanz dot de) * @author Christian Scheible (christian.scheible at uni-konstanz dot de)
*/ */
public class DSpaceWebapp public class DSpaceWebapp
extends AbstractDSpaceWebapp extends AbstractDSpaceWebapp {
{ public DSpaceWebapp() {
public DSpaceWebapp()
{
super("OAI"); super("OAI");
} }
@Override @Override
public boolean isUI() public boolean isUI() {
{
return false; return false;
} }
} }

View File

@@ -7,16 +7,12 @@
*/ */
package org.dspace.xoai.app; package org.dspace.xoai.app;
import org.dspace.xoai.services.impl.DSpaceFieldResolver;
import org.dspace.xoai.services.impl.DSpaceHandleResolver;
import org.dspace.xoai.services.impl.DSpaceEarliestDateResolver;
import org.dspace.xoai.services.impl.DSpaceCollectionsService;
import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.CollectionsService;
import org.dspace.xoai.services.api.HandleResolver;
import org.dspace.xoai.services.api.FieldResolver;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver; import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.xoai.services.api.CollectionsService;
import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.FieldResolver;
import org.dspace.xoai.services.api.HandleResolver;
import org.dspace.xoai.services.api.cache.XOAICacheService; import org.dspace.xoai.services.api.cache.XOAICacheService;
import org.dspace.xoai.services.api.cache.XOAIItemCacheService; import org.dspace.xoai.services.api.cache.XOAIItemCacheService;
import org.dspace.xoai.services.api.cache.XOAILastCompilationCacheService; import org.dspace.xoai.services.api.cache.XOAILastCompilationCacheService;
@@ -30,6 +26,10 @@ import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver;
import org.dspace.xoai.services.api.xoai.IdentifyResolver; import org.dspace.xoai.services.api.xoai.IdentifyResolver;
import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver; import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver;
import org.dspace.xoai.services.api.xoai.SetRepositoryResolver; import org.dspace.xoai.services.api.xoai.SetRepositoryResolver;
import org.dspace.xoai.services.impl.DSpaceCollectionsService;
import org.dspace.xoai.services.impl.DSpaceEarliestDateResolver;
import org.dspace.xoai.services.impl.DSpaceFieldResolver;
import org.dspace.xoai.services.impl.DSpaceHandleResolver;
import org.dspace.xoai.services.impl.cache.DSpaceEmptyCacheService; import org.dspace.xoai.services.impl.cache.DSpaceEmptyCacheService;
import org.dspace.xoai.services.impl.cache.DSpaceXOAICacheService; import org.dspace.xoai.services.impl.cache.DSpaceXOAICacheService;
import org.dspace.xoai.services.impl.cache.DSpaceXOAIItemCacheService; import org.dspace.xoai.services.impl.cache.DSpaceXOAIItemCacheService;
@@ -63,7 +63,7 @@ public class BasicConfiguration {
@Bean @Bean
public SolrServerResolver solrServerResolver () { public SolrServerResolver solrServerResolver() {
return new DSpaceSolrServerResolver(); return new DSpaceSolrServerResolver();
} }
@@ -82,17 +82,18 @@ public class BasicConfiguration {
log.error("Not able to start XOAI normal cache service.", e); log.error("Not able to start XOAI normal cache service.", e);
return new DSpaceEmptyCacheService(); return new DSpaceEmptyCacheService();
} }
} else } else {
return new DSpaceEmptyCacheService(); return new DSpaceEmptyCacheService();
}
} }
@Bean @Bean
public XOAILastCompilationCacheService xoaiLastCompilationCacheService () { public XOAILastCompilationCacheService xoaiLastCompilationCacheService() {
return new DSpaceXOAILastCompilationCacheService(); return new DSpaceXOAILastCompilationCacheService();
} }
@Bean @Bean
public XOAIItemCacheService xoaiItemCacheService () { public XOAIItemCacheService xoaiItemCacheService() {
return new DSpaceXOAIItemCacheService(); return new DSpaceXOAIItemCacheService();
} }
@@ -103,47 +104,47 @@ public class BasicConfiguration {
} }
@Bean @Bean
public FieldResolver databaseService () { public FieldResolver databaseService() {
return new DSpaceFieldResolver(); return new DSpaceFieldResolver();
} }
@Bean @Bean
public EarliestDateResolver earliestDateResolver () { public EarliestDateResolver earliestDateResolver() {
return new DSpaceEarliestDateResolver(); return new DSpaceEarliestDateResolver();
} }
@Bean @Bean
public ItemRepositoryResolver itemRepositoryResolver () { public ItemRepositoryResolver itemRepositoryResolver() {
return new DSpaceItemRepositoryResolver(); return new DSpaceItemRepositoryResolver();
} }
@Bean @Bean
public SetRepositoryResolver setRepositoryResolver () { public SetRepositoryResolver setRepositoryResolver() {
return new DSpaceSetRepositoryResolver(); return new DSpaceSetRepositoryResolver();
} }
@Bean @Bean
public IdentifyResolver identifyResolver () { public IdentifyResolver identifyResolver() {
return new DSpaceIdentifyResolver(); return new DSpaceIdentifyResolver();
} }
@Bean @Bean
public DSpaceFilterResolver dSpaceFilterResolver () { public DSpaceFilterResolver dSpaceFilterResolver() {
return new BaseDSpaceFilterResolver(); return new BaseDSpaceFilterResolver();
} }
@Bean @Bean
public HandleResolver handleResolver () { public HandleResolver handleResolver() {
return new DSpaceHandleResolver(); return new DSpaceHandleResolver();
} }
@Bean @Bean
public CollectionsService collectionsService () { public CollectionsService collectionsService() {
return new DSpaceCollectionsService(); return new DSpaceCollectionsService();
} }
@Bean @Bean
public SolrQueryResolver solrQueryResolver () { public SolrQueryResolver solrQueryResolver() {
return new DSpaceSolrQueryResolver(); return new DSpaceSolrQueryResolver();
} }
} }

View File

@@ -7,6 +7,8 @@
*/ */
package org.dspace.xoai.app; package org.dspace.xoai.app;
import static java.lang.Integer.MAX_VALUE;
import com.lyncode.jtwig.mvc.JtwigViewResolver; import com.lyncode.jtwig.mvc.JtwigViewResolver;
import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver; import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver;
import org.dspace.xoai.services.impl.xoai.DSpaceItemRepositoryResolver; import org.dspace.xoai.services.impl.xoai.DSpaceItemRepositoryResolver;
@@ -20,10 +22,8 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import static java.lang.Integer.MAX_VALUE; @Import( {
BasicConfiguration.class
@Import({
BasicConfiguration.class
}) })
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
@@ -53,6 +53,7 @@ public class DSpaceWebappConfiguration extends WebMvcConfigurerAdapter {
return viewResolver; return viewResolver;
} }
@Bean @Bean
public ItemRepositoryResolver xoaiItemRepositoryResolver() { public ItemRepositoryResolver xoaiItemRepositoryResolver() {
return new DSpaceItemRepositoryResolver(); return new DSpaceItemRepositoryResolver();

View File

@@ -7,6 +7,21 @@
*/ */
package org.dspace.xoai.app; package org.dspace.xoai.app;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
import static org.dspace.xoai.util.ItemUtils.retrieveMetadata;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import com.lyncode.xoai.dataprovider.exceptions.ConfigurationException; import com.lyncode.xoai.dataprovider.exceptions.ConfigurationException;
import com.lyncode.xoai.dataprovider.exceptions.MetadataBindException; import com.lyncode.xoai.dataprovider.exceptions.MetadataBindException;
import com.lyncode.xoai.dataprovider.exceptions.WritingXmlException; import com.lyncode.xoai.dataprovider.exceptions.WritingXmlException;
@@ -25,15 +40,18 @@ import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
import org.dspace.authorize.factory.AuthorizeServiceFactory; import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService; import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.*; import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.content.MetadataField;
import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.handle.Handle;
import org.dspace.xoai.exceptions.CompilingException; import org.dspace.xoai.exceptions.CompilingException;
import org.dspace.xoai.services.api.CollectionsService; import org.dspace.xoai.services.api.CollectionsService;
import org.dspace.xoai.services.api.cache.XOAICacheService; import org.dspace.xoai.services.api.cache.XOAICacheService;
@@ -47,17 +65,6 @@ import org.dspace.xoai.solr.exceptions.DSpaceSolrIndexerException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
import static org.dspace.xoai.util.ItemUtils.retrieveMetadata;
/** /**
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@@ -133,15 +140,16 @@ public class XOAI {
result = this.indexAll(); result = this.indexAll();
} else { } else {
SolrQuery solrParams = new SolrQuery("*:*") SolrQuery solrParams = new SolrQuery("*:*")
.addField("item.lastmodified") .addField("item.lastmodified")
.addSortField("item.lastmodified", ORDER.desc).setRows(1); .addSortField("item.lastmodified", ORDER.desc).setRows(1);
SolrDocumentList results = DSpaceSolrSearch.query(solrServerResolver.getServer(), solrParams); SolrDocumentList results = DSpaceSolrSearch.query(solrServerResolver.getServer(), solrParams);
if (results.getNumFound() == 0) { if (results.getNumFound() == 0) {
System.out.println("There are no indexed documents, using full import."); System.out.println("There are no indexed documents, using full import.");
result = this.indexAll(); result = this.indexAll();
} else } else {
result = this.index((Date) results.get(0).getFieldValue("item.lastmodified")); result = this.index((Date) results.get(0).getFieldValue("item.lastmodified"));
}
} }
solrServerResolver.getServer().commit(); solrServerResolver.getServer().commit();
@@ -163,13 +171,13 @@ public class XOAI {
private int index(Date last) throws DSpaceSolrIndexerException { private int index(Date last) throws DSpaceSolrIndexerException {
System.out System.out
.println("Incremental import. Searching for documents modified after: " .println("Incremental import. Searching for documents modified after: "
+ last.toString()); + last.toString());
// Index both in_archive items AND withdrawn items. Withdrawn items will be flagged withdrawn // Index both in_archive items AND withdrawn items. Withdrawn items will be flagged withdrawn
// (in order to notify external OAI harvesters of their new status) // (in order to notify external OAI harvesters of their new status)
try { try {
Iterator<Item> iterator = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince( Iterator<Item> iterator = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince(
context, last); context, last);
return this.index(iterator); return this.index(iterator);
} catch (SQLException ex) { } catch (SQLException ex) {
throw new DSpaceSolrIndexerException(ex.getMessage(), ex); throw new DSpaceSolrIndexerException(ex.getMessage(), ex);
@@ -182,7 +190,7 @@ public class XOAI {
// Index both in_archive items AND withdrawn items. Withdrawn items will be flagged withdrawn // Index both in_archive items AND withdrawn items. Withdrawn items will be flagged withdrawn
// (in order to notify external OAI harvesters of their new status) // (in order to notify external OAI harvesters of their new status)
Iterator<Item> iterator = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince( Iterator<Item> iterator = itemService.findInArchiveOrWithdrawnDiscoverableModifiedSince(
context, null); context, null);
return this.index(iterator); return this.index(iterator);
} catch (SQLException ex) { } catch (SQLException ex) {
throw new DSpaceSolrIndexerException(ex.getMessage(), ex); throw new DSpaceSolrIndexerException(ex.getMessage(), ex);
@@ -190,7 +198,7 @@ public class XOAI {
} }
private int index(Iterator<Item> iterator) private int index(Iterator<Item> iterator)
throws DSpaceSolrIndexerException { throws DSpaceSolrIndexerException {
try { try {
int i = 0; int i = 0;
SolrServer server = solrServerResolver.getServer(); SolrServer server = solrServerResolver.getServer();
@@ -203,11 +211,13 @@ public class XOAI {
context.uncacheEntity(item); context.uncacheEntity(item);
} catch (SQLException | MetadataBindException | ParseException } catch (SQLException | MetadataBindException | ParseException
| XMLStreamException | WritingXmlException ex) { | XMLStreamException | WritingXmlException ex) {
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
} }
i++; i++;
if (i % 100 == 0) System.out.println(i + " items imported so far..."); if (i % 100 == 0) {
System.out.println(i + " items imported so far...");
}
} }
System.out.println("Total: " + i + " items"); System.out.println("Total: " + i + " items");
server.commit(); server.commit();
@@ -217,7 +227,8 @@ public class XOAI {
} }
} }
private SolrInputDocument index(Item item) throws SQLException, MetadataBindException, ParseException, XMLStreamException, WritingXmlException { private SolrInputDocument index(Item item)
throws SQLException, MetadataBindException, ParseException, XMLStreamException, WritingXmlException {
SolrInputDocument doc = new SolrInputDocument(); SolrInputDocument doc = new SolrInputDocument();
doc.addField("item.id", item.getID()); doc.addField("item.id", item.getID());
boolean pub = this.isPublic(item); boolean pub = this.isPublic(item);
@@ -229,20 +240,22 @@ public class XOAI {
doc.addField("item.submitter", item.getSubmitter().getEmail()); doc.addField("item.submitter", item.getSubmitter().getEmail());
} }
doc.addField("item.deleted", item.isWithdrawn() ? "true" : "false"); doc.addField("item.deleted", item.isWithdrawn() ? "true" : "false");
for (Collection col : item.getCollections()) for (Collection col : item.getCollections()) {
doc.addField("item.collections", doc.addField("item.collections",
"col_" + col.getHandle().replace("/", "_")); "col_" + col.getHandle().replace("/", "_"));
for (Community com : collectionsService.flatParentCommunities(context, item)) }
for (Community com : collectionsService.flatParentCommunities(context, item)) {
doc.addField("item.communities", doc.addField("item.communities",
"com_" + com.getHandle().replace("/", "_")); "com_" + com.getHandle().replace("/", "_"));
}
List<MetadataValue> allData = itemService.getMetadata(item, List<MetadataValue> allData = itemService.getMetadata(item,
Item.ANY, Item.ANY, Item.ANY, Item.ANY); Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (MetadataValue dc : allData) { for (MetadataValue dc : allData) {
MetadataField field = dc.getMetadataField(); MetadataField field = dc.getMetadataField();
String key = "metadata." String key = "metadata."
+ field.getMetadataSchema().getName() + "." + field.getMetadataSchema().getName() + "."
+ field.getElement(); + field.getElement();
if (field.getQualifier() != null) { if (field.getQualifier() != null) {
key += "." + field.getQualifier(); key += "." + field.getQualifier();
} }
@@ -286,8 +299,8 @@ public class XOAI {
private static boolean getKnownExplanation(Throwable t) { private static boolean getKnownExplanation(Throwable t) {
if (t instanceof ConnectException) { if (t instanceof ConnectException) {
System.err.println("Solr server (" System.err.println("Solr server ("
+ ConfigurationManager.getProperty("oai", "solr.url") + ConfigurationManager.getProperty("oai", "solr.url")
+ ") is down, turn it on."); + ") is down, turn it on.");
return true; return true;
} }
@@ -295,10 +308,12 @@ public class XOAI {
} }
private static boolean searchForReason(Throwable t) { private static boolean searchForReason(Throwable t) {
if (getKnownExplanation(t)) if (getKnownExplanation(t)) {
return true; return true;
if (t.getCause() != null) }
if (t.getCause() != null) {
return searchForReason(t.getCause()); return searchForReason(t.getCause());
}
return false; return false;
} }
@@ -313,7 +328,8 @@ public class XOAI {
} }
} }
private static void cleanCache(XOAIItemCacheService xoaiItemCacheService, XOAICacheService xoaiCacheService) throws IOException { private static void cleanCache(XOAIItemCacheService xoaiItemCacheService, XOAICacheService xoaiCacheService)
throws IOException {
System.out.println("Purging cached OAI responses."); System.out.println("Purging cached OAI responses.");
xoaiItemCacheService.deleteAll(); xoaiItemCacheService.deleteAll();
xoaiCacheService.deleteAll(); xoaiCacheService.deleteAll();
@@ -327,8 +343,8 @@ public class XOAI {
public static void main(String[] argv) throws IOException, ConfigurationException { public static void main(String[] argv) throws IOException, ConfigurationException {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(new Class[]{ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(new Class[] {
BasicConfiguration.class BasicConfiguration.class
}); });
ConfigurationService configurationService = applicationContext.getBean(ConfigurationService.class); ConfigurationService configurationService = applicationContext.getBean(ConfigurationService.class);
@@ -342,7 +358,7 @@ public class XOAI {
Options options = new Options(); Options options = new Options();
options.addOption("c", "clear", false, "Clear index before indexing"); options.addOption("c", "clear", false, "Clear index before indexing");
options.addOption("o", "optimize", false, options.addOption("o", "optimize", false,
"Optimize index at the end"); "Optimize index at the end");
options.addOption("v", "verbose", false, "Verbose output"); options.addOption("v", "verbose", false, "Verbose output");
options.addOption("h", "help", false, "Shows some help"); options.addOption("h", "help", false, "Shows some help");
options.addOption("n", "number", true, "FOR DEVELOPMENT MUST DELETE"); options.addOption("n", "number", true, "FOR DEVELOPMENT MUST DELETE");
@@ -378,14 +394,16 @@ public class XOAI {
if (COMMAND_IMPORT.equals(command)) { if (COMMAND_IMPORT.equals(command)) {
ctx = new Context(Context.Mode.READ_ONLY); ctx = new Context(Context.Mode.READ_ONLY);
XOAI indexer = new XOAI(ctx, XOAI indexer = new XOAI(ctx,
line.hasOption('o'), line.hasOption('o'),
line.hasOption('c'), line.hasOption('c'),
line.hasOption('v')); line.hasOption('v'));
applicationContext.getAutowireCapableBeanFactory().autowireBean(indexer); applicationContext.getAutowireCapableBeanFactory().autowireBean(indexer);
int imported = indexer.index(); int imported = indexer.index();
if (imported > 0) cleanCache(itemCacheService, cacheService); if (imported > 0) {
cleanCache(itemCacheService, cacheService);
}
} else if (COMMAND_CLEAN_CACHE.equals(command)) { } else if (COMMAND_CLEAN_CACHE.equals(command)) {
cleanCache(itemCacheService, cacheService); cleanCache(itemCacheService, cacheService);
} else if (COMMAND_COMPILE_ITEMS.equals(command)) { } else if (COMMAND_COMPILE_ITEMS.equals(command)) {
@@ -403,8 +421,8 @@ public class XOAI {
} }
System.out.println("OAI 2.0 manager action ended. It took " System.out.println("OAI 2.0 manager action ended. It took "
+ ((System.currentTimeMillis() - start) / 1000) + ((System.currentTimeMillis() - start) / 1000)
+ " seconds."); + " seconds.");
} else { } else {
usage(); usage();
} }
@@ -413,12 +431,11 @@ public class XOAI {
ex.printStackTrace(); ex.printStackTrace();
} }
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
} } finally {
finally
{
// Abort our context, if still open // Abort our context, if still open
if(ctx!=null && ctx.isValid()) if (ctx != null && ctx.isValid()) {
ctx.abort(); ctx.abort();
}
} }
} }
@@ -442,7 +459,9 @@ public class XOAI {
while (iterator.hasNext()) { while (iterator.hasNext()) {
Item item = iterator.next(); Item item = iterator.next();
if (verbose) System.out.println("Compiling item with handle: " + item.getHandle()); if (verbose) {
System.out.println("Compiling item with handle: " + item.getHandle());
}
xoaiItemCacheService.put(item, retrieveMetadata(context, item)); xoaiItemCacheService.put(item, retrieveMetadata(context, item));
} }

View File

@@ -7,6 +7,21 @@
*/ */
package org.dspace.xoai.controller; package org.dspace.xoai.controller;
import static java.util.Arrays.asList;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static org.apache.log4j.Logger.getLogger;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;
import com.lyncode.xoai.dataprovider.OAIDataProvider; import com.lyncode.xoai.dataprovider.OAIDataProvider;
import com.lyncode.xoai.dataprovider.OAIRequestParameters; import com.lyncode.xoai.dataprovider.OAIRequestParameters;
import com.lyncode.xoai.dataprovider.core.XOAIManager; import com.lyncode.xoai.dataprovider.core.XOAIManager;
@@ -30,41 +45,30 @@ import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static org.apache.log4j.Logger.getLogger;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@Controller @Controller
public class DSpaceOAIDataProvider public class DSpaceOAIDataProvider {
{
private static final Logger log = getLogger(DSpaceOAIDataProvider.class); private static final Logger log = getLogger(DSpaceOAIDataProvider.class);
@Autowired XOAICacheService cacheService; @Autowired
@Autowired ContextService contextService; XOAICacheService cacheService;
@Autowired XOAIManagerResolver xoaiManagerResolver; @Autowired
@Autowired ItemRepositoryResolver itemRepositoryResolver; ContextService contextService;
@Autowired IdentifyResolver identifyResolver; @Autowired
@Autowired SetRepositoryResolver setRepositoryResolver; XOAIManagerResolver xoaiManagerResolver;
@Autowired
ItemRepositoryResolver itemRepositoryResolver;
@Autowired
IdentifyResolver identifyResolver;
@Autowired
SetRepositoryResolver setRepositoryResolver;
private DSpaceResumptionTokenFormatter resumptionTokenFormat = new DSpaceResumptionTokenFormatter(); private DSpaceResumptionTokenFormatter resumptionTokenFormat = new DSpaceResumptionTokenFormatter();
@RequestMapping("/") @RequestMapping("/")
public String indexAction (HttpServletResponse response, Model model) throws ServletException { public String indexAction(HttpServletResponse response, Model model) throws ServletException {
try { try {
XOAIManager manager = xoaiManagerResolver.getManager(); XOAIManager manager = xoaiManagerResolver.getManager();
model.addAttribute("contexts", manager.getContextManager().getContexts()); model.addAttribute("contexts", manager.getContextManager().getContexts());
@@ -77,7 +81,8 @@ public class DSpaceOAIDataProvider
} }
@RequestMapping("/{context}") @RequestMapping("/{context}")
public String contextAction (Model model, HttpServletRequest request, HttpServletResponse response, @PathVariable("context") String xoaiContext) throws IOException, ServletException { public String contextAction(Model model, HttpServletRequest request, HttpServletResponse response,
@PathVariable("context") String xoaiContext) throws IOException, ServletException {
Context context = null; Context context = null;
try { try {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
@@ -86,10 +91,10 @@ public class DSpaceOAIDataProvider
XOAIManager manager = xoaiManagerResolver.getManager(); XOAIManager manager = xoaiManagerResolver.getManager();
OAIDataProvider dataProvider = new OAIDataProvider(manager, xoaiContext, OAIDataProvider dataProvider = new OAIDataProvider(manager, xoaiContext,
identifyResolver.getIdentify(), identifyResolver.getIdentify(),
setRepositoryResolver.getSetRepository(), setRepositoryResolver.getSetRepository(),
itemRepositoryResolver.getItemRepository(), itemRepositoryResolver.getItemRepository(),
resumptionTokenFormat); resumptionTokenFormat);
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
OAIRequestParameters parameters = new OAIRequestParameters(buildParametersMap(request)); OAIRequestParameters parameters = new OAIRequestParameters(buildParametersMap(request));
@@ -100,11 +105,14 @@ public class DSpaceOAIDataProvider
String identification = xoaiContext + parameters.requestID(); String identification = xoaiContext + parameters.requestID();
if (cacheService.isActive()) { if (cacheService.isActive()) {
if (!cacheService.hasCache(identification)) if (!cacheService.hasCache(identification)) {
cacheService.store(identification, dataProvider.handle(parameters)); cacheService.store(identification, dataProvider.handle(parameters));
}
cacheService.handle(identification, out); cacheService.handle(identification, out);
} else dataProvider.handle(parameters, out); } else {
dataProvider.handle(parameters, out);
}
out.flush(); out.flush();
@@ -119,24 +127,25 @@ public class DSpaceOAIDataProvider
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
closeContext(context); closeContext(context);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Unexpected error while writing the output. For more information visit the log files."); "Unexpected error while writing the output. For more information visit the log files.");
} catch (XOAIManagerResolverException e) { } catch (XOAIManagerResolverException e) {
throw new ServletException("OAI 2.0 wasn't correctly initialized, please check the log for previous errors", e); throw new ServletException("OAI 2.0 wasn't correctly initialized, please check the log for previous errors",
e);
} catch (OAIException e) { } catch (OAIException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
closeContext(context); closeContext(context);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Unexpected error. For more information visit the log files."); "Unexpected error. For more information visit the log files.");
} catch (WritingXmlException e) { } catch (WritingXmlException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
closeContext(context); closeContext(context);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Unexpected error while writing the output. For more information visit the log files."); "Unexpected error while writing the output. For more information visit the log files.");
} catch (XMLStreamException e) { } catch (XMLStreamException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
closeContext(context); closeContext(context);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Unexpected error while writing the output. For more information visit the log files."); "Unexpected error while writing the output. For more information visit the log files.");
} finally { } finally {
closeContext(context); closeContext(context);
} }
@@ -145,20 +154,21 @@ public class DSpaceOAIDataProvider
} }
private void closeContext(Context context) { private void closeContext(Context context) {
if (context != null && context.isValid()) if (context != null && context.isValid()) {
context.abort(); context.abort();
}
} }
private Map<String, List<String>> buildParametersMap( private Map<String, List<String>> buildParametersMap(
HttpServletRequest request) { HttpServletRequest request) {
Map<String, List<String>> map = new HashMap<String, List<String>>(); Map<String, List<String>> map = new HashMap<String, List<String>>();
Enumeration names = request.getParameterNames(); Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) { while (names.hasMoreElements()) {
String name = (String) names.nextElement(); String name = (String) names.nextElement();
String[] values = request.getParameterValues(name); String[] values = request.getParameterValues(name);
map.put(name, asList(values)); map.put(name, asList(values));
} }
return map; return map;
} }
} }

View File

@@ -7,6 +7,10 @@
*/ */
package org.dspace.xoai.data; package org.dspace.xoai.data;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Collections2; import com.google.common.collect.Collections2;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
@@ -16,101 +20,108 @@ import com.lyncode.xoai.dataprovider.xml.xoai.Element;
import com.lyncode.xoai.dataprovider.xml.xoai.Element.Field; import com.lyncode.xoai.dataprovider.xml.xoai.Element.Field;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public abstract class DSpaceItem implements Item public abstract class DSpaceItem implements Item {
{ private static List<Element> filter(List<Element> input, String name) {
private static List<Element> filter (List<Element> input, String name) { return Lists.newArrayList(Collections2.filter(input, new MetadataNamePredicate(name)));
return Lists.newArrayList(Collections2.filter(input, new MetadataNamePredicate(name)));
}
private static List<Element> flat (List<Element> input) {
List<Element> elems = new ArrayList<Element>();
for (Element e : input) {
if (e.getElement() != null) {
elems.addAll(e.getElement());
}
}
return elems;
}
private static List<String> values (List<Element> input) {
List<String> elems = new ArrayList<String>();
for (Element e : input)
if (e.getElement() != null && !e.getElement().isEmpty() && e.getElement().get(0).getField() != null)
for (Field f : e.getElement().get(0).getField())
if (f.getName() != null && f.getName().equals("value"))
elems.add(f.getValue());
return elems;
}
private List<String> getMetadata (String schema, String element) {
List<Element> metadata = this.getMetadata().getMetadata().getElement();
return values(filter(flat(filter(metadata, schema)), element));
}
private List<String> getMetadata (String schema, String element, String qualifier) {
List<Element> metadata = this.getMetadata().getMetadata().getElement();
return values(filter(flat(filter(flat(filter(metadata, schema)), element)), qualifier));
} }
private static List<Element> flat(List<Element> input) {
List<Element> elems = new ArrayList<Element>();
for (Element e : input) {
if (e.getElement() != null) {
elems.addAll(e.getElement());
}
}
return elems;
}
private static List<String> values(List<Element> input) {
List<String> elems = new ArrayList<String>();
for (Element e : input) {
if (e.getElement() != null && !e.getElement().isEmpty() && e.getElement().get(0).getField() != null) {
for (Field f : e.getElement().get(0).getField()) {
if (f.getName() != null && f.getName().equals("value")) {
elems.add(f.getValue());
}
}
}
}
return elems;
}
private List<String> getMetadata(String schema, String element) {
List<Element> metadata = this.getMetadata().getMetadata().getElement();
return values(filter(flat(filter(metadata, schema)), element));
}
private List<String> getMetadata(String schema, String element, String qualifier) {
List<Element> metadata = this.getMetadata().getMetadata().getElement();
return values(filter(flat(filter(flat(filter(metadata, schema)), element)), qualifier));
}
private static String _prefix = null; private static String _prefix = null;
public static String buildIdentifier (String handle) {
if (_prefix == null) public static String buildIdentifier(String handle) {
{ if (_prefix == null) {
_prefix = ConfigurationManager.getProperty("oai", _prefix = ConfigurationManager.getProperty("oai",
"identifier.prefix"); "identifier.prefix");
} }
return "oai:" + _prefix + ":" + handle; return "oai:" + _prefix + ":" + handle;
} }
public static String parseHandle (String oaiIdentifier) {
String[] parts = oaiIdentifier.split(Pattern.quote(":")); public static String parseHandle(String oaiIdentifier) {
if (parts.length > 0) return parts[parts.length - 1]; String[] parts = oaiIdentifier.split(Pattern.quote(":"));
else return null; // Contract if (parts.length > 0) {
return parts[parts.length - 1];
} else {
return null; // Contract
}
} }
public List<String> getMetadata(String field) public List<String> getMetadata(String field) {
{
String[] parts = field.split(Pattern.quote(".")); String[] parts = field.split(Pattern.quote("."));
if (parts.length == 2) return this.getMetadata(parts[0], parts[1]); if (parts.length == 2) {
else if (parts.length == 3) return this.getMetadata(parts[0], parts[1], parts[2]); return this.getMetadata(parts[0], parts[1]);
else return new ArrayList<String>(); } else if (parts.length == 3) {
return this.getMetadata(parts[0], parts[1], parts[2]);
} else {
return new ArrayList<String>();
}
} }
@Override
public List<About> getAbout()
{
return new ArrayList<About>();
}
protected abstract String getHandle ();
@Override @Override
public String getIdentifier() public List<About> getAbout() {
{ return new ArrayList<About>();
return buildIdentifier(getHandle()); }
protected abstract String getHandle();
@Override
public String getIdentifier() {
return buildIdentifier(getHandle());
} }
private static class MetadataNamePredicate implements Predicate<Element> { private static class MetadataNamePredicate implements Predicate<Element> {
private String name; private String name;
public MetadataNamePredicate (String n) { public MetadataNamePredicate(String n) {
name = n; name = n;
} }
@Override @Override
public boolean apply(Element arg0) { public boolean apply(Element arg0) {
if (name == null) return false; if (name == null) {
else if (name.equals(org.dspace.content.Item.ANY)) return true; return false;
else return (name.toLowerCase().equals(arg0.getName().toLowerCase())); } else if (name.equals(org.dspace.content.Item.ANY)) {
return true;
} else {
return (name.toLowerCase().equals(arg0.getName().toLowerCase()));
}
} }
} }
} }

View File

@@ -7,38 +7,37 @@
*/ */
package org.dspace.xoai.data; package org.dspace.xoai.data;
import com.lyncode.xoai.dataprovider.core.Set;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
import com.lyncode.xoai.dataprovider.core.Set;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceSet extends Set { public class DSpaceSet extends Set {
private static final String DefaultName = "undefined"; private static final String DefaultName = "undefined";
public static String checkName(String name) { public static String checkName(String name) {
if (name != null && !name.trim().equals("")) if (name != null && !name.trim().equals("")) {
return name; return name;
return DefaultName; }
} return DefaultName;
}
public static Set newDSpaceCommunitySet(String handle, String name) { public static Set newDSpaceCommunitySet(String handle, String name) {
return new Set("com_" + handle.replace('/', '_'), checkName(name)); return new Set("com_" + handle.replace('/', '_'), checkName(name));
} }
public static Set newDSpaceCollectionSet(String handle, String name) { public static Set newDSpaceCollectionSet(String handle, String name) {
return new Set("col_" + handle.replace('/', '_'), checkName(name)); return new Set("col_" + handle.replace('/', '_'), checkName(name));
} }
public DSpaceSet(Community c) { public DSpaceSet(Community c) {
super("com_" + c.getHandle().replace('/', '_'), checkName(c.getName())); super("com_" + c.getHandle().replace('/', '_'), checkName(c.getName()));
} }
public DSpaceSet(Collection c) { public DSpaceSet(Collection c) {
super("col_" + c.getHandle().replace('/', '_'), checkName(c.getName())); super("col_" + c.getHandle().replace('/', '_'), checkName(c.getName()));
} }
} }

View File

@@ -8,26 +8,23 @@
package org.dspace.xoai.data; package org.dspace.xoai.data;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import com.lyncode.xoai.dataprovider.core.ItemMetadata;
import com.lyncode.xoai.dataprovider.core.ReferenceSet;
import org.apache.log4j.LogManager; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocument;
import com.lyncode.xoai.dataprovider.core.ItemMetadata;
import com.lyncode.xoai.dataprovider.core.ReferenceSet;
import java.util.Collection;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceSolrItem extends DSpaceItem public class DSpaceSolrItem extends DSpaceItem {
{
private static final Logger log = LogManager private static final Logger log = LogManager
.getLogger(DSpaceSolrItem.class); .getLogger(DSpaceSolrItem.class);
private final String unparsedMD; private final String unparsedMD;
private ItemMetadata metadata; private ItemMetadata metadata;
private final String handle; private final String handle;
@@ -35,8 +32,8 @@ public class DSpaceSolrItem extends DSpaceItem
private final List<ReferenceSet> sets; private final List<ReferenceSet> sets;
private final boolean deleted; private final boolean deleted;
public DSpaceSolrItem (SolrDocument doc) { public DSpaceSolrItem(SolrDocument doc) {
log.debug("Creating OAI Item from Solr source"); log.debug("Creating OAI Item from Solr source");
unparsedMD = (String) doc.getFieldValue("item.compile"); unparsedMD = (String) doc.getFieldValue("item.compile");
handle = (String) doc.getFieldValue("item.handle"); handle = (String) doc.getFieldValue("item.handle");
lastMod = (Date) doc.getFieldValue("item.lastmodified"); lastMod = (Date) doc.getFieldValue("item.lastmodified");
@@ -45,21 +42,24 @@ public class DSpaceSolrItem extends DSpaceItem
Collection<Object> fieldValues; Collection<Object> fieldValues;
fieldValues = doc.getFieldValues("item.communities"); fieldValues = doc.getFieldValues("item.communities");
if (null != fieldValues) if (null != fieldValues) {
for (Object obj : fieldValues) for (Object obj : fieldValues) {
sets.add(new ReferenceSet((String) obj)); sets.add(new ReferenceSet((String) obj));
}
}
fieldValues = doc.getFieldValues("item.collections"); fieldValues = doc.getFieldValues("item.collections");
if (null != fieldValues) if (null != fieldValues) {
for (Object obj : fieldValues) for (Object obj : fieldValues) {
sets.add(new ReferenceSet((String) obj)); sets.add(new ReferenceSet((String) obj));
}
}
deleted = (Boolean) doc.getFieldValue("item.deleted"); deleted = (Boolean) doc.getFieldValue("item.deleted");
} }
@Override @Override
public ItemMetadata getMetadata() public ItemMetadata getMetadata() {
{
if (metadata == null) { if (metadata == null) {
metadata = new ItemMetadata(unparsedMD); metadata = new ItemMetadata(unparsedMD);
} }
@@ -67,26 +67,22 @@ public class DSpaceSolrItem extends DSpaceItem
} }
@Override @Override
public Date getDatestamp() public Date getDatestamp() {
{
return lastMod; return lastMod;
} }
@Override @Override
public List<ReferenceSet> getSets() public List<ReferenceSet> getSets() {
{
return sets; return sets;
} }
@Override @Override
public boolean isDeleted() public boolean isDeleted() {
{
return deleted; return deleted;
} }
@Override @Override
protected String getHandle() protected String getHandle() {
{
return handle; return handle;
} }

View File

@@ -9,29 +9,23 @@ package org.dspace.xoai.exceptions;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class CompilingException extends Exception public class CompilingException extends Exception {
{
public CompilingException() public CompilingException() {
{
} }
public CompilingException(String arg0) public CompilingException(String arg0) {
{
super(arg0); super(arg0);
} }
public CompilingException(Throwable arg0) public CompilingException(Throwable arg0) {
{
super(arg0); super(arg0);
} }
public CompilingException(String arg0, Throwable arg1) public CompilingException(String arg0, Throwable arg1) {
{
super(arg0, arg1); super(arg0, arg1);
} }

View File

@@ -8,11 +8,9 @@
package org.dspace.xoai.exceptions; package org.dspace.xoai.exceptions;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class InvalidMetadataFieldException extends Exception public class InvalidMetadataFieldException extends Exception {
{
private static final long serialVersionUID = 5187555092904394914L; private static final long serialVersionUID = 5187555092904394914L;

View File

@@ -22,7 +22,8 @@ public class AndFilter extends DSpaceFilter {
@Override @Override
public SolrFilterResult buildSolrQuery() { public SolrFilterResult buildSolrQuery() {
return new SolrFilterResult("("+left.buildSolrQuery().getQuery()+") AND ("+right.buildSolrQuery().getQuery()+")"); return new SolrFilterResult(
"(" + left.buildSolrQuery().getQuery() + ") AND (" + right.buildSolrQuery().getQuery() + ")");
} }
@Override @Override

View File

@@ -11,6 +11,11 @@ package org.dspace.xoai.filter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.google.common.base.Function;
import com.lyncode.builder.ListBuilder;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterList;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterValue;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.SimpleType;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@@ -19,12 +24,6 @@ import org.dspace.xoai.data.DSpaceItem;
import org.dspace.xoai.filter.data.DSpaceMetadataFilterOperator; import org.dspace.xoai.filter.data.DSpaceMetadataFilterOperator;
import org.dspace.xoai.filter.results.SolrFilterResult; import org.dspace.xoai.filter.results.SolrFilterResult;
import com.google.common.base.Function;
import com.lyncode.builder.ListBuilder;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterList;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterValue;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.SimpleType;
/** /**
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@@ -45,72 +44,87 @@ public class DSpaceAtLeastOneMetadataFilter extends DSpaceFilter {
private List<String> getValues() { private List<String> getValues() {
if (values == null) { if (values == null) {
ParameterValue parameterValue = getConfiguration().get("value"); ParameterValue parameterValue = getConfiguration().get("value");
if (parameterValue == null) parameterValue = getConfiguration().get("values"); if (parameterValue == null) {
parameterValue = getConfiguration().get("values");
}
if (parameterValue instanceof SimpleType) { if (parameterValue instanceof SimpleType) {
values = new ArrayList<>(); values = new ArrayList<>();
values.add(((SimpleType) parameterValue).asString()); values.add(((SimpleType) parameterValue).asString());
} else if (parameterValue instanceof ParameterList) { } else if (parameterValue instanceof ParameterList) {
values = new ListBuilder<ParameterValue>() values = new ListBuilder<ParameterValue>()
.add(parameterValue.asParameterList().getValues()) .add(parameterValue.asParameterList().getValues())
.build(new Function<ParameterValue, String>() { .build(new Function<ParameterValue, String>() {
@Override @Override
public String apply(ParameterValue elem) { public String apply(ParameterValue elem) {
return elem.asSimpleType().asString(); return elem.asSimpleType().asString();
} }
}); });
} else values = new ArrayList<>(); } else {
values = new ArrayList<>();
}
} }
return values; return values;
} }
private DSpaceMetadataFilterOperator getOperator() { private DSpaceMetadataFilterOperator getOperator() {
if (operator == DSpaceMetadataFilterOperator.UNDEF) if (operator == DSpaceMetadataFilterOperator.UNDEF) {
operator = DSpaceMetadataFilterOperator.valueOf(getConfiguration() operator = DSpaceMetadataFilterOperator.valueOf(getConfiguration()
.get("operator").asSimpleType().asString().toUpperCase()); .get("operator").asSimpleType().asString()
.toUpperCase());
}
return operator; return operator;
} }
@Override @Override
public boolean isShown(DSpaceItem item) { public boolean isShown(DSpaceItem item) {
if (this.getField() == null) if (this.getField() == null) {
return true; return true;
}
List<String> values = item.getMetadata(this.getField()); List<String> values = item.getMetadata(this.getField());
for (String praticalValue : values) { for (String praticalValue : values) {
for (String theoreticValue : this.getValues()) { for (String theoreticValue : this.getValues()) {
switch (this.getOperator()) { switch (this.getOperator()) {
case STARTS_WITH: case STARTS_WITH:
if (praticalValue.startsWith(theoreticValue)) if (praticalValue.startsWith(theoreticValue)) {
return true; return true;
}
break; break;
case ENDS_WITH: case ENDS_WITH:
if (praticalValue.endsWith(theoreticValue)) if (praticalValue.endsWith(theoreticValue)) {
return true; return true;
}
break; break;
case EQUAL: case EQUAL:
if (praticalValue.equals(theoreticValue)) if (praticalValue.equals(theoreticValue)) {
return true; return true;
}
break; break;
case GREATER: case GREATER:
if (praticalValue.compareTo(theoreticValue) > 0) if (praticalValue.compareTo(theoreticValue) > 0) {
return true; return true;
}
break; break;
case GREATER_OR_EQUAL: case GREATER_OR_EQUAL:
if (praticalValue.compareTo(theoreticValue) >= 0) if (praticalValue.compareTo(theoreticValue) >= 0) {
return true; return true;
}
break; break;
case LOWER: case LOWER:
if (praticalValue.compareTo(theoreticValue) < 0) if (praticalValue.compareTo(theoreticValue) < 0) {
return true; return true;
}
break; break;
case LOWER_OR_EQUAL: case LOWER_OR_EQUAL:
if (praticalValue.compareTo(theoreticValue) <= 0) if (praticalValue.compareTo(theoreticValue) <= 0) {
return true; return true;
}
break; break;
case CONTAINS: case CONTAINS:
default: default:
if (praticalValue.contains(theoreticValue)) if (praticalValue.contains(theoreticValue)) {
return true; return true;
}
break; break;
} }
} }
@@ -123,12 +137,13 @@ public class DSpaceAtLeastOneMetadataFilter extends DSpaceFilter {
String field = this.getField(); String field = this.getField();
List<String> parts = new ArrayList<>(); List<String> parts = new ArrayList<>();
if (this.getField() != null) { if (this.getField() != null) {
for (String v : this.getValues()) for (String v : this.getValues()) {
this.buildQuery("metadata." + field, this.buildQuery("metadata." + field,
ClientUtils.escapeQueryChars(v), parts); ClientUtils.escapeQueryChars(v), parts);
}
if (parts.size() > 0) { if (parts.size() > 0) {
return new SolrFilterResult(StringUtils.join(parts.iterator(), return new SolrFilterResult(StringUtils.join(parts.iterator(),
" OR ")); " OR "));
} }
} }
return new SolrFilterResult(); return new SolrFilterResult();

View File

@@ -22,46 +22,41 @@ import org.dspace.xoai.data.DSpaceItem;
import org.dspace.xoai.filter.results.SolrFilterResult; import org.dspace.xoai.filter.results.SolrFilterResult;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceAuthorizationFilter extends DSpaceFilter public class DSpaceAuthorizationFilter extends DSpaceFilter {
{
private static final Logger log = LogManager.getLogger(DSpaceAuthorizationFilter.class); private static final Logger log = LogManager.getLogger(DSpaceAuthorizationFilter.class);
private static final AuthorizeService authorizeService private static final AuthorizeService authorizeService
= AuthorizeServiceFactory.getInstance().getAuthorizeService(); = AuthorizeServiceFactory.getInstance().getAuthorizeService();
private static final HandleService handleService private static final HandleService handleService
= HandleServiceFactory.getInstance().getHandleService(); = HandleServiceFactory.getInstance().getHandleService();
@Override @Override
public boolean isShown(DSpaceItem item) public boolean isShown(DSpaceItem item) {
{
boolean pub = false; boolean pub = false;
try try {
{
// If Handle or Item are not found, return false // If Handle or Item are not found, return false
String handle = DSpaceItem.parseHandle(item.getIdentifier()); String handle = DSpaceItem.parseHandle(item.getIdentifier());
if (handle == null) if (handle == null) {
return false; return false;
}
Item dspaceItem = (Item) handleService.resolveToObject(context, handle); Item dspaceItem = (Item) handleService.resolveToObject(context, handle);
if (dspaceItem == null) if (dspaceItem == null) {
return false; return false;
}
// Check if READ access allowed on Item // Check if READ access allowed on Item
pub = authorizeService.authorizeActionBoolean(context, dspaceItem, Constants.READ); pub = authorizeService.authorizeActionBoolean(context, dspaceItem, Constants.READ);
} } catch (SQLException ex) {
catch (SQLException ex)
{
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
} }
return pub; return pub;
} }
@Override @Override
public SolrFilterResult buildSolrQuery() public SolrFilterResult buildSolrQuery() {
{
return new SolrFilterResult("item.public:true"); return new SolrFilterResult("item.public:true");
} }

View File

@@ -10,35 +10,37 @@ package org.dspace.xoai.filter;
import com.lyncode.xoai.dataprovider.data.Filter; import com.lyncode.xoai.dataprovider.data.Filter;
import com.lyncode.xoai.dataprovider.data.ItemIdentifier; import com.lyncode.xoai.dataprovider.data.ItemIdentifier;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterMap; import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterMap;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.data.DSpaceItem; import org.dspace.xoai.data.DSpaceItem;
import org.dspace.xoai.filter.results.SolrFilterResult; import org.dspace.xoai.filter.results.SolrFilterResult;
import org.dspace.xoai.services.api.FieldResolver; import org.dspace.xoai.services.api.FieldResolver;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public abstract class DSpaceFilter implements Filter public abstract class DSpaceFilter implements Filter {
{ /**
/** The configuration from xoai.xml file */ * The configuration from xoai.xml file
*/
protected ParameterMap configuration; protected ParameterMap configuration;
/** The configuration from xoai.xml file */ /**
* The configuration from xoai.xml file
*/
protected FieldResolver fieldResolver; protected FieldResolver fieldResolver;
/** The oai context */ /**
* The oai context
*/
protected Context context; protected Context context;
public abstract SolrFilterResult buildSolrQuery(); public abstract SolrFilterResult buildSolrQuery();
public abstract boolean isShown(DSpaceItem item); public abstract boolean isShown(DSpaceItem item);
@Override @Override
public boolean isItemShown(ItemIdentifier item) public boolean isItemShown(ItemIdentifier item) {
{ if (item instanceof DSpaceItem) {
if (item instanceof DSpaceItem)
{
return isShown((DSpaceItem) item); return isShown((DSpaceItem) item);
} }
return false; return false;
@@ -47,51 +49,42 @@ public abstract class DSpaceFilter implements Filter
/** /**
* @return the configuration map if defined in xoai.xml, otherwise null. * @return the configuration map if defined in xoai.xml, otherwise null.
*/ */
public ParameterMap getConfiguration() public ParameterMap getConfiguration() {
{
return configuration; return configuration;
} }
/** /**
* @param configuration * @param configuration the configuration map to set
* the configuration map to set
*/ */
public void setConfiguration(ParameterMap configuration) public void setConfiguration(ParameterMap configuration) {
{
this.configuration = configuration; this.configuration = configuration;
} }
/** /**
* @return the fieldResolver * @return the fieldResolver
*/ */
public FieldResolver getFieldResolver() public FieldResolver getFieldResolver() {
{
return fieldResolver; return fieldResolver;
} }
/** /**
* @param fieldResolver * @param fieldResolver the fieldResolver to set
* the fieldResolver to set
*/ */
public void setFieldResolver(FieldResolver fieldResolver) public void setFieldResolver(FieldResolver fieldResolver) {
{
this.fieldResolver = fieldResolver; this.fieldResolver = fieldResolver;
} }
/** /**
* @return the context * @return the context
*/ */
public Context getContext() public Context getContext() {
{
return context; return context;
} }
/** /**
* @param context * @param context the context to set
* the context to set
*/ */
public void setContext(Context context) public void setContext(Context context) {
{
this.context = context; this.context = context;
} }
} }

View File

@@ -10,14 +10,13 @@ package org.dspace.xoai.filter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterValue;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.SimpleType;
import org.apache.log4j.LogManager; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.xoai.data.DSpaceItem; import org.dspace.xoai.data.DSpaceItem;
import org.dspace.xoai.filter.results.SolrFilterResult; import org.dspace.xoai.filter.results.SolrFilterResult;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterValue;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.SimpleType;
/** /**
* This filter allows one to retrieve (from the data source) those items * This filter allows one to retrieve (from the data source) those items
* which contains at least one metadata field value defined, it allows * which contains at least one metadata field value defined, it allows
@@ -30,22 +29,25 @@ import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.SimpleType;
*/ */
public class DSpaceMetadataExistsFilter extends DSpaceFilter { public class DSpaceMetadataExistsFilter extends DSpaceFilter {
private static final Logger log = LogManager private static final Logger log = LogManager
.getLogger(DSpaceMetadataExistsFilter.class); .getLogger(DSpaceMetadataExistsFilter.class);
private List<String> fields; private List<String> fields;
private List<String> getFields() { private List<String> getFields() {
if (this.fields == null) { if (this.fields == null) {
ParameterValue fields = getConfiguration().get("fields"); ParameterValue fields = getConfiguration().get("fields");
if (fields == null) fields = getConfiguration().get("field"); if (fields == null) {
fields = getConfiguration().get("field");
}
if (fields instanceof SimpleType) { if (fields instanceof SimpleType) {
this.fields = new ArrayList<String>(); this.fields = new ArrayList<String>();
this.fields.add(((SimpleType) fields).asString()); this.fields.add(((SimpleType) fields).asString());
} else { } else {
this.fields = new ArrayList<String>(); this.fields = new ArrayList<String>();
for (ParameterValue val : fields.asParameterList().getValues()) for (ParameterValue val : fields.asParameterList().getValues()) {
this.fields.add(val.asSimpleType().asString()); this.fields.add(val.asSimpleType().asString());
}
} }
} }
@@ -56,8 +58,9 @@ public class DSpaceMetadataExistsFilter extends DSpaceFilter {
public boolean isShown(DSpaceItem item) { public boolean isShown(DSpaceItem item) {
for (String field : this.getFields()) { for (String field : this.getFields()) {
//do we have a match? if yes, our job is done //do we have a match? if yes, our job is done
if (item.getMetadata(field).size() > 0) if (item.getMetadata(field).size() > 0) {
return true; return true;
}
} }
return false; return false;
} }
@@ -68,8 +71,9 @@ public class DSpaceMetadataExistsFilter extends DSpaceFilter {
List<String> fields = this.getFields(); List<String> fields = this.getFields();
for (int i = 0; i < fields.size(); i++) { for (int i = 0; i < fields.size(); i++) {
cond.append("metadata.").append(fields.get(i)).append(":[* TO *]"); cond.append("metadata.").append(fields.get(i)).append(":[* TO *]");
if (i < fields.size() - 1) if (i < fields.size() - 1) {
cond.append(" OR "); cond.append(" OR ");
}
} }
cond.append(")"); cond.append(")");

View File

@@ -18,57 +18,45 @@ import org.dspace.xoai.services.api.HandleResolver;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceSetSpecFilter extends DSpaceFilter public class DSpaceSetSpecFilter extends DSpaceFilter {
{
private static final Logger log = LogManager.getLogger(DSpaceSetSpecFilter.class); private static final Logger log = LogManager.getLogger(DSpaceSetSpecFilter.class);
private final String setSpec; private final String setSpec;
private final HandleResolver handleResolver; private final HandleResolver handleResolver;
private final CollectionsService collectionsService; private final CollectionsService collectionsService;
public DSpaceSetSpecFilter(CollectionsService collectionsService, HandleResolver handleResolver, String spec) public DSpaceSetSpecFilter(CollectionsService collectionsService, HandleResolver handleResolver, String spec) {
{
this.collectionsService = collectionsService; this.collectionsService = collectionsService;
this.handleResolver = handleResolver; this.handleResolver = handleResolver;
this.setSpec = spec; this.setSpec = spec;
} }
@Override @Override
public boolean isShown(DSpaceItem item) public boolean isShown(DSpaceItem item) {
{ for (ReferenceSet s : item.getSets()) {
for (ReferenceSet s : item.getSets()) if (s.getSetSpec().equals(setSpec)) {
if (s.getSetSpec().equals(setSpec))
return true; return true;
}
}
return false; return false;
} }
@Override @Override
public SolrFilterResult buildSolrQuery() public SolrFilterResult buildSolrQuery() {
{ if (setSpec.startsWith("col_")) {
if (setSpec.startsWith("col_")) try {
{
try
{
return new SolrFilterResult("item.collections:" return new SolrFilterResult("item.collections:"
+ ClientUtils.escapeQueryChars(setSpec)); + ClientUtils.escapeQueryChars(setSpec));
} } catch (Exception ex) {
catch (Exception ex)
{
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
} }
} } else if (setSpec.startsWith("com_")) {
else if (setSpec.startsWith("com_")) try {
{
try
{
return new SolrFilterResult("item.communities:" return new SolrFilterResult("item.communities:"
+ ClientUtils.escapeQueryChars(setSpec)); + ClientUtils.escapeQueryChars(setSpec));
} } catch (Exception e) {
catch (Exception e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }

View File

@@ -18,14 +18,13 @@ import org.dspace.xoai.filter.results.SolrFilterResult;
* http://www.openarchives.org/OAI/openarchivesprotocol.html#deletion * http://www.openarchives.org/OAI/openarchivesprotocol.html#deletion
* <P> * <P>
* (Don't worry, a tombstone doesn't display the withdrawn item's metadata or files.) * (Don't worry, a tombstone doesn't display the withdrawn item's metadata or files.)
* *
* @author Tim Donohue * @author Tim Donohue
*/ */
public class DSpaceWithdrawnFilter extends DSpaceFilter { public class DSpaceWithdrawnFilter extends DSpaceFilter {
@Override @Override
public boolean isShown(DSpaceItem item) public boolean isShown(DSpaceItem item) {
{
// For DSpace, if an Item is withdrawn, "isDeleted()" will be true. // For DSpace, if an Item is withdrawn, "isDeleted()" will be true.
// In this scenario, we want a withdrawn item to be *shown* so that // In this scenario, we want a withdrawn item to be *shown* so that
// we can properly respond with a "deleted" status via OAI-PMH. // we can properly respond with a "deleted" status via OAI-PMH.
@@ -35,8 +34,7 @@ public class DSpaceWithdrawnFilter extends DSpaceFilter {
} }
@Override @Override
public SolrFilterResult buildSolrQuery() public SolrFilterResult buildSolrQuery() {
{
// In Solr, we store withdrawn items as "deleted". // In Solr, we store withdrawn items as "deleted".
// See org.dspace.xoai.app.XOAI, index(Item) method. // See org.dspace.xoai.app.XOAI, index(Item) method.
return new SolrFilterResult("item.deleted:true"); return new SolrFilterResult("item.deleted:true");

View File

@@ -7,6 +7,8 @@
*/ */
package org.dspace.xoai.filter; package org.dspace.xoai.filter;
import java.util.Date;
import com.lyncode.builder.DateBuilder; import com.lyncode.builder.DateBuilder;
import com.lyncode.xoai.dataprovider.services.api.DateProvider; import com.lyncode.xoai.dataprovider.services.api.DateProvider;
import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider; import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider;
@@ -14,36 +16,31 @@ import org.apache.solr.client.solrj.util.ClientUtils;
import org.dspace.xoai.data.DSpaceItem; import org.dspace.xoai.data.DSpaceItem;
import org.dspace.xoai.filter.results.SolrFilterResult; import org.dspace.xoai.filter.results.SolrFilterResult;
import java.util.Date;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DateFromFilter extends DSpaceFilter { public class DateFromFilter extends DSpaceFilter {
private static final DateProvider dateProvider = new BaseDateProvider(); private static final DateProvider dateProvider = new BaseDateProvider();
private final Date date; private final Date date;
public DateFromFilter(Date date) public DateFromFilter(Date date) {
{
this.date = new DateBuilder(date).setMinMilliseconds().build(); this.date = new DateBuilder(date).setMinMilliseconds().build();
} }
@Override @Override
public boolean isShown(DSpaceItem item) public boolean isShown(DSpaceItem item) {
{ if (item.getDatestamp().compareTo(date) >= 0) {
if (item.getDatestamp().compareTo(date) >= 0)
return true; return true;
}
return false; return false;
} }
@Override @Override
public SolrFilterResult buildSolrQuery() public SolrFilterResult buildSolrQuery() {
{
String format = dateProvider.format(date).replace("Z", ".000Z"); // Tweak to set the milliseconds String format = dateProvider.format(date).replace("Z", ".000Z"); // Tweak to set the milliseconds
return new SolrFilterResult("item.lastmodified:[" return new SolrFilterResult("item.lastmodified:["
+ ClientUtils.escapeQueryChars(format) + ClientUtils.escapeQueryChars(format)
+ " TO *]"); + " TO *]");
} }
} }

View File

@@ -7,6 +7,8 @@
*/ */
package org.dspace.xoai.filter; package org.dspace.xoai.filter;
import java.util.Date;
import com.lyncode.builder.DateBuilder; import com.lyncode.builder.DateBuilder;
import com.lyncode.xoai.dataprovider.services.api.DateProvider; import com.lyncode.xoai.dataprovider.services.api.DateProvider;
import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider; import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider;
@@ -14,41 +16,34 @@ import org.apache.solr.client.solrj.util.ClientUtils;
import org.dspace.xoai.data.DSpaceItem; import org.dspace.xoai.data.DSpaceItem;
import org.dspace.xoai.filter.results.SolrFilterResult; import org.dspace.xoai.filter.results.SolrFilterResult;
import java.util.Date;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DateUntilFilter extends DSpaceFilter public class DateUntilFilter extends DSpaceFilter {
{
private static final DateProvider dateProvider = new BaseDateProvider(); private static final DateProvider dateProvider = new BaseDateProvider();
private final Date date; private final Date date;
public DateUntilFilter(Date date) public DateUntilFilter(Date date) {
{
this.date = new DateBuilder(date).setMaxMilliseconds().build(); this.date = new DateBuilder(date).setMaxMilliseconds().build();
} }
@Override @Override
public boolean isShown(DSpaceItem item) public boolean isShown(DSpaceItem item) {
{ if (item.getDatestamp().compareTo(date) <= 0) {
if (item.getDatestamp().compareTo(date) <= 0)
return true; return true;
}
return false; return false;
} }
@Override @Override
public SolrFilterResult buildSolrQuery() public SolrFilterResult buildSolrQuery() {
{
String format = dateProvider.format(date).replace("Z", ".999Z"); // Tweak to set the milliseconds String format = dateProvider.format(date).replace("Z", ".999Z"); // Tweak to set the milliseconds
// if date has timestamp of 00:00:00, switch it to refer to end of day // if date has timestamp of 00:00:00, switch it to refer to end of day
if (format.substring(11, 19).equals("00:00:00")) if (format.substring(11, 19).equals("00:00:00")) {
{
format = format.substring(0, 11) + "23:59:59" + format.substring(19); format = format.substring(0, 11) + "23:59:59" + format.substring(19);
} }
return new SolrFilterResult("item.lastmodified:[* TO " return new SolrFilterResult("item.lastmodified:[* TO "
+ ClientUtils.escapeQueryChars(format) + "]"); + ClientUtils.escapeQueryChars(format) + "]");
} }
} }

View File

@@ -22,7 +22,8 @@ public class OrFilter extends DSpaceFilter {
@Override @Override
public SolrFilterResult buildSolrQuery() { public SolrFilterResult buildSolrQuery() {
return new SolrFilterResult("("+left.buildSolrQuery().getQuery()+") OR ("+right.buildSolrQuery().getQuery()+")"); return new SolrFilterResult(
"(" + left.buildSolrQuery().getQuery() + ") OR (" + right.buildSolrQuery().getQuery() + ")");
} }
@Override @Override

View File

@@ -11,35 +11,29 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class SolrFilterResult public class SolrFilterResult {
{ private static Logger log = LogManager.getLogger(SolrFilterResult.class);
private static Logger log = LogManager.getLogger(SolrFilterResult.class);
private String _where; private String _where;
private boolean _nothing; private boolean _nothing;
public SolrFilterResult() public SolrFilterResult() {
{
_nothing = true; _nothing = true;
} }
public SolrFilterResult(String query) public SolrFilterResult(String query) {
{ log.debug("XOAI SolrQuery: " + query);
log.debug("XOAI SolrQuery: "+ query);
_nothing = false; _nothing = false;
_where = query; _where = query;
} }
public boolean hasResult() public boolean hasResult() {
{
return !_nothing; return !_nothing;
} }
public String getQuery() public String getQuery() {
{
return _where; return _where;
} }
} }

View File

@@ -9,7 +9,6 @@
package org.dspace.xoai.filter.data; package org.dspace.xoai.filter.data;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public enum DSpaceMetadataFilterOperator { public enum DSpaceMetadataFilterOperator {

View File

@@ -11,35 +11,29 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class SolrFilterResult public class SolrFilterResult {
{ private static Logger log = LogManager.getLogger(SolrFilterResult.class);
private static Logger log = LogManager.getLogger(SolrFilterResult.class);
private String _where; private String _where;
private boolean _nothing; private boolean _nothing;
public SolrFilterResult() public SolrFilterResult() {
{
_nothing = true; _nothing = true;
} }
public SolrFilterResult(String query) public SolrFilterResult(String query) {
{ log.debug("XOAI SolrQuery: " + query);
log.debug("XOAI SolrQuery: "+ query);
_nothing = false; _nothing = false;
_where = query; _where = query;
} }
public boolean hasResult() public boolean hasResult() {
{
return !_nothing; return !_nothing;
} }
public String getQuery() public String getQuery() {
{
return _where; return _where;
} }
} }

View File

@@ -7,19 +7,22 @@
*/ */
package org.dspace.xoai.services.api; package org.dspace.xoai.services.api;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
import org.dspace.content.Item; import org.dspace.content.Item;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.services.api.context.ContextService; import org.dspace.xoai.services.api.context.ContextService;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
public interface CollectionsService { public interface CollectionsService {
List<UUID> getAllSubCollections(ContextService contextService, UUID communityId) throws SQLException; List<UUID> getAllSubCollections(ContextService contextService, UUID communityId) throws SQLException;
List<Community> flatParentCommunities(Collection collection) throws SQLException; List<Community> flatParentCommunities(Collection collection) throws SQLException;
List<Community> flatParentCommunities(Community community) throws SQLException; List<Community> flatParentCommunities(Community community) throws SQLException;
List<Community> flatParentCommunities(Context context, Item item) throws SQLException; List<Community> flatParentCommunities(Context context, Item item) throws SQLException;
} }

View File

@@ -7,12 +7,12 @@
*/ */
package org.dspace.xoai.services.api; package org.dspace.xoai.services.api;
import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Date; import java.util.Date;
import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
public interface EarliestDateResolver { public interface EarliestDateResolver {
public Date getEarliestDate (Context context) throws InvalidMetadataFieldException, SQLException; public Date getEarliestDate(Context context) throws InvalidMetadataFieldException, SQLException;
} }

View File

@@ -7,11 +7,11 @@
*/ */
package org.dspace.xoai.services.api; package org.dspace.xoai.services.api;
import java.sql.SQLException;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException; import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import java.sql.SQLException;
public interface FieldResolver { public interface FieldResolver {
int getFieldID(Context context, String field) throws InvalidMetadataFieldException, SQLException; int getFieldID(Context context, String field) throws InvalidMetadataFieldException, SQLException;
} }

View File

@@ -10,6 +10,7 @@ package org.dspace.xoai.services.api;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
public interface HandleResolver { public interface HandleResolver {
DSpaceObject resolve (String handle) throws HandleResolverException; DSpaceObject resolve(String handle) throws HandleResolverException;
String getHandle (DSpaceObject object) throws HandleResolverException;
String getHandle(DSpaceObject object) throws HandleResolverException;
} }

View File

@@ -8,5 +8,5 @@
package org.dspace.xoai.services.api; package org.dspace.xoai.services.api;
public interface ServiceResolver { public interface ServiceResolver {
<T> T getService (Class<T> type); <T> T getService(Class<T> type);
} }

View File

@@ -7,17 +7,22 @@
*/ */
package org.dspace.xoai.services.api.cache; package org.dspace.xoai.services.api.cache;
import com.lyncode.xoai.dataprovider.xml.oaipmh.OAIPMH;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import com.lyncode.xoai.dataprovider.xml.oaipmh.OAIPMH;
public interface XOAICacheService { public interface XOAICacheService {
boolean isActive (); boolean isActive();
boolean hasCache (String requestID);
void handle (String requestID, OutputStream out) throws IOException; boolean hasCache(String requestID);
void store (String requestID, OAIPMH response) throws IOException;
void delete (String requestID); void handle(String requestID, OutputStream out) throws IOException;
void deleteAll () throws IOException;
void store(String requestID, OAIPMH response) throws IOException;
void delete(String requestID);
void deleteAll() throws IOException;
} }

View File

@@ -7,16 +7,20 @@
*/ */
package org.dspace.xoai.services.api.cache; package org.dspace.xoai.services.api.cache;
import java.io.IOException;
import com.lyncode.xoai.dataprovider.xml.xoai.Metadata; import com.lyncode.xoai.dataprovider.xml.xoai.Metadata;
import org.dspace.content.Item; import org.dspace.content.Item;
import java.io.IOException;
public interface XOAIItemCacheService { public interface XOAIItemCacheService {
boolean hasCache (Item item); boolean hasCache(Item item);
Metadata get (Item item) throws IOException;
void put (Item item, Metadata metadata) throws IOException; Metadata get(Item item) throws IOException;
void delete (Item item);
void put(Item item, Metadata metadata) throws IOException;
void delete(Item item);
void deleteAll() throws IOException; void deleteAll() throws IOException;
} }

View File

@@ -12,7 +12,9 @@ import java.util.Date;
public interface XOAILastCompilationCacheService { public interface XOAILastCompilationCacheService {
boolean hasCache (); boolean hasCache();
void put (Date date) throws IOException;
Date get () throws IOException; void put(Date date) throws IOException;
Date get() throws IOException;
} }

View File

@@ -8,7 +8,9 @@
package org.dspace.xoai.services.api.config; package org.dspace.xoai.services.api.config;
public interface ConfigurationService { public interface ConfigurationService {
String getProperty (String key); String getProperty(String key);
String getProperty (String module, String key);
String getProperty(String module, String key);
boolean getBooleanProperty(String module, String key, boolean defaultValue); boolean getBooleanProperty(String module, String key, boolean defaultValue);
} }

View File

@@ -10,5 +10,5 @@ package org.dspace.xoai.services.api.config;
import com.lyncode.xoai.dataprovider.core.XOAIManager; import com.lyncode.xoai.dataprovider.core.XOAIManager;
public interface XOAIManagerResolver { public interface XOAIManagerResolver {
XOAIManager getManager () throws XOAIManagerResolverException; XOAIManager getManager() throws XOAIManagerResolverException;
} }

View File

@@ -8,7 +8,8 @@
package org.dspace.xoai.services.api.config; package org.dspace.xoai.services.api.config;
public class XOAIManagerResolverException extends Exception { public class XOAIManagerResolverException extends Exception {
public XOAIManagerResolverException() {} public XOAIManagerResolverException() {
}
public XOAIManagerResolverException(String message) { public XOAIManagerResolverException(String message) {
super(message); super(message);

View File

@@ -14,7 +14,9 @@ import org.dspace.content.DSpaceObject;
import org.dspace.xoai.exceptions.InvalidSetSpecException; import org.dspace.xoai.exceptions.InvalidSetSpecException;
public interface SetSpecResolver { public interface SetSpecResolver {
String toSetSpec (Community community) throws InvalidSetSpecException; String toSetSpec(Community community) throws InvalidSetSpecException;
String toSetSpec (Collection collection) throws InvalidSetSpecException;
DSpaceObject fromSetSpec (String setSpec) throws InvalidSetSpecException; String toSetSpec(Collection collection) throws InvalidSetSpecException;
DSpaceObject fromSetSpec(String setSpec) throws InvalidSetSpecException;
} }

View File

@@ -7,10 +7,10 @@
*/ */
package org.dspace.xoai.services.api.solr; package org.dspace.xoai.services.api.solr;
import com.lyncode.xoai.dataprovider.filter.ScopedFilter;
import java.util.List; import java.util.List;
import com.lyncode.xoai.dataprovider.filter.ScopedFilter;
public interface SolrQueryResolver { public interface SolrQueryResolver {
String buildQuery (List<ScopedFilter> filters); String buildQuery(List<ScopedFilter> filters);
} }

View File

@@ -11,5 +11,5 @@ import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.SolrServerException;
public interface SolrServerResolver { public interface SolrServerResolver {
SolrServer getServer () throws SolrServerException; SolrServer getServer() throws SolrServerException;
} }

View File

@@ -7,7 +7,6 @@
*/ */
package org.dspace.xoai.services.api.xoai; package org.dspace.xoai.services.api.xoai;
import com.lyncode.xoai.dataprovider.filter.Scope; import com.lyncode.xoai.dataprovider.filter.Scope;
import com.lyncode.xoai.dataprovider.filter.conditions.Condition; import com.lyncode.xoai.dataprovider.filter.conditions.Condition;
import com.lyncode.xoai.dataprovider.services.api.FilterResolver; import com.lyncode.xoai.dataprovider.services.api.FilterResolver;

View File

@@ -11,5 +11,5 @@ import com.lyncode.xoai.dataprovider.services.api.ItemRepository;
import org.dspace.xoai.services.api.context.ContextServiceException; import org.dspace.xoai.services.api.context.ContextServiceException;
public interface ItemRepositoryResolver { public interface ItemRepositoryResolver {
ItemRepository getItemRepository () throws ContextServiceException; ItemRepository getItemRepository() throws ContextServiceException;
} }

View File

@@ -11,5 +11,5 @@ import com.lyncode.xoai.dataprovider.services.api.SetRepository;
import org.dspace.xoai.services.api.context.ContextServiceException; import org.dspace.xoai.services.api.context.ContextServiceException;
public interface SetRepositoryResolver { public interface SetRepositoryResolver {
SetRepository getSetRepository () throws ContextServiceException; SetRepository getSetRepository() throws ContextServiceException;
} }

View File

@@ -7,32 +7,31 @@
*/ */
package org.dspace.xoai.services.impl; package org.dspace.xoai.services.impl;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException;
import org.dspace.xoai.services.api.CollectionsService;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Queue; import java.util.Queue;
import java.util.UUID; import java.util.UUID;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.core.Context;
import org.dspace.xoai.services.api.CollectionsService;
import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException;
public class DSpaceCollectionsService implements CollectionsService { public class DSpaceCollectionsService implements CollectionsService {
private static final CommunityService communityService private static final CommunityService communityService
= ContentServiceFactory.getInstance().getCommunityService(); = ContentServiceFactory.getInstance().getCommunityService();
@Override @Override
public List<UUID> getAllSubCollections(ContextService contextService, UUID communityId) public List<UUID> getAllSubCollections(ContextService contextService, UUID communityId)
throws SQLException throws SQLException {
{
Queue<Community> comqueue = new LinkedList<>(); Queue<Community> comqueue = new LinkedList<>();
List<UUID> list = new ArrayList<>(); List<UUID> list = new ArrayList<>();
try { try {
@@ -40,35 +39,38 @@ public class DSpaceCollectionsService implements CollectionsService {
} catch (ContextServiceException e) { } catch (ContextServiceException e) {
throw new SQLException(e); throw new SQLException(e);
} }
while (!comqueue.isEmpty()) while (!comqueue.isEmpty()) {
{
Community c = comqueue.poll(); Community c = comqueue.poll();
for (Community sub : c.getSubcommunities()) for (Community sub : c.getSubcommunities()) {
comqueue.add(sub); comqueue.add(sub);
for (Collection col : c.getCollections()) }
if (!list.contains(col.getID())) for (Collection col : c.getCollections()) {
if (!list.contains(col.getID())) {
list.add(col.getID()); list.add(col.getID());
}
}
} }
return list; return list;
} }
@Override @Override
public List<Community> flatParentCommunities(Collection c) public List<Community> flatParentCommunities(Collection c)
throws SQLException throws SQLException {
{
Queue<Community> queue = new LinkedList<>(); Queue<Community> queue = new LinkedList<>();
List<Community> result = new ArrayList<>(); List<Community> result = new ArrayList<>();
for (Community com : c.getCommunities()) for (Community com : c.getCommunities()) {
queue.add(com); queue.add(com);
}
while (!queue.isEmpty()) while (!queue.isEmpty()) {
{
Community p = queue.poll(); Community p = queue.poll();
List<Community> par = p.getParentCommunities(); List<Community> par = p.getParentCommunities();
if (par != null) if (par != null) {
queue.addAll(par); queue.addAll(par);
if (!result.contains(p)) }
if (!result.contains(p)) {
result.add(p); result.add(p);
}
} }
return result; return result;
@@ -76,21 +78,21 @@ public class DSpaceCollectionsService implements CollectionsService {
@Override @Override
public List<Community> flatParentCommunities(Community c) public List<Community> flatParentCommunities(Community c)
throws SQLException throws SQLException {
{
Queue<Community> queue = new LinkedList<>(); Queue<Community> queue = new LinkedList<>();
List<Community> result = new ArrayList<>(); List<Community> result = new ArrayList<>();
queue.add(c); queue.add(c);
while (!queue.isEmpty()) while (!queue.isEmpty()) {
{
Community p = queue.poll(); Community p = queue.poll();
List<Community> par = p.getParentCommunities(); List<Community> par = p.getParentCommunities();
if (par != null) if (par != null) {
queue.addAll(par); queue.addAll(par);
if (!result.contains(p)) }
if (!result.contains(p)) {
result.add(p); result.add(p);
}
} }
return result; return result;
@@ -98,22 +100,23 @@ public class DSpaceCollectionsService implements CollectionsService {
@Override @Override
public List<Community> flatParentCommunities(Context context, Item c) public List<Community> flatParentCommunities(Context context, Item c)
throws SQLException throws SQLException {
{
Queue<Community> queue = new LinkedList<>(); Queue<Community> queue = new LinkedList<>();
List<Community> result = new ArrayList<>(); List<Community> result = new ArrayList<>();
for (Collection collection : c.getCollections()) for (Collection collection : c.getCollections()) {
queue.addAll(communityService.getAllParents(context, collection)); queue.addAll(communityService.getAllParents(context, collection));
}
while (!queue.isEmpty()) while (!queue.isEmpty()) {
{
Community p = queue.poll(); Community p = queue.poll();
List<Community> par = p.getParentCommunities(); List<Community> par = p.getParentCommunities();
if (par != null) if (par != null) {
queue.addAll(par); queue.addAll(par);
if (!result.contains(p)) }
if (!result.contains(p)) {
result.add(p); result.add(p);
}
} }
return result; return result;

View File

@@ -7,8 +7,14 @@
*/ */
package org.dspace.xoai.services.impl; package org.dspace.xoai.services.impl;
import java.sql.SQLException;
import java.util.Date;
import org.apache.log4j.LogManager; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.MetadataValueService;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException; import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import org.dspace.xoai.services.api.EarliestDateResolver; import org.dspace.xoai.services.api.EarliestDateResolver;
@@ -16,12 +22,6 @@ import org.dspace.xoai.services.api.FieldResolver;
import org.dspace.xoai.util.DateUtils; import org.dspace.xoai.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.sql.SQLException;
import java.util.Date;
import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.MetadataValueService;
public class DSpaceEarliestDateResolver implements EarliestDateResolver { public class DSpaceEarliestDateResolver implements EarliestDateResolver {
private static final Logger log = LogManager.getLogger(DSpaceEarliestDateResolver.class); private static final Logger log = LogManager.getLogger(DSpaceEarliestDateResolver.class);
@@ -34,17 +34,15 @@ public class DSpaceEarliestDateResolver implements EarliestDateResolver {
MetadataValueService metadataValueService = ContentServiceFactory.getInstance().getMetadataValueService(); MetadataValueService metadataValueService = ContentServiceFactory.getInstance().getMetadataValueService();
MetadataValue minimum = metadataValueService.getMinimum(context, MetadataValue minimum = metadataValueService.getMinimum(context,
fieldResolver.getFieldID(context, "dc.date.available")); fieldResolver.getFieldID(context, "dc.date.available"));
if (null != minimum) if (null != minimum) {
{
String str = minimum.getValue(); String str = minimum.getValue();
try try {
{
Date d = DateUtils.parse(str); Date d = DateUtils.parse(str);
if (d != null) return d; if (d != null) {
} return d;
catch (Exception e) }
{ } catch (Exception e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }

View File

@@ -7,6 +7,9 @@
*/ */
package org.dspace.xoai.services.impl; package org.dspace.xoai.services.impl;
import java.sql.SQLException;
import java.util.regex.Pattern;
import org.dspace.content.MetadataField; import org.dspace.content.MetadataField;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.MetadataFieldService; import org.dspace.content.service.MetadataFieldService;
@@ -14,41 +17,37 @@ import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException; import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import org.dspace.xoai.services.api.FieldResolver; import org.dspace.xoai.services.api.FieldResolver;
import java.sql.SQLException;
import java.util.regex.Pattern;
public class DSpaceFieldResolver implements FieldResolver { public class DSpaceFieldResolver implements FieldResolver {
private MetadataFieldCache metadataFieldCache = null; private MetadataFieldCache metadataFieldCache = null;
private static final MetadataFieldService metadataFieldService private static final MetadataFieldService metadataFieldService
= ContentServiceFactory.getInstance().getMetadataFieldService(); = ContentServiceFactory.getInstance().getMetadataFieldService();
@Override @Override
public int getFieldID(Context context, String field) throws InvalidMetadataFieldException, SQLException { public int getFieldID(Context context, String field) throws InvalidMetadataFieldException, SQLException {
if (metadataFieldCache == null) if (metadataFieldCache == null) {
metadataFieldCache = new MetadataFieldCache(); metadataFieldCache = new MetadataFieldCache();
if (!metadataFieldCache.hasField(field)) }
{ if (!metadataFieldCache.hasField(field)) {
String[] pieces = field.split(Pattern.quote(".")); String[] pieces = field.split(Pattern.quote("."));
if (pieces.length > 1) if (pieces.length > 1) {
{
String schema = pieces[0]; String schema = pieces[0];
String element = pieces[1]; String element = pieces[1];
String qualifier = null; String qualifier = null;
if (pieces.length > 2) if (pieces.length > 2) {
qualifier = pieces[2]; qualifier = pieces[2];
}
MetadataField metadataField = metadataFieldService.findByElement(context, schema, element, qualifier); MetadataField metadataField = metadataFieldService.findByElement(context, schema, element, qualifier);
if (null != metadataField) if (null != metadataField) {
{
metadataFieldCache.add(field, metadataField.getID()); metadataFieldCache.add(field, metadataField.getID());
} } else {
else
throw new InvalidMetadataFieldException(); throw new InvalidMetadataFieldException();
}
} } else {
else
throw new InvalidMetadataFieldException(); throw new InvalidMetadataFieldException();
}
} }
return metadataFieldCache.getField(field); return metadataFieldCache.getField(field);
} }

View File

@@ -9,13 +9,14 @@ package org.dspace.xoai.services.impl;
import java.sql.SQLException; import java.sql.SQLException;
import javax.inject.Inject; import javax.inject.Inject;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException;
import org.dspace.xoai.services.api.HandleResolver; import org.dspace.xoai.services.api.HandleResolver;
import org.dspace.xoai.services.api.HandleResolverException; import org.dspace.xoai.services.api.HandleResolverException;
import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException;
public class DSpaceHandleResolver implements HandleResolver { public class DSpaceHandleResolver implements HandleResolver {
@Inject @Inject
@@ -23,8 +24,7 @@ public class DSpaceHandleResolver implements HandleResolver {
private final HandleService handleService; private final HandleService handleService;
public DSpaceHandleResolver() public DSpaceHandleResolver() {
{
handleService = HandleServiceFactory.getInstance().getHandleService(); handleService = HandleServiceFactory.getInstance().getHandleService();
} }

View File

@@ -7,6 +7,8 @@
*/ */
package org.dspace.xoai.services.impl; package org.dspace.xoai.services.impl;
import java.util.Map;
import com.lyncode.builder.MapBuilder; import com.lyncode.builder.MapBuilder;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver; import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import org.dspace.xoai.services.api.ServiceResolver; import org.dspace.xoai.services.api.ServiceResolver;
@@ -14,13 +16,11 @@ import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.impl.config.DSpaceConfigurationService; import org.dspace.xoai.services.impl.config.DSpaceConfigurationService;
import org.dspace.xoai.services.impl.resources.DSpaceResourceResolver; import org.dspace.xoai.services.impl.resources.DSpaceResourceResolver;
import java.util.Map;
public class DSpaceServiceResolver implements ServiceResolver { public class DSpaceServiceResolver implements ServiceResolver {
private Map<String, Object> services = new MapBuilder<String, Object>() private Map<String, Object> services = new MapBuilder<String, Object>()
.withPair(ConfigurationService.class.getName(), new DSpaceConfigurationService()) .withPair(ConfigurationService.class.getName(), new DSpaceConfigurationService())
.withPair(ResourceResolver.class.getName(), new DSpaceResourceResolver()) .withPair(ResourceResolver.class.getName(), new DSpaceResourceResolver())
.build(); .build();
@Override @Override
public <T> T getService(Class<T> type) { public <T> T getService(Class<T> type) {

View File

@@ -7,40 +7,34 @@
*/ */
package org.dspace.xoai.services.impl; package org.dspace.xoai.services.impl;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class MetadataFieldCache public class MetadataFieldCache {
{
private static Logger log = LogManager private static Logger log = LogManager
.getLogger(MetadataFieldCache.class); .getLogger(MetadataFieldCache.class);
private Map<String, Integer> fields; private Map<String, Integer> fields;
public MetadataFieldCache() public MetadataFieldCache() {
{
fields = new HashMap<String, Integer>(); fields = new HashMap<String, Integer>();
} }
public boolean hasField(String field) public boolean hasField(String field) {
{
return fields.containsKey(field); return fields.containsKey(field);
} }
public int getField(String field) public int getField(String field) {
{
return fields.get(field).intValue(); return fields.get(field).intValue();
} }
public void add(String field, int id) public void add(String field, int id) {
{
fields.put(field, new Integer(id)); fields.put(field, new Integer(id));
} }
} }

View File

@@ -7,12 +7,12 @@
*/ */
package org.dspace.xoai.services.impl.cache; package org.dspace.xoai.services.impl.cache;
import com.lyncode.xoai.dataprovider.xml.oaipmh.OAIPMH;
import org.dspace.xoai.services.api.cache.XOAICacheService;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import com.lyncode.xoai.dataprovider.xml.oaipmh.OAIPMH;
import org.dspace.xoai.services.api.cache.XOAICacheService;
public class DSpaceEmptyCacheService implements XOAICacheService { public class DSpaceEmptyCacheService implements XOAICacheService {
@Override @Override
public boolean isActive() { public boolean isActive() {

View File

@@ -7,6 +7,20 @@
*/ */
package org.dspace.xoai.services.impl.cache; package org.dspace.xoai.services.impl.cache;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.apache.commons.io.IOUtils.copy;
import static org.apache.commons.io.IOUtils.write;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import javax.xml.stream.XMLStreamException;
import com.lyncode.xoai.dataprovider.core.XOAIManager; import com.lyncode.xoai.dataprovider.core.XOAIManager;
import com.lyncode.xoai.dataprovider.exceptions.WritingXmlException; import com.lyncode.xoai.dataprovider.exceptions.WritingXmlException;
import com.lyncode.xoai.dataprovider.xml.XmlOutputContext; import com.lyncode.xoai.dataprovider.xml.XmlOutputContext;
@@ -19,15 +33,6 @@ import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.util.DateUtils; import org.dspace.xoai.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import javax.xml.stream.XMLStreamException;
import java.io.*;
import java.util.Date;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.apache.commons.io.IOUtils.copy;
import static org.apache.commons.io.IOUtils.write;
public class DSpaceXOAICacheService implements XOAICacheService { public class DSpaceXOAICacheService implements XOAICacheService {
private static final String REQUEST_DIR = File.separator + "requests"; private static final String REQUEST_DIR = File.separator + "requests";
@@ -43,12 +48,15 @@ public class DSpaceXOAICacheService implements XOAICacheService {
} }
private static String getStaticHead(XOAIManager manager, Date date) { private static String getStaticHead(XOAIManager manager, Date date) {
if (staticHead == null) if (staticHead == null) {
staticHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" staticHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ ((manager.hasStyleSheet()) ? ("<?xml-stylesheet type=\"text/xsl\" href=\"" + ((manager.hasStyleSheet()) ? ("<?xml-stylesheet type=\"text/xsl\" href=\""
+ manager.getStyleSheet() + "\"?>") : "") + manager.getStyleSheet() + "\"?>") : "")
+ "<OAI-PMH xmlns=\"http://www.openarchives.org/OAI/2.0/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "<OAI-PMH xmlns=\"http://www.openarchives.org/OAI/2.0/\" xmlns:xsi=\"http://www" +
+ "xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd\">"; ".w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/ http://www.openarchives" +
".org/OAI/2.0/OAI-PMH.xsd\">";
}
return staticHead + "<responseDate>" + DateUtils.format(date) + "</responseDate>"; return staticHead + "<responseDate>" + DateUtils.format(date) + "</responseDate>";
} }
@@ -64,8 +72,9 @@ public class DSpaceXOAICacheService implements XOAICacheService {
private File getCacheFile(String id) { private File getCacheFile(String id) {
File dir = new File(getBaseDir()); File dir = new File(getBaseDir());
if (!dir.exists()) if (!dir.exists()) {
dir.mkdirs(); dir.mkdirs();
}
String name = File.separator + Base64Utils.encode(id); String name = File.separator + Base64Utils.encode(id);
return new File(getBaseDir() + name); return new File(getBaseDir() + name);
@@ -103,8 +112,9 @@ public class DSpaceXOAICacheService implements XOAICacheService {
// Cutting the header (to allow one to change the response time) // Cutting the header (to allow one to change the response time)
String end = "</responseDate>"; String end = "</responseDate>";
int pos = xoaiResponse.indexOf(end); int pos = xoaiResponse.indexOf(end);
if (pos > 0) if (pos > 0) {
xoaiResponse = xoaiResponse.substring(pos + (end.length())); xoaiResponse = xoaiResponse.substring(pos + (end.length()));
}
FileUtils.write(this.getCacheFile(requestID), xoaiResponse); FileUtils.write(this.getCacheFile(requestID), xoaiResponse);
} catch (XMLStreamException e) { } catch (XMLStreamException e) {

View File

@@ -7,6 +7,15 @@
*/ */
package org.dspace.xoai.services.impl.cache; package org.dspace.xoai.services.impl.cache;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.stream.XMLStreamException;
import com.lyncode.xoai.dataprovider.exceptions.WritingXmlException; import com.lyncode.xoai.dataprovider.exceptions.WritingXmlException;
import com.lyncode.xoai.dataprovider.xml.XmlOutputContext; import com.lyncode.xoai.dataprovider.xml.XmlOutputContext;
import com.lyncode.xoai.dataprovider.xml.xoai.Metadata; import com.lyncode.xoai.dataprovider.xml.xoai.Metadata;
@@ -17,15 +26,6 @@ import org.dspace.xoai.services.api.cache.XOAIItemCacheService;
import org.dspace.xoai.services.api.config.ConfigurationService; import org.dspace.xoai.services.api.config.ConfigurationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
import static org.apache.commons.io.FileUtils.deleteDirectory;
public class DSpaceXOAIItemCacheService implements XOAIItemCacheService { public class DSpaceXOAIItemCacheService implements XOAIItemCacheService {
private static final String ITEMDIR = File.separator + "items"; private static final String ITEMDIR = File.separator + "items";
@@ -35,36 +35,31 @@ public class DSpaceXOAIItemCacheService implements XOAIItemCacheService {
private String baseDir; private String baseDir;
private String getBaseDir() private String getBaseDir() {
{ if (baseDir == null) {
if (baseDir == null)
baseDir = configurationService.getProperty("oai", "cache.dir") + ITEMDIR; baseDir = configurationService.getProperty("oai", "cache.dir") + ITEMDIR;
}
return baseDir; return baseDir;
} }
private File getMetadataCache(Item item) private File getMetadataCache(Item item) {
{
File dir = new File(getBaseDir()); File dir = new File(getBaseDir());
if (!dir.exists()) if (!dir.exists()) {
dir.mkdirs(); dir.mkdirs();
}
String name = File.separator + item.getHandle().replace('/', '_'); String name = File.separator + item.getHandle().replace('/', '_');
return new File(getBaseDir() + name); return new File(getBaseDir() + name);
} }
@Override @Override
public boolean hasCache(Item item) { public boolean hasCache(Item item) {
return getMetadataCache(item).exists(); return getMetadataCache(item).exists();
} }
@Override @Override
public Metadata get(Item item) throws IOException { public Metadata get(Item item) throws IOException {
System.out.println(FileUtils.readFileToString(getMetadataCache(item))); System.out.println(FileUtils.readFileToString(getMetadataCache(item)));
@@ -76,14 +71,11 @@ public class DSpaceXOAIItemCacheService implements XOAIItemCacheService {
throw new IOException(e); throw new IOException(e);
} }
input.close(); input.close();
return metadata; return metadata;
} }
@Override @Override
public void put(Item item, Metadata metadata) throws IOException { public void put(Item item, Metadata metadata) throws IOException {
FileOutputStream output = new FileOutputStream(getMetadataCache(item)); FileOutputStream output = new FileOutputStream(getMetadataCache(item));
@@ -92,7 +84,7 @@ public class DSpaceXOAIItemCacheService implements XOAIItemCacheService {
metadata.write(context); metadata.write(context);
context.getWriter().flush(); context.getWriter().flush();
context.getWriter().close(); context.getWriter().close();
output.close(); output.close();
} catch (XMLStreamException e) { } catch (XMLStreamException e) {
throw new IOException(e); throw new IOException(e);

View File

@@ -7,10 +7,6 @@
*/ */
package org.dspace.xoai.services.impl.cache; package org.dspace.xoai.services.impl.cache;
import org.apache.commons.io.FileUtils;
import org.dspace.core.ConfigurationManager;
import org.dspace.xoai.services.api.cache.XOAILastCompilationCacheService;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.text.DateFormat; import java.text.DateFormat;
@@ -18,23 +14,25 @@ import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.dspace.core.ConfigurationManager;
import org.dspace.xoai.services.api.cache.XOAILastCompilationCacheService;
public class DSpaceXOAILastCompilationCacheService implements XOAILastCompilationCacheService { public class DSpaceXOAILastCompilationCacheService implements XOAILastCompilationCacheService {
private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>(){ private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() {
@Override @Override
protected DateFormat initialValue() { protected DateFormat initialValue() {
return new SimpleDateFormat(); return new SimpleDateFormat();
} }
}; };
private static final String DATEFILE = File.separator + "date.file"; private static final String DATEFILE = File.separator + "date.file";
private static File file = null; private static File file = null;
private static File getFile() private static File getFile() {
{ if (file == null) {
if (file == null)
{
String dir = ConfigurationManager.getProperty("oai", "cache.dir") + DATEFILE; String dir = ConfigurationManager.getProperty("oai", "cache.dir") + DATEFILE;
file = new File(dir); file = new File(dir);
} }
@@ -48,18 +46,12 @@ public class DSpaceXOAILastCompilationCacheService implements XOAILastCompilatio
} }
@Override @Override
public void put(Date date) throws IOException { public void put(Date date) throws IOException {
FileUtils.write(getFile(), format.get().format(date)); FileUtils.write(getFile(), format.get().format(date));
} }
@Override @Override
public Date get() throws IOException { public Date get() throws IOException {
try { try {

View File

@@ -17,7 +17,7 @@ public class DSpaceConfigurationService implements ConfigurationService {
} }
@Override @Override
public String getProperty(String module, String key) { public String getProperty(String module, String key) {
return ConfigurationManager.getProperty(module, key); return ConfigurationManager.getProperty(module, key);
} }

View File

@@ -7,20 +7,21 @@
*/ */
package org.dspace.xoai.services.impl.context; package org.dspace.xoai.services.impl.context;
import javax.servlet.http.HttpServletRequest;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.services.api.context.ContextService; import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException; import org.dspace.xoai.services.api.context.ContextServiceException;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class DSpaceContextService implements ContextService { public class DSpaceContextService implements ContextService {
private static final String OAI_CONTEXT = "OAI_CONTEXT"; private static final String OAI_CONTEXT = "OAI_CONTEXT";
@Override @Override
public Context getContext() throws ContextServiceException { public Context getContext() throws ContextServiceException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Object value = request.getAttribute(OAI_CONTEXT); Object value = request.getAttribute(OAI_CONTEXT);
if (value == null || !(value instanceof Context)) { if (value == null || !(value instanceof Context)) {
request.setAttribute(OAI_CONTEXT, new Context()); request.setAttribute(OAI_CONTEXT, new Context());

View File

@@ -7,6 +7,8 @@
*/ */
package org.dspace.xoai.services.impl.context; package org.dspace.xoai.services.impl.context;
import static com.lyncode.xoai.dataprovider.xml.xoaiconfig.Configuration.readConfiguration;
import com.lyncode.xoai.dataprovider.core.XOAIManager; import com.lyncode.xoai.dataprovider.core.XOAIManager;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver; import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import org.dspace.xoai.services.api.config.XOAIManagerResolver; import org.dspace.xoai.services.api.config.XOAIManagerResolver;
@@ -14,12 +16,12 @@ import org.dspace.xoai.services.api.config.XOAIManagerResolverException;
import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver; import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import static com.lyncode.xoai.dataprovider.xml.xoaiconfig.Configuration.readConfiguration;
public class DSpaceXOAIManagerResolver implements XOAIManagerResolver { public class DSpaceXOAIManagerResolver implements XOAIManagerResolver {
public static final String XOAI_CONFIGURATION_FILE = "xoai.xml"; public static final String XOAI_CONFIGURATION_FILE = "xoai.xml";
@Autowired ResourceResolver resourceResolver; @Autowired
@Autowired DSpaceFilterResolver filterResolver; ResourceResolver resourceResolver;
@Autowired
DSpaceFilterResolver filterResolver;
private XOAIManager manager; private XOAIManager manager;
@@ -27,7 +29,8 @@ public class DSpaceXOAIManagerResolver implements XOAIManagerResolver {
public XOAIManager getManager() throws XOAIManagerResolverException { public XOAIManager getManager() throws XOAIManagerResolverException {
if (manager == null) { if (manager == null) {
try { try {
manager = new XOAIManager(filterResolver, resourceResolver, readConfiguration(resourceResolver.getResource(XOAI_CONFIGURATION_FILE))); manager = new XOAIManager(filterResolver, resourceResolver,
readConfiguration(resourceResolver.getResource(XOAI_CONFIGURATION_FILE)));
} catch (Exception e) { } catch (Exception e) {
throw new XOAIManagerResolverException(e); throw new XOAIManagerResolverException(e);
} }

View File

@@ -11,35 +11,30 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver; public class DSpaceResourceResolver implements ResourceResolver {
public class DSpaceResourceResolver implements ResourceResolver
{
private static final TransformerFactory transformerFactory = TransformerFactory private static final TransformerFactory transformerFactory = TransformerFactory
.newInstance(); .newInstance();
private final String basePath = ConfigurationManager.getProperty("oai", private final String basePath = ConfigurationManager.getProperty("oai",
"config.dir"); "config.dir");
@Override @Override
public InputStream getResource(String path) throws IOException public InputStream getResource(String path) throws IOException {
{
return new FileInputStream(new File(basePath, path)); return new FileInputStream(new File(basePath, path));
} }
@Override @Override
public Transformer getTransformer(String path) throws IOException, public Transformer getTransformer(String path) throws IOException,
TransformerConfigurationException TransformerConfigurationException {
{
// construct a Source that reads from an InputStream // construct a Source that reads from an InputStream
Source mySrc = new StreamSource(getResource(path)); Source mySrc = new StreamSource(getResource(path));
// specify a system ID (the path to the XSLT-file on the filesystem) // specify a system ID (the path to the XSLT-file on the filesystem)

View File

@@ -8,20 +8,20 @@
package org.dspace.xoai.services.impl.set; package org.dspace.xoai.services.impl.set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.xoai.exceptions.InvalidSetSpecException; import org.dspace.xoai.exceptions.InvalidSetSpecException;
import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.HandleResolver; import org.dspace.xoai.services.api.HandleResolver;
import org.dspace.xoai.services.api.HandleResolverException; import org.dspace.xoai.services.api.HandleResolverException;
import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.set.SetSpecResolver; import org.dspace.xoai.services.api.set.SetSpecResolver;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DSpaceSetSpecResolver implements SetSpecResolver { public class DSpaceSetSpecResolver implements SetSpecResolver {
private static final String HANDLE_PREFIX = "{handle-prefix}"; private static final String HANDLE_PREFIX = "{handle-prefix}";
private static final String LOCAL_ID = "{local-id}"; private static final String LOCAL_ID = "{local-id}";
@@ -40,7 +40,9 @@ public class DSpaceSetSpecResolver implements SetSpecResolver {
public String toSetSpec(Community community) throws InvalidSetSpecException { public String toSetSpec(Community community) throws InvalidSetSpecException {
String handle = community.getHandle(); String handle = community.getHandle();
String[] split = handle.split("/"); String[] split = handle.split("/");
if (split.length != 2) throw new InvalidSetSpecException("Invalid handle "+handle); if (split.length != 2) {
throw new InvalidSetSpecException("Invalid handle " + handle);
}
return format(getSetSpecFormat(Community.class), split[0], split[1]); return format(getSetSpecFormat(Community.class), split[0], split[1]);
} }
@@ -49,7 +51,9 @@ public class DSpaceSetSpecResolver implements SetSpecResolver {
public String toSetSpec(Collection collection) throws InvalidSetSpecException { public String toSetSpec(Collection collection) throws InvalidSetSpecException {
String handle = collection.getHandle(); String handle = collection.getHandle();
String[] split = handle.split("/"); String[] split = handle.split("/");
if (split.length != 2) throw new InvalidSetSpecException("Invalid handle "+handle); if (split.length != 2) {
throw new InvalidSetSpecException("Invalid handle " + handle);
}
return String.format(getSetSpecFormat(Community.class), split[0], split[1]); return String.format(getSetSpecFormat(Community.class), split[0], split[1]);
} }
@@ -59,12 +63,13 @@ public class DSpaceSetSpecResolver implements SetSpecResolver {
String communityPattern = getPattern(Community.class); String communityPattern = getPattern(Community.class);
String collectionPattern = getPattern(Collection.class); String collectionPattern = getPattern(Collection.class);
String pattern; String pattern;
if (setSpec.matches(communityPattern)) if (setSpec.matches(communityPattern)) {
pattern = communityPattern; pattern = communityPattern;
else if (setSpec.matches(collectionPattern)) } else if (setSpec.matches(collectionPattern)) {
pattern = collectionPattern; pattern = collectionPattern;
else } else {
throw new InvalidSetSpecException("Unknown set spec"); throw new InvalidSetSpecException("Unknown set spec");
}
Matcher matcher = Pattern.compile(pattern).matcher(setSpec); Matcher matcher = Pattern.compile(pattern).matcher(setSpec);
@@ -83,11 +88,12 @@ public class DSpaceSetSpecResolver implements SetSpecResolver {
} }
private String getPattern(Class<?> clazz) { private String getPattern(Class<?> clazz) {
return "^"+getSetSpecFormat(clazz).replace(HANDLE_PREFIX, "([0-9]+)").replace(LOCAL_ID, "([0-9]+)")+"$"; return "^" + getSetSpecFormat(clazz).replace(HANDLE_PREFIX, "([0-9]+)").replace(LOCAL_ID, "([0-9]+)") + "$";
} }
private String getSetSpecFormat(Class<?> clazz) { private String getSetSpecFormat(Class<?> clazz) {
String property = configurationService.getProperty("oai", clazz.getSimpleName().toLowerCase() + ".setSpecFormat"); String property = configurationService
.getProperty("oai", clazz.getSimpleName().toLowerCase() + ".setSpecFormat");
return property == null ? DEFAULT_FORMAT : property; return property == null ? DEFAULT_FORMAT : property;
} }
} }

View File

@@ -7,6 +7,9 @@
*/ */
package org.dspace.xoai.services.impl.solr; package org.dspace.xoai.services.impl.solr;
import java.util.ArrayList;
import java.util.List;
import com.lyncode.xoai.dataprovider.filter.Scope; import com.lyncode.xoai.dataprovider.filter.Scope;
import com.lyncode.xoai.dataprovider.filter.ScopedFilter; import com.lyncode.xoai.dataprovider.filter.ScopedFilter;
import com.lyncode.xoai.dataprovider.filter.conditions.Condition; import com.lyncode.xoai.dataprovider.filter.conditions.Condition;
@@ -15,9 +18,6 @@ import org.dspace.xoai.services.api.solr.SolrQueryResolver;
import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver; import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
public class DSpaceSolrQueryResolver implements SolrQueryResolver { public class DSpaceSolrQueryResolver implements SolrQueryResolver {
@Autowired @Autowired
DSpaceFilterResolver filterResolver; DSpaceFilterResolver filterResolver;
@@ -25,18 +25,20 @@ public class DSpaceSolrQueryResolver implements SolrQueryResolver {
@Override @Override
public String buildQuery(List<ScopedFilter> filters) { public String buildQuery(List<ScopedFilter> filters) {
List<String> whereCond = new ArrayList<String>(); List<String> whereCond = new ArrayList<String>();
for (ScopedFilter filter : filters) for (ScopedFilter filter : filters) {
whereCond.add(buildQuery(filter.getScope(), filter.getCondition())); whereCond.add(buildQuery(filter.getScope(), filter.getCondition()));
}
if (whereCond.isEmpty()) if (whereCond.isEmpty()) {
whereCond.add("*:*"); whereCond.add("*:*");
}
String where = "(" + StringUtils.join(whereCond.iterator(), ") AND (") + ")"; String where = "(" + StringUtils.join(whereCond.iterator(), ") AND (") + ")";
return where; return where;
} }
private String buildQuery (Scope scope, Condition condition) { private String buildQuery(Scope scope, Condition condition) {
return filterResolver.buildSolrQuery(scope, condition); return filterResolver.buildSolrQuery(scope, condition);
} }
} }

View File

@@ -24,17 +24,12 @@ public class DSpaceSolrServerResolver implements SolrServerResolver {
private ConfigurationService configurationService; private ConfigurationService configurationService;
@Override @Override
public SolrServer getServer() throws SolrServerException public SolrServer getServer() throws SolrServerException {
{ if (server == null) {
if (server == null) try {
{
try
{
server = new HttpSolrServer(configurationService.getProperty("oai", "solr.url")); server = new HttpSolrServer(configurationService.getProperty("oai", "solr.url"));
log.debug("Solr Server Initialized"); log.debug("Solr Server Initialized");
} } catch (Exception e) {
catch (Exception e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }

View File

@@ -7,21 +7,28 @@
*/ */
package org.dspace.xoai.services.impl.xoai; package org.dspace.xoai.services.impl.xoai;
import static com.lyncode.xoai.dataprovider.filter.Scope.MetadataFormat;
import com.lyncode.xoai.dataprovider.data.Filter; import com.lyncode.xoai.dataprovider.data.Filter;
import com.lyncode.xoai.dataprovider.filter.Scope; import com.lyncode.xoai.dataprovider.filter.Scope;
import com.lyncode.xoai.dataprovider.filter.conditions.*; import com.lyncode.xoai.dataprovider.filter.conditions.AndCondition;
import com.lyncode.xoai.dataprovider.filter.conditions.Condition;
import com.lyncode.xoai.dataprovider.filter.conditions.CustomCondition;
import com.lyncode.xoai.dataprovider.filter.conditions.NotCondition;
import com.lyncode.xoai.dataprovider.filter.conditions.OrCondition;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterMap; import com.lyncode.xoai.dataprovider.xml.xoaiconfig.parameters.ParameterMap;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.xoai.filter.*; import org.dspace.xoai.filter.AndFilter;
import org.dspace.xoai.filter.DSpaceFilter;
import org.dspace.xoai.filter.NotFilter;
import org.dspace.xoai.filter.OrFilter;
import org.dspace.xoai.filter.results.SolrFilterResult; import org.dspace.xoai.filter.results.SolrFilterResult;
import org.dspace.xoai.services.api.FieldResolver;
import org.dspace.xoai.services.api.context.ContextService; import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException; import org.dspace.xoai.services.api.context.ContextServiceException;
import org.dspace.xoai.services.api.FieldResolver;
import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver; import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import static com.lyncode.xoai.dataprovider.filter.Scope.MetadataFormat;
public class BaseDSpaceFilterResolver implements DSpaceFilterResolver { public class BaseDSpaceFilterResolver implements DSpaceFilterResolver {
private static final Logger LOGGER = Logger.getLogger(BaseDSpaceFilterResolver.class); private static final Logger LOGGER = Logger.getLogger(BaseDSpaceFilterResolver.class);
@@ -31,11 +38,14 @@ public class BaseDSpaceFilterResolver implements DSpaceFilterResolver {
@Autowired @Autowired
ContextService contextService; ContextService contextService;
public DSpaceFilter getFilter (Condition condition) { public DSpaceFilter getFilter(Condition condition) {
if (condition instanceof AndCondition) return (DSpaceFilter) getFilter((AndCondition) condition); if (condition instanceof AndCondition) {
else if (condition instanceof OrCondition) return (DSpaceFilter) getFilter((OrCondition) condition); return (DSpaceFilter) getFilter((AndCondition) condition);
else if (condition instanceof NotCondition) return (DSpaceFilter) getFilter((NotCondition) condition); } else if (condition instanceof OrCondition) {
else if (condition instanceof CustomCondition) { return (DSpaceFilter) getFilter((OrCondition) condition);
} else if (condition instanceof NotCondition) {
return (DSpaceFilter) getFilter((NotCondition) condition);
} else if (condition instanceof CustomCondition) {
CustomCondition customCondition = (CustomCondition) condition; CustomCondition customCondition = (CustomCondition) condition;
return (DSpaceFilter) customCondition.getFilter(); return (DSpaceFilter) customCondition.getFilter();
} else { } else {
@@ -47,13 +57,13 @@ public class BaseDSpaceFilterResolver implements DSpaceFilterResolver {
public String buildSolrQuery(Scope scope, Condition condition) { public String buildSolrQuery(Scope scope, Condition condition) {
DSpaceFilter filter = getFilter(condition); DSpaceFilter filter = getFilter(condition);
SolrFilterResult result = filter.buildSolrQuery(); SolrFilterResult result = filter.buildSolrQuery();
if (result.hasResult()) if (result.hasResult()) {
{ if (scope == MetadataFormat) {
if (scope == MetadataFormat)
return "(item.deleted:true OR (" return "(item.deleted:true OR ("
+ result.getQuery() + "))"; + result.getQuery() + "))";
else } else {
return "(" + result.getQuery() + ")"; return "(" + result.getQuery() + ")";
}
} }
return "true"; return "true";
} }
@@ -61,22 +71,18 @@ public class BaseDSpaceFilterResolver implements DSpaceFilterResolver {
@Override @Override
public Filter getFilter(Class<? extends Filter> filterClass, ParameterMap configuration) { public Filter getFilter(Class<? extends Filter> filterClass, ParameterMap configuration) {
Filter result = null; Filter result = null;
try try {
{
result = filterClass.newInstance(); result = filterClass.newInstance();
if (result instanceof DSpaceFilter) if (result instanceof DSpaceFilter) {
{
// add the DSpace filter specific objects // add the DSpace filter specific objects
((DSpaceFilter) result).setConfiguration(configuration); ((DSpaceFilter) result).setConfiguration(configuration);
((DSpaceFilter) result).setContext(contextService.getContext()); ((DSpaceFilter) result).setContext(contextService.getContext());
((DSpaceFilter) result).setFieldResolver(fieldResolver); ((DSpaceFilter) result).setFieldResolver(fieldResolver);
} }
} } catch (InstantiationException | IllegalAccessException
catch (InstantiationException | IllegalAccessException | ContextServiceException e) {
| ContextServiceException e)
{
LOGGER.error("Filter " + filterClass.getName() LOGGER.error("Filter " + filterClass.getName()
+ " could not be instantiated", e); + " could not be instantiated", e);
} }
return result; return result;
} }

View File

@@ -8,10 +8,10 @@
package org.dspace.xoai.services.impl.xoai; package org.dspace.xoai.services.impl.xoai;
import com.lyncode.xoai.dataprovider.services.api.RepositoryConfiguration; import com.lyncode.xoai.dataprovider.services.api.RepositoryConfiguration;
import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.config.ConfigurationService; import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.context.ContextService; import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException; import org.dspace.xoai.services.api.context.ContextServiceException;
import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.xoai.IdentifyResolver; import org.dspace.xoai.services.api.xoai.IdentifyResolver;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -25,6 +25,7 @@ public class DSpaceIdentifyResolver implements IdentifyResolver {
@Override @Override
public RepositoryConfiguration getIdentify() throws ContextServiceException { public RepositoryConfiguration getIdentify() throws ContextServiceException {
return new DSpaceRepositoryConfiguration(earliestDateResolver, configurationService, contextService.getContext()); return new DSpaceRepositoryConfiguration(earliestDateResolver, configurationService,
contextService.getContext());
} }
} }

View File

@@ -7,6 +7,9 @@
*/ */
package org.dspace.xoai.services.impl.xoai; package org.dspace.xoai.services.impl.xoai;
import java.util.Date;
import java.util.List;
import com.lyncode.xoai.dataprovider.core.ListItemIdentifiersResult; import com.lyncode.xoai.dataprovider.core.ListItemIdentifiersResult;
import com.lyncode.xoai.dataprovider.core.ListItemsResults; import com.lyncode.xoai.dataprovider.core.ListItemsResults;
import com.lyncode.xoai.dataprovider.data.Filter; import com.lyncode.xoai.dataprovider.data.Filter;
@@ -21,15 +24,10 @@ import org.dspace.xoai.filter.DateUntilFilter;
import org.dspace.xoai.services.api.CollectionsService; import org.dspace.xoai.services.api.CollectionsService;
import org.dspace.xoai.services.api.HandleResolver; import org.dspace.xoai.services.api.HandleResolver;
import java.util.Date;
import java.util.List;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public abstract class DSpaceItemRepository implements ItemRepository public abstract class DSpaceItemRepository implements ItemRepository {
{
private CollectionsService collectionsService; private CollectionsService collectionsService;
private HandleResolver handleResolver; private HandleResolver handleResolver;
@@ -40,24 +38,21 @@ public abstract class DSpaceItemRepository implements ItemRepository
@Override @Override
public ListItemIdentifiersResult getItemIdentifiers( public ListItemIdentifiersResult getItemIdentifiers(
List<ScopedFilter> filters, int offset, int length, Date from) throws OAIException List<ScopedFilter> filters, int offset, int length, Date from) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
return this.getItemIdentifiers(filters, offset, length); return this.getItemIdentifiers(filters, offset, length);
} }
@Override @Override
public ListItemIdentifiersResult getItemIdentifiers( public ListItemIdentifiersResult getItemIdentifiers(
List<ScopedFilter> filters, int offset, int length, String setSpec) throws OAIException List<ScopedFilter> filters, int offset, int length, String setSpec) throws OAIException {
{
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), Scope.Query)); filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), Scope.Query));
return this.getItemIdentifiers(filters, offset, length); return this.getItemIdentifiers(filters, offset, length);
} }
@Override @Override
public ListItemIdentifiersResult getItemIdentifiers( public ListItemIdentifiersResult getItemIdentifiers(
List<ScopedFilter> filters, int offset, int length, Date from, Date until) throws OAIException List<ScopedFilter> filters, int offset, int length, Date from, Date until) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query));
return this.getItemIdentifiers(filters, offset, length); return this.getItemIdentifiers(filters, offset, length);
@@ -65,67 +60,60 @@ public abstract class DSpaceItemRepository implements ItemRepository
@Override @Override
public ListItemIdentifiersResult getItemIdentifiers( public ListItemIdentifiersResult getItemIdentifiers(
List<ScopedFilter> filters, int offset, int length, String setSpec, List<ScopedFilter> filters, int offset, int length, String setSpec,
Date from) throws OAIException Date from) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec),
Scope.Query)); Scope.Query));
return this.getItemIdentifiers(filters, offset, length); return this.getItemIdentifiers(filters, offset, length);
} }
@Override @Override
public ListItemIdentifiersResult getItemIdentifiers( public ListItemIdentifiersResult getItemIdentifiers(
List<ScopedFilter> filters, int offset, int length, String setSpec, List<ScopedFilter> filters, int offset, int length, String setSpec,
Date from, Date until) throws OAIException Date from, Date until) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query));
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec),
Scope.Query)); Scope.Query));
return this.getItemIdentifiers(filters, offset, length); return this.getItemIdentifiers(filters, offset, length);
} }
@Override @Override
public ListItemIdentifiersResult getItemIdentifiersUntil( public ListItemIdentifiersResult getItemIdentifiersUntil(
List<ScopedFilter> filters, int offset, int length, Date until) throws OAIException List<ScopedFilter> filters, int offset, int length, Date until) throws OAIException {
{
filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query));
return this.getItemIdentifiers(filters, offset, length); return this.getItemIdentifiers(filters, offset, length);
} }
@Override @Override
public ListItemIdentifiersResult getItemIdentifiersUntil( public ListItemIdentifiersResult getItemIdentifiersUntil(
List<ScopedFilter> filters, int offset, int length, String setSpec, List<ScopedFilter> filters, int offset, int length, String setSpec,
Date until) throws OAIException Date until) throws OAIException {
{
filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query));
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec),
Scope.Query)); Scope.Query));
return this.getItemIdentifiers(filters, offset, length); return this.getItemIdentifiers(filters, offset, length);
} }
@Override @Override
public ListItemsResults getItems(List<ScopedFilter> filters, int offset, public ListItemsResults getItems(List<ScopedFilter> filters, int offset,
int length, Date from) throws OAIException int length, Date from) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
return this.getItems(filters, offset, length); return this.getItems(filters, offset, length);
} }
@Override @Override
public ListItemsResults getItems(List<ScopedFilter> filters, int offset, public ListItemsResults getItems(List<ScopedFilter> filters, int offset,
int length, String setSpec) throws OAIException int length, String setSpec) throws OAIException {
{
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec),
Scope.Query)); Scope.Query));
return this.getItems(filters, offset, length); return this.getItems(filters, offset, length);
} }
@Override @Override
public ListItemsResults getItems(List<ScopedFilter> filters, int offset, public ListItemsResults getItems(List<ScopedFilter> filters, int offset,
int length, Date from, Date until) throws OAIException int length, Date from, Date until) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query));
return this.getItems(filters, offset, length); return this.getItems(filters, offset, length);
@@ -133,40 +121,36 @@ public abstract class DSpaceItemRepository implements ItemRepository
@Override @Override
public ListItemsResults getItems(List<ScopedFilter> filters, int offset, public ListItemsResults getItems(List<ScopedFilter> filters, int offset,
int length, String setSpec, Date from) throws OAIException int length, String setSpec, Date from) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec),
Scope.Query)); Scope.Query));
return this.getItems(filters, offset, length); return this.getItems(filters, offset, length);
} }
@Override @Override
public ListItemsResults getItems(List<ScopedFilter> filters, int offset, public ListItemsResults getItems(List<ScopedFilter> filters, int offset,
int length, String setSpec, Date from, Date until) throws OAIException int length, String setSpec, Date from, Date until) throws OAIException {
{
filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query)); filters.add(new ScopedFilter(getDateFromCondition(from), Scope.Query));
filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query));
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec),
Scope.Query)); Scope.Query));
return this.getItems(filters, offset, length); return this.getItems(filters, offset, length);
} }
@Override @Override
public ListItemsResults getItemsUntil(List<ScopedFilter> filters, int offset, public ListItemsResults getItemsUntil(List<ScopedFilter> filters, int offset,
int length, Date until) throws OAIException int length, Date until) throws OAIException {
{
filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(until), Scope.Query));
return this.getItems(filters, offset, length); return this.getItems(filters, offset, length);
} }
@Override @Override
public ListItemsResults getItemsUntil(List<ScopedFilter> filters, int offset, public ListItemsResults getItemsUntil(List<ScopedFilter> filters, int offset,
int length, String setSpec, Date from) throws OAIException int length, String setSpec, Date from) throws OAIException {
{
filters.add(new ScopedFilter(getDateUntilFilter(from), Scope.Query)); filters.add(new ScopedFilter(getDateUntilFilter(from), Scope.Query));
filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec), filters.add(new ScopedFilter(getDSpaceSetSpecFilter(setSpec),
Scope.Query)); Scope.Query));
return this.getItems(filters, offset, length); return this.getItems(filters, offset, length);
} }

View File

@@ -9,11 +9,11 @@ package org.dspace.xoai.services.impl.xoai;
import com.lyncode.xoai.dataprovider.services.api.ItemRepository; import com.lyncode.xoai.dataprovider.services.api.ItemRepository;
import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.SolrServerException;
import org.dspace.xoai.services.api.CollectionsService;
import org.dspace.xoai.services.api.HandleResolver;
import org.dspace.xoai.services.api.config.ConfigurationService; import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.context.ContextService; import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException; import org.dspace.xoai.services.api.context.ContextServiceException;
import org.dspace.xoai.services.api.CollectionsService;
import org.dspace.xoai.services.api.HandleResolver;
import org.dspace.xoai.services.api.solr.SolrQueryResolver; import org.dspace.xoai.services.api.solr.SolrQueryResolver;
import org.dspace.xoai.services.api.solr.SolrServerResolver; import org.dspace.xoai.services.api.solr.SolrServerResolver;
import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver; import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver;
@@ -41,10 +41,10 @@ public class DSpaceItemRepositoryResolver implements ItemRepositoryResolver {
if (itemRepository == null) { if (itemRepository == null) {
try { try {
itemRepository = new DSpaceItemSolrRepository( itemRepository = new DSpaceItemSolrRepository(
solrServerResolver.getServer(), solrServerResolver.getServer(),
collectionsService, collectionsService,
handleResolver, handleResolver,
solrQueryResolver); solrQueryResolver);
} catch (SolrServerException e) { } catch (SolrServerException e) {
throw new ContextServiceException(e.getMessage(), e); throw new ContextServiceException(e.getMessage(), e);
} }

View File

@@ -7,6 +7,10 @@
*/ */
package org.dspace.xoai.services.impl.xoai; package org.dspace.xoai.services.impl.xoai;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.lyncode.builder.ListBuilder; import com.lyncode.builder.ListBuilder;
import com.lyncode.xoai.dataprovider.core.ListItemIdentifiersResult; import com.lyncode.xoai.dataprovider.core.ListItemIdentifiersResult;
@@ -29,22 +33,16 @@ import org.dspace.xoai.solr.DSpaceSolrSearch;
import org.dspace.xoai.solr.exceptions.DSpaceSolrException; import org.dspace.xoai.solr.exceptions.DSpaceSolrException;
import org.dspace.xoai.solr.exceptions.SolrSearchEmptyException; import org.dspace.xoai.solr.exceptions.SolrSearchEmptyException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceItemSolrRepository extends DSpaceItemRepository public class DSpaceItemSolrRepository extends DSpaceItemRepository {
{
private static Logger log = LogManager.getLogger(DSpaceItemSolrRepository.class); private static Logger log = LogManager.getLogger(DSpaceItemSolrRepository.class);
private SolrServer server; private SolrServer server;
private SolrQueryResolver solrQueryResolver; private SolrQueryResolver solrQueryResolver;
public DSpaceItemSolrRepository(SolrServer server, CollectionsService collectionsService, HandleResolver handleResolver, SolrQueryResolver solrQueryResolver) public DSpaceItemSolrRepository(SolrServer server, CollectionsService collectionsService,
{ HandleResolver handleResolver, SolrQueryResolver solrQueryResolver) {
super(collectionsService, handleResolver); super(collectionsService, handleResolver);
this.server = server; this.server = server;
this.solrQueryResolver = solrQueryResolver; this.solrQueryResolver = solrQueryResolver;
@@ -52,17 +50,15 @@ public class DSpaceItemSolrRepository extends DSpaceItemRepository
@Override @Override
public Item getItem(String identifier) throws IdDoesNotExistException { public Item getItem(String identifier) throws IdDoesNotExistException {
if (identifier == null) throw new IdDoesNotExistException(); if (identifier == null) {
throw new IdDoesNotExistException();
}
String parts[] = identifier.split(Pattern.quote(":")); String parts[] = identifier.split(Pattern.quote(":"));
if (parts.length == 3) if (parts.length == 3) {
{ try {
try
{
SolrQuery params = new SolrQuery("item.handle:" + parts[2]); SolrQuery params = new SolrQuery("item.handle:" + parts[2]);
return new DSpaceSolrItem(DSpaceSolrSearch.querySingle(server, params)); return new DSpaceSolrItem(DSpaceSolrSearch.querySingle(server, params));
} } catch (SolrSearchEmptyException ex) {
catch (SolrSearchEmptyException ex)
{
throw new IdDoesNotExistException(ex); throw new IdDoesNotExistException(ex);
} }
} }
@@ -71,23 +67,19 @@ public class DSpaceItemSolrRepository extends DSpaceItemRepository
@Override @Override
public ListItemIdentifiersResult getItemIdentifiers( public ListItemIdentifiersResult getItemIdentifiers(
List<ScopedFilter> filters, int offset, int length) List<ScopedFilter> filters, int offset, int length) {
{ try {
try
{
QueryResult queryResult = retrieveItems(filters, offset, length); QueryResult queryResult = retrieveItems(filters, offset, length);
List<ItemIdentifier> identifierList = new ListBuilder<Item>() List<ItemIdentifier> identifierList = new ListBuilder<Item>()
.add(queryResult.getResults()) .add(queryResult.getResults())
.build(new Function<Item, ItemIdentifier>() { .build(new Function<Item, ItemIdentifier>() {
@Override @Override
public ItemIdentifier apply(Item elem) { public ItemIdentifier apply(Item elem) {
return elem; return elem;
} }
}); });
return new ListItemIdentifiersResult(queryResult.hasMore(), identifierList, queryResult.getTotal()); return new ListItemIdentifiersResult(queryResult.hasMore(), identifierList, queryResult.getTotal());
} } catch (DSpaceSolrException ex) {
catch (DSpaceSolrException ex)
{
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return new ListItemIdentifiersResult(false, new ArrayList<ItemIdentifier>()); return new ListItemIdentifiersResult(false, new ArrayList<ItemIdentifier>());
} }
@@ -95,29 +87,27 @@ public class DSpaceItemSolrRepository extends DSpaceItemRepository
@Override @Override
public ListItemsResults getItems(List<ScopedFilter> filters, int offset, public ListItemsResults getItems(List<ScopedFilter> filters, int offset,
int length) int length) {
{ try {
try
{
QueryResult queryResult = retrieveItems(filters, offset, length); QueryResult queryResult = retrieveItems(filters, offset, length);
return new ListItemsResults(queryResult.hasMore(), queryResult.getResults(), queryResult.getTotal()); return new ListItemsResults(queryResult.hasMore(), queryResult.getResults(), queryResult.getTotal());
} } catch (DSpaceSolrException ex) {
catch (DSpaceSolrException ex)
{
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return new ListItemsResults(false, new ArrayList<Item>()); return new ListItemsResults(false, new ArrayList<Item>());
} }
} }
private QueryResult retrieveItems (List<ScopedFilter> filters, int offset, int length) throws DSpaceSolrException { private QueryResult retrieveItems(List<ScopedFilter> filters, int offset, int length) throws DSpaceSolrException {
List<Item> list = new ArrayList<Item>(); List<Item> list = new ArrayList<Item>();
SolrQuery params = new SolrQuery(solrQueryResolver.buildQuery(filters)) SolrQuery params = new SolrQuery(solrQueryResolver.buildQuery(filters))
.setRows(length) .setRows(length)
.setStart(offset); .setStart(offset);
SolrDocumentList solrDocuments = DSpaceSolrSearch.query(server, params); SolrDocumentList solrDocuments = DSpaceSolrSearch.query(server, params);
for (SolrDocument doc : solrDocuments) for (SolrDocument doc : solrDocuments) {
list.add(new DSpaceSolrItem(doc)); list.add(new DSpaceSolrItem(doc));
return new QueryResult(list, (solrDocuments.getNumFound() > offset + length), (int) solrDocuments.getNumFound()); }
return new QueryResult(list, (solrDocuments.getNumFound() > offset + length),
(int) solrDocuments.getNumFound());
} }
private class QueryResult { private class QueryResult {

View File

@@ -7,6 +7,14 @@
*/ */
package org.dspace.xoai.services.impl.xoai; package org.dspace.xoai.services.impl.xoai;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.lyncode.xoai.dataprovider.core.DeleteMethod; import com.lyncode.xoai.dataprovider.core.DeleteMethod;
import com.lyncode.xoai.dataprovider.core.Granularity; import com.lyncode.xoai.dataprovider.core.Granularity;
import com.lyncode.xoai.dataprovider.services.api.RepositoryConfiguration; import com.lyncode.xoai.dataprovider.services.api.RepositoryConfiguration;
@@ -15,26 +23,16 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException; import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.EarliestDateResolver; import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.config.ConfigurationService;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
* @author Domingo Iglesias (diglesias at ub dot edu) * @author Domingo Iglesias (diglesias at ub dot edu)
*/ */
public class DSpaceRepositoryConfiguration implements RepositoryConfiguration public class DSpaceRepositoryConfiguration implements RepositoryConfiguration {
{
private static Logger log = LogManager.getLogger(DSpaceRepositoryConfiguration.class); private static Logger log = LogManager.getLogger(DSpaceRepositoryConfiguration.class);
private List<String> emails = null; private List<String> emails = null;
@@ -44,126 +42,120 @@ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration
private EarliestDateResolver dateResolver; private EarliestDateResolver dateResolver;
private ConfigurationService configurationService; private ConfigurationService configurationService;
public DSpaceRepositoryConfiguration(EarliestDateResolver dateResolver, ConfigurationService configurationService, Context context) public DSpaceRepositoryConfiguration(EarliestDateResolver dateResolver, ConfigurationService configurationService,
{ Context context) {
this.dateResolver = dateResolver; this.dateResolver = dateResolver;
this.configurationService = configurationService; this.configurationService = configurationService;
this.context = context; this.context = context;
} }
@Override @Override
public List<String> getAdminEmails() public List<String> getAdminEmails() {
{ if (emails == null) {
if (emails == null)
{
emails = new ArrayList<String>(); emails = new ArrayList<String>();
String result = configurationService.getProperty("mail.admin"); String result = configurationService.getProperty("mail.admin");
if (result == null) if (result == null) {
{ log.warn(
log.warn("{ OAI 2.0 :: DSpace } Not able to retrieve the mail.admin property from the configuration file"); "{ OAI 2.0 :: DSpace } Not able to retrieve the mail.admin property from the configuration file");
} } else {
else
emails.add(result); emails.add(result);
}
} }
return emails; return emails;
} }
@Override @Override
public String getBaseUrl() public String getBaseUrl() {
{ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); .getRequest();
if (baseUrl == null) if (baseUrl == null) {
{
baseUrl = configurationService.getProperty("oai.url"); baseUrl = configurationService.getProperty("oai.url");
if (baseUrl == null) { if (baseUrl == null) {
log.warn("{ OAI 2.0 :: DSpace } Not able to retrieve the oai.url property from oai.cfg. Falling back to request address"); log.warn(
"{ OAI 2.0 :: DSpace } Not able to retrieve the oai.url property from oai.cfg. Falling back to " +
"request address");
baseUrl = request.getRequestURL().toString() baseUrl = request.getRequestURL().toString()
.replace(request.getPathInfo(), ""); .replace(request.getPathInfo(), "");
} }
} }
return baseUrl + request.getPathInfo(); return baseUrl + request.getPathInfo();
} }
@Override @Override
public DeleteMethod getDeleteMethod() public DeleteMethod getDeleteMethod() {
{
return DeleteMethod.TRANSIENT; return DeleteMethod.TRANSIENT;
} }
@Override @Override
public Date getEarliestDate() public Date getEarliestDate() {
{
// Look at the database! // Look at the database!
try try {
{
return dateResolver.getEarliestDate(context); return dateResolver.getEarliestDate(context);
} } catch (SQLException e) {
catch (SQLException e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} } catch (InvalidMetadataFieldException e) {
catch (InvalidMetadataFieldException e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return new Date(); return new Date();
} }
@Override @Override
public Granularity getGranularity() public Granularity getGranularity() {
{
return Granularity.Second; return Granularity.Second;
} }
@Override @Override
public String getRepositoryName() public String getRepositoryName() {
{ if (name == null) {
if (name == null)
{
name = configurationService.getProperty("dspace.name"); name = configurationService.getProperty("dspace.name");
if (name == null) if (name == null) {
{ log.warn(
log.warn("{ OAI 2.0 :: DSpace } Not able to retrieve the dspace.name property from the configuration file"); "{ OAI 2.0 :: DSpace } Not able to retrieve the dspace.name property from the configuration file");
name = "OAI Repository"; name = "OAI Repository";
} }
} }
return name; return name;
} }
@Override @Override
public List<String> getDescription() { public List<String> getDescription() {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<String>();
String descriptionFile = configurationService.getProperty("oai", "description.file"); String descriptionFile = configurationService.getProperty("oai", "description.file");
if (descriptionFile == null) { if (descriptionFile == null) {
// Try indexed // Try indexed
boolean stop = false; boolean stop = false;
List<String> descriptionFiles = new ArrayList<String>(); List<String> descriptionFiles = new ArrayList<String>();
for (int i=0;!stop;i++) { 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; if (tmp == null) {
else descriptionFiles.add(tmp); stop = true;
} } else {
descriptionFiles.add(tmp);
for (String path : descriptionFiles) { }
try { }
File f = new File(path);
if (f.exists()) for (String path : descriptionFiles) {
result.add(FileUtils.readFileToString(f)); try {
} catch (IOException e) { File f = new File(path);
log.debug(e.getMessage(), e); if (f.exists()) {
} result.add(FileUtils.readFileToString(f));
} }
} catch (IOException e) {
} else { log.debug(e.getMessage(), e);
try { }
File f = new File(descriptionFile); }
if (f.exists())
result.add(FileUtils.readFileToString(f)); } else {
} catch (IOException e) { try {
log.debug(e.getMessage(), e); File f = new File(descriptionFile);
} if (f.exists()) {
} result.add(FileUtils.readFileToString(f));
return result; }
} } catch (IOException e) {
log.debug(e.getMessage(), e);
}
}
return result;
}
} }

View File

@@ -7,6 +7,8 @@
*/ */
package org.dspace.xoai.services.impl.xoai; package org.dspace.xoai.services.impl.xoai;
import java.util.Date;
import com.lyncode.xoai.dataprovider.core.ResumptionToken; import com.lyncode.xoai.dataprovider.core.ResumptionToken;
import com.lyncode.xoai.dataprovider.exceptions.BadResumptionToken; import com.lyncode.xoai.dataprovider.exceptions.BadResumptionToken;
import com.lyncode.xoai.dataprovider.services.api.ResumptionTokenFormatter; import com.lyncode.xoai.dataprovider.services.api.ResumptionTokenFormatter;
@@ -14,12 +16,10 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.xoai.util.DateUtils; import org.dspace.xoai.util.DateUtils;
import java.util.Date;
public class DSpaceResumptionTokenFormatter implements ResumptionTokenFormatter { public class DSpaceResumptionTokenFormatter implements ResumptionTokenFormatter {
private static Logger log = LogManager private static Logger log = LogManager
.getLogger(DSpaceResumptionTokenFormatter.class); .getLogger(DSpaceResumptionTokenFormatter.class);
public DSpaceResumptionTokenFormatter() { public DSpaceResumptionTokenFormatter() {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
@@ -27,10 +27,13 @@ public class DSpaceResumptionTokenFormatter implements ResumptionTokenFormatter
@Override @Override
public ResumptionToken parse(String resumptionToken) throws BadResumptionToken { public ResumptionToken parse(String resumptionToken) throws BadResumptionToken {
if (resumptionToken == null) return new ResumptionToken(); if (resumptionToken == null) {
return new ResumptionToken();
}
String[] res = resumptionToken.split("/", -1); String[] res = resumptionToken.split("/", -1);
if (res.length != 5) throw new BadResumptionToken(); if (res.length != 5) {
else { throw new BadResumptionToken();
} else {
try { try {
int offset = Integer.parseInt(res[4]); int offset = Integer.parseInt(res[4]);
String prefix = (res[0].equals("")) ? null : res[0]; String prefix = (res[0].equals("")) ? null : res[0];
@@ -49,17 +52,21 @@ public class DSpaceResumptionTokenFormatter implements ResumptionTokenFormatter
@Override @Override
public String format(ResumptionToken resumptionToken) { public String format(ResumptionToken resumptionToken) {
String result = ""; String result = "";
if (resumptionToken.hasMetadataPrefix()) if (resumptionToken.hasMetadataPrefix()) {
result += resumptionToken.getMetadataPrefix(); result += resumptionToken.getMetadataPrefix();
}
result += "/"; result += "/";
if (resumptionToken.hasFrom()) if (resumptionToken.hasFrom()) {
result += DateUtils.format(resumptionToken.getFrom()); result += DateUtils.format(resumptionToken.getFrom());
}
result += "/"; result += "/";
if (resumptionToken.hasUntil()) if (resumptionToken.hasUntil()) {
result += DateUtils.format(resumptionToken.getUntil()); result += DateUtils.format(resumptionToken.getUntil());
}
result += "/"; result += "/";
if (resumptionToken.hasSet()) if (resumptionToken.hasSet()) {
result += resumptionToken.getSet(); result += resumptionToken.getSet();
}
result += "/"; result += "/";
result += resumptionToken.getOffset(); result += resumptionToken.getOffset();
return result; return result;

View File

@@ -7,6 +7,10 @@
*/ */
package org.dspace.xoai.services.impl.xoai; package org.dspace.xoai.services.impl.xoai;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.lyncode.xoai.dataprovider.core.ListSetsResult; import com.lyncode.xoai.dataprovider.core.ListSetsResult;
import com.lyncode.xoai.dataprovider.core.Set; import com.lyncode.xoai.dataprovider.core.Set;
import com.lyncode.xoai.dataprovider.services.api.SetRepository; import com.lyncode.xoai.dataprovider.services.api.SetRepository;
@@ -15,24 +19,18 @@ import org.apache.log4j.Logger;
import org.dspace.content.Collection; import org.dspace.content.Collection;
import org.dspace.content.Community; import org.dspace.content.Community;
import org.dspace.content.DSpaceObject; import org.dspace.content.DSpaceObject;
import org.dspace.core.Context;
import org.dspace.xoai.data.DSpaceSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService; import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService; import org.dspace.content.service.CommunityService;
import org.dspace.core.Context;
import org.dspace.handle.factory.HandleServiceFactory; import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService; import org.dspace.handle.service.HandleService;
import org.dspace.xoai.data.DSpaceSet;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceSetRepository implements SetRepository public class DSpaceSetRepository implements SetRepository {
{
private static final Logger log = LogManager.getLogger(DSpaceSetRepository.class); private static final Logger log = LogManager.getLogger(DSpaceSetRepository.class);
private final Context _context; private final Context _context;
@@ -41,39 +39,30 @@ public class DSpaceSetRepository implements SetRepository
private final CommunityService communityService; private final CommunityService communityService;
private final CollectionService collectionService; private final CollectionService collectionService;
public DSpaceSetRepository(Context context) public DSpaceSetRepository(Context context) {
{
_context = context; _context = context;
handleService = HandleServiceFactory.getInstance().getHandleService(); handleService = HandleServiceFactory.getInstance().getHandleService();
communityService = ContentServiceFactory.getInstance().getCommunityService(); communityService = ContentServiceFactory.getInstance().getCommunityService();
collectionService = ContentServiceFactory.getInstance().getCollectionService(); collectionService = ContentServiceFactory.getInstance().getCollectionService();
} }
private int getCommunityCount() private int getCommunityCount() {
{ try {
try
{
List<Community> communityList = communityService.findAll(_context); List<Community> communityList = communityService.findAll(_context);
return communityList.size(); return communityList.size();
} } catch (SQLException e) {
catch (SQLException e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return 0; return 0;
} }
private int getCollectionCount() private int getCollectionCount() {
{ try {
try
{
List<Collection> collectionList = collectionService.findAll(_context); List<Collection> collectionList = collectionService.findAll(_context);
return collectionList.size(); return collectionList.size();
} } catch (SQLException e) {
catch (SQLException e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return 0; return 0;
@@ -87,23 +76,18 @@ public class DSpaceSetRepository implements SetRepository
* @param length return up to this many Sets. * @param length return up to this many Sets.
* @return some Sets representing the Community list segment. * @return some Sets representing the Community list segment.
*/ */
private List<Set> community(int offset, int length) private List<Set> community(int offset, int length) {
{
List<Set> array = new ArrayList<Set>(); List<Set> array = new ArrayList<Set>();
try try {
{
List<Community> communityList = communityService.findAll(_context, length, offset); List<Community> communityList = communityService.findAll(_context, length, offset);
for(Community community : communityList) for (Community community : communityList) {
{
array.add(DSpaceSet.newDSpaceCommunitySet( array.add(DSpaceSet.newDSpaceCommunitySet(
community.getHandle(), community.getHandle(),
community.getName())); community.getName()));
} }
} } catch (SQLException e) {
catch (SQLException e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return array; return array;
@@ -117,31 +101,25 @@ public class DSpaceSetRepository implements SetRepository
* @param length return up to this many Sets. * @param length return up to this many Sets.
* @return some Sets representing the Collection list segment. * @return some Sets representing the Collection list segment.
*/ */
private List<Set> collection(int offset, int length) private List<Set> collection(int offset, int length) {
{
List<Set> array = new ArrayList<Set>(); List<Set> array = new ArrayList<Set>();
try try {
{
List<Collection> collectionList = collectionService.findAll(_context, length, offset); List<Collection> collectionList = collectionService.findAll(_context, length, offset);
for(Collection collection : collectionList) for (Collection collection : collectionList) {
{
array.add(DSpaceSet.newDSpaceCollectionSet( array.add(DSpaceSet.newDSpaceCollectionSet(
collection.getHandle(), collection.getHandle(),
collection.getName())); collection.getName()));
} }
} } catch (SQLException e) {
catch (SQLException e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return array; return array;
} }
@Override @Override
public ListSetsResult retrieveSets(int offset, int length) public ListSetsResult retrieveSets(int offset, int length) {
{
// Only database sets (virtual sets are added by lyncode common library) // Only database sets (virtual sets are added by lyncode common library)
log.debug("Querying sets. Offset: " + offset + " - Length: " + length); log.debug("Querying sets. Offset: " + offset + " - Length: " + length);
List<Set> array = new ArrayList<Set>(); List<Set> array = new ArrayList<Set>();
@@ -150,66 +128,53 @@ public class DSpaceSetRepository implements SetRepository
int collectionCount = this.getCollectionCount(); int collectionCount = this.getCollectionCount();
log.debug("Collections: " + collectionCount); log.debug("Collections: " + collectionCount);
if (offset < communityCount) if (offset < communityCount) {
{ if (offset + length > communityCount) {
if (offset + length > communityCount)
{
// Add some collections // Add some collections
List<Set> tmp = community(offset, length); List<Set> tmp = community(offset, length);
array.addAll(tmp); array.addAll(tmp);
array.addAll(collection(0, length - tmp.size())); array.addAll(collection(0, length - tmp.size()));
} } else {
else
array.addAll(community(offset, length)); array.addAll(community(offset, length));
} }
else if (offset < communityCount + collectionCount) } else if (offset < communityCount + collectionCount) {
{
array.addAll(collection(offset - communityCount, length)); array.addAll(collection(offset - communityCount, length));
} }
log.debug("Has More Results: " log.debug("Has More Results: "
+ ((offset + length < communityCount + collectionCount) ? "Yes" + ((offset + length < communityCount + collectionCount) ? "Yes"
: "No")); : "No"));
return new ListSetsResult(offset + length < communityCount return new ListSetsResult(offset + length < communityCount
+ collectionCount, array, communityCount + collectionCount); + collectionCount, array, communityCount + collectionCount);
} }
@Override @Override
public boolean supportSets() public boolean supportSets() {
{
return true; return true;
} }
@Override @Override
public boolean exists(String setSpec) public boolean exists(String setSpec) {
{ if (setSpec.startsWith("col_")) {
if (setSpec.startsWith("col_")) try {
{
try
{
DSpaceObject dso = handleService.resolveToObject(_context, DSpaceObject dso = handleService.resolveToObject(_context,
setSpec.replace("col_", "").replace("_", "/")); setSpec.replace("col_", "").replace("_", "/"));
if (dso == null || !(dso instanceof Collection)) if (dso == null || !(dso instanceof Collection)) {
return false; return false;
}
return true; return true;
} } catch (SQLException ex) {
catch (SQLException ex)
{
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
} }
} } else if (setSpec.startsWith("com_")) {
else if (setSpec.startsWith("com_")) try {
{
try
{
DSpaceObject dso = handleService.resolveToObject(_context, DSpaceObject dso = handleService.resolveToObject(_context,
setSpec.replace("com_", "").replace("_", "/")); setSpec.replace("com_", "").replace("_", "/"));
if (dso == null || !(dso instanceof Community)) if (dso == null || !(dso instanceof Community)) {
return false; return false;
}
return true; return true;
} } catch (SQLException ex) {
catch (SQLException ex)
{
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
} }
} }

View File

@@ -19,40 +19,37 @@ import org.dspace.xoai.solr.exceptions.DSpaceSolrException;
import org.dspace.xoai.solr.exceptions.SolrSearchEmptyException; import org.dspace.xoai.solr.exceptions.SolrSearchEmptyException;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceSolrSearch public class DSpaceSolrSearch {
{
/**
* Default constructor
*/
private DSpaceSolrSearch() { }
public static SolrDocumentList query(SolrServer server, SolrQuery solrParams) public static SolrDocumentList query(SolrServer server, SolrQuery solrParams)
throws DSpaceSolrException throws DSpaceSolrException {
{ try {
try
{
solrParams.addSortField("item.id", ORDER.asc); solrParams.addSortField("item.id", ORDER.asc);
QueryResponse response = server.query(solrParams); QueryResponse response = server.query(solrParams);
return response.getResults(); return response.getResults();
} } catch (SolrServerException ex) {
catch (SolrServerException ex)
{
throw new DSpaceSolrException(ex.getMessage(), ex); throw new DSpaceSolrException(ex.getMessage(), ex);
} }
} }
public static SolrDocument querySingle(SolrServer server, SolrQuery solrParams) public static SolrDocument querySingle(SolrServer server, SolrQuery solrParams)
throws SolrSearchEmptyException throws SolrSearchEmptyException {
{ try {
try
{
solrParams.addSortField("item.id", ORDER.asc); solrParams.addSortField("item.id", ORDER.asc);
QueryResponse response = server.query(solrParams); QueryResponse response = server.query(solrParams);
if (response.getResults().getNumFound() > 0) if (response.getResults().getNumFound() > 0) {
return response.getResults().get(0); return response.getResults().get(0);
else } else {
throw new SolrSearchEmptyException(); throw new SolrSearchEmptyException();
} }
catch (SolrServerException ex) } catch (SolrServerException ex) {
{
throw new SolrSearchEmptyException(ex.getMessage(), ex); throw new SolrSearchEmptyException(ex.getMessage(), ex);
} }
} }

View File

@@ -16,27 +16,25 @@ import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.dspace.core.ConfigurationManager; import org.dspace.core.ConfigurationManager;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DSpaceSolrServer public class DSpaceSolrServer {
{
private static Logger log = LogManager.getLogger(DSpaceSolrServer.class); private static Logger log = LogManager.getLogger(DSpaceSolrServer.class);
private static SolrServer _server = null; private static SolrServer _server = null;
public static SolrServer getServer() throws SolrServerException /**
{ * Default constructor
if (_server == null) */
{ private DSpaceSolrServer() { }
try
{ public static SolrServer getServer() throws SolrServerException {
if (_server == null) {
try {
_server = new HttpSolrServer( _server = new HttpSolrServer(
ConfigurationManager.getProperty("oai", "solr.url")); ConfigurationManager.getProperty("oai", "solr.url"));
log.debug("Solr Server Initialized"); log.debug("Solr Server Initialized");
} } catch (Exception e) {
catch (Exception e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }

View File

@@ -8,35 +8,29 @@
package org.dspace.xoai.solr.exceptions; package org.dspace.xoai.solr.exceptions;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class DSpaceSolrException extends Exception public class DSpaceSolrException extends Exception {
{
/** /**
* Creates a new instance of <code>DSpaceSolrException</code> without detail * Creates a new instance of <code>DSpaceSolrException</code> without detail
* message. * message.
*/ */
public DSpaceSolrException() public DSpaceSolrException() {
{
} }
/** /**
* Constructs an instance of <code>DSpaceSolrException</code> with the * Constructs an instance of <code>DSpaceSolrException</code> with the
* specified detail message. * specified detail message.
* *
* @param msg * @param msg the detail message.
* the detail message.
*/ */
public DSpaceSolrException(String msg) public DSpaceSolrException(String msg) {
{
super(msg); super(msg);
} }
public DSpaceSolrException(String msg, Throwable t) public DSpaceSolrException(String msg, Throwable t) {
{
super(msg, t); super(msg, t);
} }
} }

View File

@@ -9,34 +9,28 @@
package org.dspace.xoai.solr.exceptions; package org.dspace.xoai.solr.exceptions;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class DSpaceSolrIndexerException extends Exception public class DSpaceSolrIndexerException extends Exception {
{
/** /**
* Creates a new instance of <code>DSpaceSolrException</code> without detail * Creates a new instance of <code>DSpaceSolrException</code> without detail
* message. * message.
*/ */
public DSpaceSolrIndexerException() public DSpaceSolrIndexerException() {
{
} }
/** /**
* Constructs an instance of <code>DSpaceSolrException</code> with the * Constructs an instance of <code>DSpaceSolrException</code> with the
* specified detail message. * specified detail message.
* *
* @param msg * @param msg the detail message.
* the detail message.
*/ */
public DSpaceSolrIndexerException(String msg) public DSpaceSolrIndexerException(String msg) {
{
super(msg); super(msg);
} }
public DSpaceSolrIndexerException(String msg, Throwable t) public DSpaceSolrIndexerException(String msg, Throwable t) {
{
super(msg, t); super(msg, t);
} }
} }

View File

@@ -9,35 +9,29 @@
package org.dspace.xoai.solr.exceptions; package org.dspace.xoai.solr.exceptions;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class SolrSearchEmptyException extends Exception public class SolrSearchEmptyException extends Exception {
{
/** /**
* Creates a new instance of <code>SolrSearchEmptyException</code> without * Creates a new instance of <code>SolrSearchEmptyException</code> without
* detail message. * detail message.
*/ */
public SolrSearchEmptyException() public SolrSearchEmptyException() {
{
} }
/** /**
* Constructs an instance of <code>SolrSearchEmptyException</code> with the * Constructs an instance of <code>SolrSearchEmptyException</code> with the
* specified detail message. * specified detail message.
* *
* @param msg * @param msg the detail message.
* the detail message.
*/ */
public SolrSearchEmptyException(String msg) public SolrSearchEmptyException(String msg) {
{
super(msg); super(msg);
} }
public SolrSearchEmptyException(String msg, Throwable t) public SolrSearchEmptyException(String msg, Throwable t) {
{
super(msg, t); super(msg, t);
} }
} }

View File

@@ -7,24 +7,26 @@
*/ */
package org.dspace.xoai.util; package org.dspace.xoai.util;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import java.util.TimeZone; import java.util.TimeZone;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class DateUtils public class DateUtils {
{
private static Logger log = LogManager.getLogger(DateUtils.class); private static Logger log = LogManager.getLogger(DateUtils.class);
/**
* Default constructor
*/
private DateUtils() { }
/** /**
* Format a Date object as a valid UTC Date String, per OAI-PMH guidelines * Format a Date object as a valid UTC Date String, per OAI-PMH guidelines
@@ -33,13 +35,12 @@ public class DateUtils
* @param date Date object * @param date Date object
* @return UTC date string * @return UTC date string
*/ */
public static String format(Date date) public static String format(Date date) {
{
// NOTE: OAI-PMH REQUIRES that all dates be expressed in UTC format // NOTE: OAI-PMH REQUIRES that all dates be expressed in UTC format
// as YYYY-MM-DDThh:mm:ssZ For more details, see // as YYYY-MM-DDThh:mm:ssZ For more details, see
// http://www.openarchives.org/OAI/openarchivesprotocol.html#DatestampsResponses // http://www.openarchives.org/OAI/openarchivesprotocol.html#DatestampsResponses
SimpleDateFormat sdf = new SimpleDateFormat( SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'"); "yyyy-MM-dd'T'HH:mm:ss'Z'");
// We indicate that the returned date is in UTC so we have // We indicate that the returned date is in UTC so we have
// to set the time zone of sdf correctly // to set the time zone of sdf correctly
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
@@ -49,57 +50,42 @@ public class DateUtils
/** /**
* Parse a string into a Date object * Parse a string into a Date object
*
* @param date string to parse * @param date string to parse
* @return Date * @return Date
*/ */
public static Date parse(String date) public static Date parse(String date) {
{
// First try to parse as a full UTC date/time, e.g. 2008-01-01T00:00:00Z // First try to parse as a full UTC date/time, e.g. 2008-01-01T00:00:00Z
SimpleDateFormat format = new SimpleDateFormat( SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'"); "yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC")); format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date ret; Date ret;
try try {
{
ret = format.parse(date); ret = format.parse(date);
return ret; return ret;
} } catch (ParseException ex) {
catch (ParseException ex)
{
// If a parse exception, try other logical date/time formats // If a parse exception, try other logical date/time formats
// based on the local timezone // based on the local timezone
format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.getDefault()); Locale.getDefault());
try try {
{
return format.parse(date); return format.parse(date);
} } catch (ParseException e1) {
catch (ParseException e1)
{
format = new SimpleDateFormat("yyyy-MM-dd", format = new SimpleDateFormat("yyyy-MM-dd",
Locale.getDefault()); Locale.getDefault());
try try {
{
return format.parse(date); return format.parse(date);
} } catch (ParseException e2) {
catch (ParseException e2)
{
format = new SimpleDateFormat("yyyy-MM", format = new SimpleDateFormat("yyyy-MM",
Locale.getDefault()); Locale.getDefault());
try try {
{
return format.parse(date); return format.parse(date);
} } catch (ParseException e3) {
catch (ParseException e3)
{
format = new SimpleDateFormat("yyyy", format = new SimpleDateFormat("yyyy",
Locale.getDefault()); Locale.getDefault());
try try {
{
return format.parse(date); return format.parse(date);
} } catch (ParseException e4) {
catch (ParseException e4)
{
log.error(e4.getMessage(), e4); log.error(e4.getMessage(), e4);
} }
} }
@@ -109,19 +95,15 @@ public class DateUtils
return new Date(); return new Date();
} }
public static Date parseFromSolrDate(String date) public static Date parseFromSolrDate(String date) {
{
SimpleDateFormat format = new SimpleDateFormat( SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'"); "yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC")); format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date ret; Date ret;
try try {
{
ret = format.parse(date); ret = format.parse(date);
return ret; return ret;
} } catch (ParseException e) {
catch (ParseException e)
{
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
return new Date(); return new Date();

View File

@@ -7,123 +7,124 @@
*/ */
package org.dspace.xoai.util; package org.dspace.xoai.util;
import com.lyncode.xoai.dataprovider.xml.xoai.Element;
import com.lyncode.xoai.dataprovider.xml.xoai.Metadata;
import com.lyncode.xoai.util.Base64Utils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.*;
import org.dspace.content.authority.Choices;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Utils;
import org.dspace.xoai.data.DSpaceItem;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import com.lyncode.xoai.dataprovider.xml.xoai.Element;
import com.lyncode.xoai.dataprovider.xml.xoai.Metadata;
import com.lyncode.xoai.util.Base64Utils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dspace.app.util.factory.UtilServiceFactory; import org.dspace.app.util.factory.UtilServiceFactory;
import org.dspace.app.util.service.MetadataExposureService; import org.dspace.app.util.service.MetadataExposureService;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.content.MetadataField;
import org.dspace.content.MetadataValue;
import org.dspace.content.authority.Choices;
import org.dspace.content.factory.ContentServiceFactory; import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamService; import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.ItemService; import org.dspace.content.service.ItemService;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.core.Utils;
import org.dspace.xoai.data.DSpaceItem;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class ItemUtils public class ItemUtils {
{
private static final Logger log = LogManager.getLogger(ItemUtils.class); private static final Logger log = LogManager.getLogger(ItemUtils.class);
private static final MetadataExposureService metadataExposureService private static final MetadataExposureService metadataExposureService
= UtilServiceFactory.getInstance().getMetadataExposureService(); = UtilServiceFactory.getInstance().getMetadataExposureService();
private static final ItemService itemService private static final ItemService itemService
= ContentServiceFactory.getInstance().getItemService(); = ContentServiceFactory.getInstance().getItemService();
private static final BitstreamService bitstreamService private static final BitstreamService bitstreamService
= ContentServiceFactory.getInstance().getBitstreamService(); = ContentServiceFactory.getInstance().getBitstreamService();
private static Element getElement(List<Element> list, String name) /**
{ * Default constructor
for (Element e : list) */
if (name.equals(e.getName())) private ItemUtils() { }
private static Element getElement(List<Element> list, String name) {
for (Element e : list) {
if (name.equals(e.getName())) {
return e; return e;
}
}
return null; return null;
} }
private static Element create(String name)
{ private static Element create(String name) {
Element e = new Element(); Element e = new Element();
e.setName(name); e.setName(name);
return e; return e;
} }
private static Element.Field createValue( private static Element.Field createValue(
String name, String value) String name, String value) {
{
Element.Field e = new Element.Field(); Element.Field e = new Element.Field();
e.setValue(value); e.setValue(value);
e.setName(name); e.setName(name);
return e; return e;
} }
public static Metadata retrieveMetadata (Context context, Item item) {
public static Metadata retrieveMetadata(Context context, Item item) {
Metadata metadata; Metadata metadata;
// read all metadata into Metadata Object // read all metadata into Metadata Object
metadata = new Metadata(); metadata = new Metadata();
List<MetadataValue> vals = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY); List<MetadataValue> vals = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (MetadataValue val : vals) for (MetadataValue val : vals) {
{
MetadataField field = val.getMetadataField(); MetadataField field = val.getMetadataField();
// Don't expose fields that are hidden by configuration // Don't expose fields that are hidden by configuration
try { try {
if (metadataExposureService.isHidden(context, if (metadataExposureService.isHidden(context,
field.getMetadataSchema().getName(), field.getMetadataSchema().getName(),
field.getElement(), field.getElement(),
field.getQualifier())) field.getQualifier())) {
{
continue; continue;
} }
} catch(SQLException se) { } catch (SQLException se) {
throw new RuntimeException(se); throw new RuntimeException(se);
} }
Element valueElem = null; Element valueElem = null;
Element schema = getElement(metadata.getElement(), field.getMetadataSchema().getName()); Element schema = getElement(metadata.getElement(), field.getMetadataSchema().getName());
if (schema == null) if (schema == null) {
{
schema = create(field.getMetadataSchema().getName()); schema = create(field.getMetadataSchema().getName());
metadata.getElement().add(schema); metadata.getElement().add(schema);
} }
valueElem = schema; valueElem = schema;
// Has element.. with XOAI one could have only schema and value // Has element.. with XOAI one could have only schema and value
if (field.getElement() != null && !field.getElement().equals("")) if (field.getElement() != null && !field.getElement().equals("")) {
{
Element element = getElement(schema.getElement(), Element element = getElement(schema.getElement(),
field.getElement()); field.getElement());
if (element == null) if (element == null) {
{
element = create(field.getElement()); element = create(field.getElement());
schema.getElement().add(element); schema.getElement().add(element);
} }
valueElem = element; valueElem = element;
// Qualified element? // Qualified element?
if (field.getQualifier() != null && !field.getQualifier().equals("")) if (field.getQualifier() != null && !field.getQualifier().equals("")) {
{
Element qualifier = getElement(element.getElement(), Element qualifier = getElement(element.getElement(),
field.getQualifier()); field.getQualifier());
if (qualifier == null) if (qualifier == null) {
{
qualifier = create(field.getQualifier()); qualifier = create(field.getQualifier());
element.getElement().add(qualifier); element.getElement().add(qualifier);
} }
@@ -132,23 +133,18 @@ public class ItemUtils
} }
// Language? // Language?
if (val.getLanguage() != null && !val.getLanguage().equals("")) if (val.getLanguage() != null && !val.getLanguage().equals("")) {
{
Element language = getElement(valueElem.getElement(), Element language = getElement(valueElem.getElement(),
val.getLanguage()); val.getLanguage());
if (language == null) if (language == null) {
{
language = create(val.getLanguage()); language = create(val.getLanguage());
valueElem.getElement().add(language); valueElem.getElement().add(language);
} }
valueElem = language; valueElem = language;
} } else {
else
{
Element language = getElement(valueElem.getElement(), Element language = getElement(valueElem.getElement(),
"none"); "none");
if (language == null) if (language == null) {
{
language = create("none"); language = create("none");
valueElem.getElement().add(language); valueElem.getElement().add(language);
} }
@@ -158,8 +154,9 @@ public class ItemUtils
valueElem.getField().add(createValue("value", val.getValue())); valueElem.getField().add(createValue("value", val.getValue()));
if (val.getAuthority() != null) { if (val.getAuthority() != null) {
valueElem.getField().add(createValue("authority", val.getAuthority())); valueElem.getField().add(createValue("authority", val.getAuthority()));
if (val.getConfidence() != Choices.CF_NOVALUE) if (val.getConfidence() != Choices.CF_NOVALUE) {
valueElem.getField().add(createValue("confidence", val.getConfidence() + "")); valueElem.getField().add(createValue("confidence", val.getConfidence() + ""));
}
} }
} }
// Done! Metadata has been read! // Done! Metadata has been read!
@@ -168,55 +165,46 @@ public class ItemUtils
metadata.getElement().add(bundles); metadata.getElement().add(bundles);
List<Bundle> bs; List<Bundle> bs;
try try {
{
bs = item.getBundles(); bs = item.getBundles();
for (Bundle b : bs) for (Bundle b : bs) {
{
Element bundle = create("bundle"); Element bundle = create("bundle");
bundles.getElement().add(bundle); bundles.getElement().add(bundle);
bundle.getField() bundle.getField()
.add(createValue("name", b.getName())); .add(createValue("name", b.getName()));
Element bitstreams = create("bitstreams"); Element bitstreams = create("bitstreams");
bundle.getElement().add(bitstreams); bundle.getElement().add(bitstreams);
List<Bitstream> bits = b.getBitstreams(); List<Bitstream> bits = b.getBitstreams();
for (Bitstream bit : bits) for (Bitstream bit : bits) {
{
Element bitstream = create("bitstream"); Element bitstream = create("bitstream");
bitstreams.getElement().add(bitstream); bitstreams.getElement().add(bitstream);
String url = ""; String url = "";
String bsName = bit.getName(); String bsName = bit.getName();
String sid = String.valueOf(bit.getSequenceID()); String sid = String.valueOf(bit.getSequenceID());
String baseUrl = ConfigurationManager.getProperty("oai", String baseUrl = ConfigurationManager.getProperty("oai",
"bitstream.baseUrl"); "bitstream.baseUrl");
String handle = null; String handle = null;
// get handle of parent Item of this bitstream, if there // get handle of parent Item of this bitstream, if there
// is one: // is one:
List<Bundle> bn = bit.getBundles(); List<Bundle> bn = bit.getBundles();
if (!bn.isEmpty()) if (!bn.isEmpty()) {
{
List<Item> bi = bn.get(0).getItems(); List<Item> bi = bn.get(0).getItems();
if (!bi.isEmpty()) if (!bi.isEmpty()) {
{
handle = bi.get(0).getHandle(); handle = bi.get(0).getHandle();
} }
} }
if (bsName == null) if (bsName == null) {
{
List<String> ext = bit.getFormat(context).getExtensions(); List<String> ext = bit.getFormat(context).getExtensions();
bsName = "bitstream_" + sid bsName = "bitstream_" + sid
+ (ext.isEmpty() ? "" : ext.get(0)); + (ext.isEmpty() ? "" : ext.get(0));
} }
if (handle != null && baseUrl != null) if (handle != null && baseUrl != null) {
{
url = baseUrl + "/bitstream/" url = baseUrl + "/bitstream/"
+ handle + "/" + handle + "/"
+ sid + "/" + sid + "/"
+ URLUtils.encode(bsName); + URLUtils.encode(bsName);
} } else {
else
{
url = URLUtils.encode(bsName); url = URLUtils.encode(bsName);
} }
@@ -226,96 +214,89 @@ public class ItemUtils
String name = bit.getName(); String name = bit.getName();
String description = bit.getDescription(); String description = bit.getDescription();
if (name != null) if (name != null) {
bitstream.getField().add( bitstream.getField().add(
createValue("name", name)); createValue("name", name));
if (oname != null) }
if (oname != null) {
bitstream.getField().add( bitstream.getField().add(
createValue("originalName", name)); createValue("originalName", name));
if (description != null) }
if (description != null) {
bitstream.getField().add( bitstream.getField().add(
createValue("description", description)); createValue("description", description));
}
bitstream.getField().add( bitstream.getField().add(
createValue("format", bit.getFormat(context) createValue("format", bit.getFormat(context)
.getMIMEType())); .getMIMEType()));
bitstream.getField().add( bitstream.getField().add(
createValue("size", "" + bit.getSize())); createValue("size", "" + bit.getSize()));
bitstream.getField().add(createValue("url", url)); bitstream.getField().add(createValue("url", url));
bitstream.getField().add( bitstream.getField().add(
createValue("checksum", cks)); createValue("checksum", cks));
bitstream.getField().add( bitstream.getField().add(
createValue("checksumAlgorithm", cka)); createValue("checksumAlgorithm", cka));
bitstream.getField().add( bitstream.getField().add(
createValue("sid", bit.getSequenceID() createValue("sid", bit.getSequenceID()
+ "")); + ""));
} }
} }
} } catch (SQLException e1) {
catch (SQLException e1)
{
e1.printStackTrace(); e1.printStackTrace();
} }
// Other info // Other info
Element other = create("others"); Element other = create("others");
other.getField().add( other.getField().add(
createValue("handle", item.getHandle())); createValue("handle", item.getHandle()));
other.getField().add( other.getField().add(
createValue("identifier", DSpaceItem.buildIdentifier(item.getHandle()))); createValue("identifier", DSpaceItem.buildIdentifier(item.getHandle())));
other.getField().add( other.getField().add(
createValue("lastModifyDate", item createValue("lastModifyDate", item
.getLastModified().toString())); .getLastModified().toString()));
metadata.getElement().add(other); metadata.getElement().add(other);
// Repository Info // Repository Info
Element repository = create("repository"); Element repository = create("repository");
repository.getField().add( repository.getField().add(
createValue("name", createValue("name",
ConfigurationManager.getProperty("dspace.name"))); ConfigurationManager.getProperty("dspace.name")));
repository.getField().add( repository.getField().add(
createValue("mail", createValue("mail",
ConfigurationManager.getProperty("mail.admin"))); ConfigurationManager.getProperty("mail.admin")));
metadata.getElement().add(repository); metadata.getElement().add(repository);
// Licensing info // Licensing info
Element license = create("license"); Element license = create("license");
List<Bundle> licBundles; List<Bundle> licBundles;
try try {
{
licBundles = itemService.getBundles(item, Constants.LICENSE_BUNDLE_NAME); licBundles = itemService.getBundles(item, Constants.LICENSE_BUNDLE_NAME);
if (!licBundles.isEmpty()) if (!licBundles.isEmpty()) {
{
Bundle licBundle = licBundles.get(0); Bundle licBundle = licBundles.get(0);
List<Bitstream> licBits = licBundle.getBitstreams(); List<Bitstream> licBits = licBundle.getBitstreams();
if (!licBits.isEmpty()) if (!licBits.isEmpty()) {
{
Bitstream licBit = licBits.get(0); Bitstream licBit = licBits.get(0);
InputStream in; InputStream in;
try try {
{
in = bitstreamService.retrieve(context, licBit); in = bitstreamService.retrieve(context, licBit);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
Utils.bufferedCopy(in, out); Utils.bufferedCopy(in, out);
license.getField().add( license.getField().add(
createValue("bin", createValue("bin",
Base64Utils.encode(out.toString()))); Base64Utils.encode(out.toString())));
metadata.getElement().add(license); metadata.getElement().add(license);
} } catch (AuthorizeException | IOException | SQLException e) {
catch (AuthorizeException | IOException | SQLException e)
{
log.warn(e.getMessage(), e); log.warn(e.getMessage(), e);
} }
} }
} }
} } catch (SQLException e1) {
catch (SQLException e1)
{
log.warn(e1.getMessage(), e1); log.warn(e1.getMessage(), e1);
} }
return metadata; return metadata;
} }
} }

View File

@@ -7,28 +7,29 @@
*/ */
package org.dspace.xoai.util; package org.dspace.xoai.util;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.LogManager; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.dspace.app.util.Util; import org.dspace.app.util.Util;
import org.dspace.core.Constants; import org.dspace.core.Constants;
import java.io.UnsupportedEncodingException;
/** /**
*
* @author Lyncode Development Team (dspace at lyncode dot com) * @author Lyncode Development Team (dspace at lyncode dot com)
*/ */
public class URLUtils public class URLUtils {
{
private static Logger log = LogManager.getLogger(URLUtils.class); private static Logger log = LogManager.getLogger(URLUtils.class);
public static String encode (String value) { /**
try * Default constructor
{ */
return Util.encodeBitstreamName(value, Constants.DEFAULT_ENCODING); private URLUtils() { }
} public static String encode(String value) {
catch (UnsupportedEncodingException e) try {
{ return Util.encodeBitstreamName(value, Constants.DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
log.warn(e.getMessage(), e); log.warn(e.getMessage(), e);
return value; return value;
} }

View File

@@ -8,36 +8,34 @@
http://www.dspace.org/license/ http://www.dspace.org/license/
--> -->
<beans <beans
xmlns="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">
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">
<!-- Acquires the DSpace Utility Class with initialized Service Manager --> <!-- Acquires the DSpace Utility Class with initialized Service Manager -->
<bean id="dspace" class="org.dspace.utils.DSpace"/> <bean id="dspace" class="org.dspace.utils.DSpace"/>
<!-- Acquires reference to EventService --> <!-- Acquires reference to EventService -->
<bean id="dspace.eventService" factory-bean="dspace" factory-method="getEventService"/> <bean id="dspace.eventService" factory-bean="dspace" factory-method="getEventService"/>
<!-- Inject the Default LoggerUsageEventListener into the EventService --> <!-- Inject the Default LoggerUsageEventListener into the EventService -->
<bean class="org.dspace.usage.LoggerUsageEventListener"> <bean class="org.dspace.usage.LoggerUsageEventListener">
<property name="eventService" > <property name="eventService">
<ref bean="dspace.eventService"/> <ref bean="dspace.eventService"/>
</property> </property>
</bean> </bean>
<!-- Inject the SolrLoggerUsageEventListener into the EventService --> <!-- Inject the SolrLoggerUsageEventListener into the EventService -->
<bean class="org.dspace.statistics.SolrLoggerUsageEventListener"> <bean class="org.dspace.statistics.SolrLoggerUsageEventListener">
<property name="eventService" > <property name="eventService">
<ref bean="dspace.eventService"/> <ref bean="dspace.eventService"/>
</property> </property>
</bean> </bean>
<!-- Google Analytics recording --> <!-- Google Analytics recording -->
<bean class="org.dspace.google.GoogleRecorderEventListener"> <bean class="org.dspace.google.GoogleRecorderEventListener">
<property name="eventService" > <property name="eventService">
<ref bean="dspace.eventService"/> <ref bean="dspace.eventService"/>
</property> </property>
</bean> </bean>

View File

@@ -9,16 +9,16 @@
--> -->
<web-app id="XOAILynCode" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" <web-app id="XOAILynCode" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>XOAI Data Provider</display-name>
<context-param> <display-name>XOAI Data Provider</display-name>
<description>The location of the DSpace home directory</description>
<param-name>dspace.dir</param-name> <context-param>
<param-value>${dspace.dir}</param-value> <description>The location of the DSpace home directory</description>
</context-param> <param-name>dspace.dir</param-name>
<param-value>${dspace.dir}</param-value>
</context-param>
<!-- Location of root application context configs (to be loaded by ContextLoaderListener below) --> <!-- Location of root application context configs (to be loaded by ContextLoaderListener below) -->
@@ -36,7 +36,7 @@
<!-- Initializes the DSpace Kernel --> <!-- Initializes the DSpace Kernel -->
<listener> <listener>
<listener-class> <listener-class>
org.dspace.servicemanager.servlet.DSpaceKernelServletContextListener org.dspace.servicemanager.servlet.DSpaceKernelServletContextListener
</listener-class> </listener-class>
</listener> </listener>
@@ -50,7 +50,7 @@
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> </listener>
<servlet> <servlet>
<servlet-name>oai</servlet-name> <servlet-name>oai</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext

View File

@@ -7,9 +7,11 @@
*/ */
package org.dspace.xoai.tests; package org.dspace.xoai.tests;
import static org.mockito.Mockito.mock;
import org.dspace.xoai.services.api.FieldResolver;
import org.dspace.xoai.services.api.config.ConfigurationService; import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.context.ContextService; import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.FieldResolver;
import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver; import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver;
import org.dspace.xoai.services.impl.xoai.BaseDSpaceFilterResolver; import org.dspace.xoai.services.impl.xoai.BaseDSpaceFilterResolver;
import org.dspace.xoai.tests.helpers.stubs.StubbedConfigurationService; import org.dspace.xoai.tests.helpers.stubs.StubbedConfigurationService;
@@ -17,15 +19,13 @@ import org.dspace.xoai.tests.helpers.stubs.StubbedFieldResolver;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import static org.mockito.Mockito.mock;
@Configuration @Configuration
public class DSpaceBasicTestConfiguration { public class DSpaceBasicTestConfiguration {
private final StubbedFieldResolver stubbedFieldResolver = new StubbedFieldResolver(); private final StubbedFieldResolver stubbedFieldResolver = new StubbedFieldResolver();
@Bean @Bean
public DSpaceFilterResolver dSpaceFilterResolver () { public DSpaceFilterResolver dSpaceFilterResolver() {
return new BaseDSpaceFilterResolver(); return new BaseDSpaceFilterResolver();
} }
@@ -38,12 +38,12 @@ public class DSpaceBasicTestConfiguration {
} }
@Bean @Bean
public ContextService contextService () { public ContextService contextService() {
return mock(ContextService.class); return mock(ContextService.class);
} }
@Bean @Bean
public FieldResolver databaseService () { public FieldResolver databaseService() {
return stubbedFieldResolver; return stubbedFieldResolver;
} }
} }

View File

@@ -11,11 +11,11 @@ import com.lyncode.xoai.dataprovider.services.api.ItemRepository;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver; import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import com.lyncode.xoai.dataprovider.services.api.SetRepository; import com.lyncode.xoai.dataprovider.services.api.SetRepository;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.cache.XOAICacheService; import org.dspace.xoai.services.api.cache.XOAICacheService;
import org.dspace.xoai.services.api.config.XOAIManagerResolver; import org.dspace.xoai.services.api.config.XOAIManagerResolver;
import org.dspace.xoai.services.api.context.ContextService; import org.dspace.xoai.services.api.context.ContextService;
import org.dspace.xoai.services.api.context.ContextServiceException; import org.dspace.xoai.services.api.context.ContextServiceException;
import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.xoai.IdentifyResolver; import org.dspace.xoai.services.api.xoai.IdentifyResolver;
import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver; import org.dspace.xoai.services.api.xoai.ItemRepositoryResolver;
import org.dspace.xoai.services.api.xoai.SetRepositoryResolver; import org.dspace.xoai.services.api.xoai.SetRepositoryResolver;
@@ -82,7 +82,8 @@ public class DSpaceTestConfiguration extends WebMvcConfigurerAdapter {
private StubbedSetRepository setRepository = new StubbedSetRepository(); private StubbedSetRepository setRepository = new StubbedSetRepository();
@Bean StubbedSetRepository setRepository () { @Bean
StubbedSetRepository setRepository() {
return setRepository; return setRepository;
} }
@@ -99,8 +100,9 @@ public class DSpaceTestConfiguration extends WebMvcConfigurerAdapter {
} }
}; };
} }
@Bean @Bean
public SetRepositoryResolver setRepositoryResolver () { public SetRepositoryResolver setRepositoryResolver() {
return new SetRepositoryResolver() { return new SetRepositoryResolver() {
@Override @Override
public SetRepository getSetRepository() throws ContextServiceException { public SetRepository getSetRepository() throws ContextServiceException {
@@ -108,13 +110,14 @@ public class DSpaceTestConfiguration extends WebMvcConfigurerAdapter {
} }
}; };
} }
@Bean @Bean
public IdentifyResolver identifyResolver () { public IdentifyResolver identifyResolver() {
return new DSpaceIdentifyResolver(); return new DSpaceIdentifyResolver();
} }
@Bean @Bean
public EarliestDateResolver earliestDateResolver () { public EarliestDateResolver earliestDateResolver() {
return new StubbedEarliestDateResolver(); return new StubbedEarliestDateResolver();
} }
} }

View File

@@ -7,16 +7,16 @@
*/ */
package org.dspace.xoai.tests.helpers; package org.dspace.xoai.tests.helpers;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.mock.web.MockHttpServletRequest;
public class HttpRequestBuilder { public class HttpRequestBuilder {
private MockHttpServletRequest request = new MockHttpServletRequest(); private MockHttpServletRequest request = new MockHttpServletRequest();
public HttpRequestBuilder withUrl (String url) { public HttpRequestBuilder withUrl(String url) {
try { try {
URI uri = new URI(url); URI uri = new URI(url);
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
@@ -25,12 +25,12 @@ public class HttpRequestBuilder {
return this; return this;
} }
public HttpRequestBuilder usingGetMethod () { public HttpRequestBuilder usingGetMethod() {
request.setMethod("GET"); request.setMethod("GET");
return this; return this;
} }
public HttpServletRequest build () { public HttpServletRequest build() {
return request; return request;
} }

View File

@@ -8,13 +8,15 @@
package org.dspace.xoai.tests.helpers; package org.dspace.xoai.tests.helpers;
public class SyntacticSugar { public class SyntacticSugar {
public static <T> T given (T elem) { public static <T> T given(T elem) {
return elem; return elem;
} }
public static <T> T the (T elem) {
public static <T> T the(T elem) {
return elem; return elem;
} }
public static <T> T and (T elem) {
public static <T> T and(T elem) {
return elem; return elem;
} }
} }

View File

@@ -7,6 +7,16 @@
*/ */
package org.dspace.xoai.tests.helpers.stubs; package org.dspace.xoai.tests.helpers.stubs;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
import java.io.ByteArrayOutputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import com.lyncode.xoai.builders.dataprovider.ElementBuilder; import com.lyncode.xoai.builders.dataprovider.ElementBuilder;
import com.lyncode.xoai.builders.dataprovider.MetadataBuilder; import com.lyncode.xoai.builders.dataprovider.MetadataBuilder;
import com.lyncode.xoai.dataprovider.exceptions.MetadataBindException; import com.lyncode.xoai.dataprovider.exceptions.MetadataBindException;
@@ -16,16 +26,6 @@ import com.lyncode.xoai.dataprovider.xml.xoai.Metadata;
import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputDocument;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayOutputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.lyncode.xoai.dataprovider.core.Granularity.Second;
public class ItemRepositoryBuilder { public class ItemRepositoryBuilder {
private SolrServer solrServer; private SolrServer solrServer;
@@ -33,7 +33,7 @@ public class ItemRepositoryBuilder {
this.solrServer = solrServer; this.solrServer = solrServer;
} }
public ItemRepositoryBuilder withItem (DSpaceItemBuilder builder) { public ItemRepositoryBuilder withItem(DSpaceItemBuilder builder) {
try { try {
solrServer.add(index(builder)); solrServer.add(index(builder));
solrServer.commit(); solrServer.commit();
@@ -44,7 +44,8 @@ public class ItemRepositoryBuilder {
} }
private SolrInputDocument index(DSpaceItemBuilder item) throws SQLException, MetadataBindException, ParseException, XMLStreamException, WritingXmlException { private SolrInputDocument index(DSpaceItemBuilder item)
throws SQLException, MetadataBindException, ParseException, XMLStreamException, WritingXmlException {
SolrInputDocument doc = new SolrInputDocument(); SolrInputDocument doc = new SolrInputDocument();
doc.addField("item.id", item.getId()); doc.addField("item.id", item.getId());
@@ -54,11 +55,13 @@ public class ItemRepositoryBuilder {
doc.addField("item.handle", item.getHandle()); doc.addField("item.handle", item.getHandle());
doc.addField("item.deleted", item.isDeleted()); doc.addField("item.deleted", item.isDeleted());
for (String col : item.getCollections()) for (String col : item.getCollections()) {
doc.addField("item.collections", col); doc.addField("item.collections", col);
}
for (String col : item.getCommunities()) for (String col : item.getCommunities()) {
doc.addField("item.communities", col); doc.addField("item.communities", col);
}
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
XmlOutputContext context = XmlOutputContext.emptyContext(out, Second); XmlOutputContext context = XmlOutputContext.emptyContext(out, Second);
@@ -82,38 +85,42 @@ public class ItemRepositoryBuilder {
private boolean aPublic = true; private boolean aPublic = true;
public DSpaceItemBuilder withLastModifiedDate (Date lastModifiedDate) { public DSpaceItemBuilder withLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate; this.lastModifiedDate = lastModifiedDate;
return this; return this;
} }
public DSpaceItemBuilder withCollection (String colName) { public DSpaceItemBuilder withCollection(String colName) {
collections.add(colName); collections.add(colName);
return this; return this;
} }
public DSpaceItemBuilder withCommunity (String comName) {
public DSpaceItemBuilder withCommunity(String comName) {
communities.add(comName); communities.add(comName);
return this; return this;
} }
public DSpaceItemBuilder whichSsPublic () {
public DSpaceItemBuilder whichSsPublic() {
aPublic = true; aPublic = true;
return this; return this;
} }
public DSpaceItemBuilder whichSsPrivate () {
public DSpaceItemBuilder whichSsPrivate() {
aPublic = false; aPublic = false;
return this; return this;
} }
public DSpaceItemBuilder whichIsDeleted () { public DSpaceItemBuilder whichIsDeleted() {
this.deleted = true; this.deleted = true;
return this; return this;
} }
public DSpaceItemBuilder whichIsNotDeleted () {
public DSpaceItemBuilder whichIsNotDeleted() {
this.deleted = false; this.deleted = false;
return this; return this;
} }
public DSpaceItemBuilder withMetadata (String schema, String element, String value) { public DSpaceItemBuilder withMetadata(String schema, String element, String value) {
metadataBuilder.withElement(new ElementBuilder().withName(schema).withField(element, value).build()); metadataBuilder.withElement(new ElementBuilder().withName(schema).withField(element, value).build());
return this; return this;
} }
@@ -122,17 +129,17 @@ public class ItemRepositoryBuilder {
return handle; return handle;
} }
public DSpaceItemBuilder withHandle (String handle) { public DSpaceItemBuilder withHandle(String handle) {
this.handle = handle; this.handle = handle;
return this; return this;
} }
public DSpaceItemBuilder withSubmitter (String submitter) { public DSpaceItemBuilder withSubmitter(String submitter) {
this.submitter = submitter; this.submitter = submitter;
return this; return this;
} }
public DSpaceItemBuilder withId (int id) { public DSpaceItemBuilder withId(int id) {
this.id = id; this.id = id;
return this; return this;
} }

View File

@@ -7,36 +7,36 @@
*/ */
package org.dspace.xoai.tests.helpers.stubs; package org.dspace.xoai.tests.helpers.stubs;
import org.dspace.xoai.services.api.config.ConfigurationService;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.dspace.xoai.services.api.config.ConfigurationService;
public class StubbedConfigurationService implements ConfigurationService { public class StubbedConfigurationService implements ConfigurationService {
private Map<String, Object> values = new HashMap<String, Object>(); private Map<String, Object> values = new HashMap<String, Object>();
public StubbedConfigurationService hasBooleanProperty (String key, boolean value) { public StubbedConfigurationService hasBooleanProperty(String key, boolean value) {
values.put(key, value); values.put(key, value);
return this; return this;
} }
public StubbedConfigurationService hasBooleanProperty (String module, String key, boolean value) { public StubbedConfigurationService hasBooleanProperty(String module, String key, boolean value) {
values.put(module + "." + key, value); values.put(module + "." + key, value);
return this; return this;
} }
public StubbedConfigurationService hasProperty (String key, String value) { public StubbedConfigurationService hasProperty(String key, String value) {
values.put(key, value); values.put(key, value);
return this; return this;
} }
public StubbedConfigurationService withoutProperty (String key) { public StubbedConfigurationService withoutProperty(String key) {
values.remove(key); values.remove(key);
return this; return this;
} }
public StubbedConfigurationService hasProperty (String module, String key, String value) { public StubbedConfigurationService hasProperty(String module, String key, String value) {
values.put(module + "." + key, value); values.put(module + "." + key, value);
return this; return this;
} }
@@ -54,7 +54,10 @@ public class StubbedConfigurationService implements ConfigurationService {
@Override @Override
public boolean getBooleanProperty(String module, String key, boolean defaultValue) { public boolean getBooleanProperty(String module, String key, boolean defaultValue) {
Boolean value = (Boolean) values.get(module + "." + key); Boolean value = (Boolean) values.get(module + "." + key);
if (value == null) return defaultValue; if (value == null) {
else return value; return defaultValue;
} else {
return value;
}
} }
} }

View File

@@ -7,17 +7,17 @@
*/ */
package org.dspace.xoai.tests.helpers.stubs; package org.dspace.xoai.tests.helpers.stubs;
import java.sql.SQLException;
import java.util.Date;
import org.dspace.core.Context; import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException; import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import org.dspace.xoai.services.api.EarliestDateResolver; import org.dspace.xoai.services.api.EarliestDateResolver;
import java.sql.SQLException;
import java.util.Date;
public class StubbedEarliestDateResolver implements EarliestDateResolver { public class StubbedEarliestDateResolver implements EarliestDateResolver {
private Date date = new Date(); private Date date = new Date();
public StubbedEarliestDateResolver is (Date date) { public StubbedEarliestDateResolver is(Date date) {
this.date = date; this.date = date;
return this; return this;
} }

View File

@@ -7,21 +7,23 @@
*/ */
package org.dspace.xoai.tests.helpers.stubs; package org.dspace.xoai.tests.helpers.stubs;
import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import org.dspace.xoai.services.api.FieldResolver;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.dspace.core.Context;
import org.dspace.xoai.exceptions.InvalidMetadataFieldException;
import org.dspace.xoai.services.api.FieldResolver;
public class StubbedFieldResolver implements FieldResolver { public class StubbedFieldResolver implements FieldResolver {
private Map<String, Integer> fieldsMap = new HashMap<String, Integer>(); private Map<String, Integer> fieldsMap = new HashMap<String, Integer>();
@Override @Override
public int getFieldID(Context context, String field) throws InvalidMetadataFieldException, SQLException { public int getFieldID(Context context, String field) throws InvalidMetadataFieldException, SQLException {
Integer integer = fieldsMap.get(field); Integer integer = fieldsMap.get(field);
if (integer == null) return -1; if (integer == null) {
return -1;
}
return integer; return integer;
} }

View File

@@ -7,15 +7,15 @@
*/ */
package org.dspace.xoai.tests.helpers.stubs; package org.dspace.xoai.tests.helpers.stubs;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
public class StubbedResourceResolver implements ResourceResolver { public class StubbedResourceResolver implements ResourceResolver {
private static TransformerFactory factory = TransformerFactory.newInstance(); private static TransformerFactory factory = TransformerFactory.newInstance();

View File

@@ -8,15 +8,15 @@
package org.dspace.xoai.tests.helpers.stubs; package org.dspace.xoai.tests.helpers.stubs;
import com.lyncode.xoai.dataprovider.core.ListSetsResult; import static java.lang.Math.min;
import com.lyncode.xoai.dataprovider.core.Set; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import com.lyncode.xoai.dataprovider.services.api.SetRepository;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static java.lang.Math.min; import com.lyncode.xoai.dataprovider.core.ListSetsResult;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import com.lyncode.xoai.dataprovider.core.Set;
import com.lyncode.xoai.dataprovider.services.api.SetRepository;
public class StubbedSetRepository implements SetRepository { public class StubbedSetRepository implements SetRepository {
private List<Set> sets = new ArrayList<Set>(); private List<Set> sets = new ArrayList<Set>();
@@ -29,15 +29,20 @@ public class StubbedSetRepository implements SetRepository {
@Override @Override
public ListSetsResult retrieveSets(int offset, int length) { public ListSetsResult retrieveSets(int offset, int length) {
if (offset > sets.size()) return new ListSetsResult(false, new ArrayList<Set>(), sets.size()); if (offset > sets.size()) {
return new ListSetsResult(offset+length < sets.size(), sets.subList(offset, min(offset + length, sets.size())), sets.size()); return new ListSetsResult(false, new ArrayList<Set>(), sets.size());
}
return new ListSetsResult(offset + length < sets.size(),
sets.subList(offset, min(offset + length, sets.size())), sets.size());
} }
@Override @Override
public boolean exists(String setSpec) { public boolean exists(String setSpec) {
for (Set set : sets) for (Set set : sets) {
if (set.getSetSpec().equals(setSpec)) if (set.getSetSpec().equals(setSpec)) {
return true; return true;
}
}
return false; return false;
} }
@@ -46,18 +51,21 @@ public class StubbedSetRepository implements SetRepository {
this.supports = true; this.supports = true;
return this; return this;
} }
public StubbedSetRepository doesNotSupportSets() { public StubbedSetRepository doesNotSupportSets() {
this.supports = false; this.supports = false;
return this; return this;
} }
public StubbedSetRepository withSet(String name, String spec) { public StubbedSetRepository withSet(String name, String spec) {
this.sets.add(new Set(spec, name)); this.sets.add(new Set(spec, name));
return this; return this;
} }
public StubbedSetRepository withRandomlyGeneratedSets(int number) { public StubbedSetRepository withRandomlyGeneratedSets(int number) {
for (int i=0;i<number;i++) for (int i = 0; i < number; i++) {
this.sets.add(new Set(randomAlphabetic(10), randomAlphabetic(10))); this.sets.add(new Set(randomAlphabetic(10), randomAlphabetic(10)));
}
return this; return this;
} }

View File

@@ -17,13 +17,14 @@ import org.dspace.xoai.services.api.xoai.DSpaceFilterResolver;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
public class StubbedXOAIManagerResolver implements XOAIManagerResolver { public class StubbedXOAIManagerResolver implements XOAIManagerResolver {
@Autowired ResourceResolver resourceResolver; @Autowired
ResourceResolver resourceResolver;
@Autowired @Autowired
DSpaceFilterResolver filterResolver; DSpaceFilterResolver filterResolver;
private Configuration builder = new Configuration(); private Configuration builder = new Configuration();
public Configuration configuration () { public Configuration configuration() {
return builder; return builder;
} }

View File

@@ -7,6 +7,13 @@
*/ */
package org.dspace.xoai.tests.integration.xoai; package org.dspace.xoai.tests.integration.xoai;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.xpath.XPathExpressionException;
import com.lyncode.builder.MapBuilder; import com.lyncode.builder.MapBuilder;
import com.lyncode.xoai.dataprovider.services.api.ResourceResolver; import com.lyncode.xoai.dataprovider.services.api.ResourceResolver;
import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider; import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider;
@@ -14,12 +21,18 @@ import com.lyncode.xoai.dataprovider.xml.xoaiconfig.Configuration;
import com.lyncode.xoai.dataprovider.xml.xoaiconfig.FormatConfiguration; import com.lyncode.xoai.dataprovider.xml.xoaiconfig.FormatConfiguration;
import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServer;
import org.dspace.xoai.controller.DSpaceOAIDataProvider; import org.dspace.xoai.controller.DSpaceOAIDataProvider;
import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.config.XOAIManagerResolver;
import org.dspace.xoai.services.api.EarliestDateResolver; import org.dspace.xoai.services.api.EarliestDateResolver;
import org.dspace.xoai.services.api.FieldResolver; import org.dspace.xoai.services.api.FieldResolver;
import org.dspace.xoai.services.api.config.ConfigurationService;
import org.dspace.xoai.services.api.config.XOAIManagerResolver;
import org.dspace.xoai.tests.DSpaceTestConfiguration; import org.dspace.xoai.tests.DSpaceTestConfiguration;
import org.dspace.xoai.tests.helpers.stubs.*; import org.dspace.xoai.tests.helpers.stubs.ItemRepositoryBuilder;
import org.dspace.xoai.tests.helpers.stubs.StubbedConfigurationService;
import org.dspace.xoai.tests.helpers.stubs.StubbedEarliestDateResolver;
import org.dspace.xoai.tests.helpers.stubs.StubbedFieldResolver;
import org.dspace.xoai.tests.helpers.stubs.StubbedResourceResolver;
import org.dspace.xoai.tests.helpers.stubs.StubbedSetRepository;
import org.dspace.xoai.tests.helpers.stubs.StubbedXOAIManagerResolver;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -33,20 +46,14 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.XpathResultMatchers; import org.springframework.test.web.servlet.result.XpathResultMatchers;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import javax.xml.xpath.XPathExpressionException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = { DSpaceTestConfiguration.class, DSpaceOAIDataProvider.class }) @ContextConfiguration(classes = {DSpaceTestConfiguration.class, DSpaceOAIDataProvider.class})
public abstract class AbstractDSpaceTest { public abstract class AbstractDSpaceTest {
private static BaseDateProvider baseDateProvider = new BaseDateProvider(); private static BaseDateProvider baseDateProvider = new BaseDateProvider();
@Autowired WebApplicationContext wac; @Autowired
WebApplicationContext wac;
private MockMvc mockMvc; private MockMvc mockMvc;
private StubbedXOAIManagerResolver xoaiManagerResolver; private StubbedXOAIManagerResolver xoaiManagerResolver;
@@ -69,7 +76,7 @@ public abstract class AbstractDSpaceTest {
resourceResolver = (StubbedResourceResolver) this.wac.getBean(ResourceResolver.class); resourceResolver = (StubbedResourceResolver) this.wac.getBean(ResourceResolver.class);
xoaiManagerResolver.configuration(); xoaiManagerResolver.configuration();
} }
@After @After
public void teardown() { public void teardown() {
// Nullify all resources so that JUnit will clean them up // Nullify all resources so that JUnit will clean them up
@@ -84,30 +91,32 @@ public abstract class AbstractDSpaceTest {
} }
protected MockMvc againstTheDataProvider() { protected MockMvc againstTheDataProvider() {
if (this.mockMvc == null) this.mockMvc = webAppContextSetup(this.wac).build(); if (this.mockMvc == null) {
this.mockMvc = webAppContextSetup(this.wac).build();
}
return this.mockMvc; return this.mockMvc;
} }
protected Configuration theConfiguration () { protected Configuration theConfiguration() {
return xoaiManagerResolver.configuration(); return xoaiManagerResolver.configuration();
} }
protected StubbedConfigurationService theDSpaceConfiguration () { protected StubbedConfigurationService theDSpaceConfiguration() {
return configurationService; return configurationService;
} }
protected StubbedFieldResolver theDatabase () { protected StubbedFieldResolver theDatabase() {
return databaseService; return databaseService;
} }
protected StubbedEarliestDateResolver theEarlistEarliestDate () { protected StubbedEarliestDateResolver theEarlistEarliestDate() {
return earliestDateResolver; return earliestDateResolver;
} }
protected XpathResultMatchers oaiXPath(String xpath) throws XPathExpressionException { protected XpathResultMatchers oaiXPath(String xpath) throws XPathExpressionException {
return MockMvcResultMatchers.xpath(this.replaceXpath(xpath), new MapBuilder<String, String>() return MockMvcResultMatchers.xpath(this.replaceXpath(xpath), new MapBuilder<String, String>()
.withPair("o", "http://www.openarchives.org/OAI/2.0/") .withPair("o", "http://www.openarchives.org/OAI/2.0/")
.build()); .build());
} }
private String replaceXpath(String xpath) { private String replaceXpath(String xpath) {
@@ -116,22 +125,25 @@ public abstract class AbstractDSpaceTest {
Pattern pattern = Pattern.compile("/[^/]+"); Pattern pattern = Pattern.compile("/[^/]+");
Matcher matcher = pattern.matcher(xpath); Matcher matcher = pattern.matcher(xpath);
while (matcher.find()) { while (matcher.find()) {
if (matcher.start() > offset) newXpath += xpath.substring(offset, matcher.start()); if (matcher.start() > offset) {
if (!matcher.group().contains(":") && !matcher.group().startsWith("/@")) newXpath += xpath.substring(offset, matcher.start());
}
if (!matcher.group().contains(":") && !matcher.group().startsWith("/@")) {
newXpath += "/o:" + matcher.group().substring(1); newXpath += "/o:" + matcher.group().substring(1);
else } else {
newXpath += matcher.group(); newXpath += matcher.group();
}
offset = matcher.end() + 1; offset = matcher.end() + 1;
} }
return newXpath; return newXpath;
} }
protected String representationOfDate (Date date) { protected String representationOfDate(Date date) {
return baseDateProvider.format(date); return baseDateProvider.format(date);
} }
protected StubbedSetRepository theSetRepository () { protected StubbedSetRepository theSetRepository() {
return setRepository; return setRepository;
} }
@@ -166,8 +178,9 @@ public abstract class AbstractDSpaceTest {
private ItemRepositoryBuilder itemRepositoryBuilder; private ItemRepositoryBuilder itemRepositoryBuilder;
public ItemRepositoryBuilder theItemRepository() { public ItemRepositoryBuilder theItemRepository() {
if (itemRepositoryBuilder == null) if (itemRepositoryBuilder == null) {
itemRepositoryBuilder = new ItemRepositoryBuilder(solrServer); itemRepositoryBuilder = new ItemRepositoryBuilder(solrServer);
}
return itemRepositoryBuilder; return itemRepositoryBuilder;
} }
} }

View File

@@ -7,16 +7,16 @@
*/ */
package org.dspace.xoai.tests.integration.xoai; package org.dspace.xoai.tests.integration.xoai;
import org.junit.Test;
import java.util.Date;
import static org.dspace.xoai.tests.helpers.SyntacticSugar.and; import static org.dspace.xoai.tests.helpers.SyntacticSugar.and;
import static org.dspace.xoai.tests.helpers.SyntacticSugar.given; import static org.dspace.xoai.tests.helpers.SyntacticSugar.given;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Date;
import org.junit.Test;
public class IdentifyTest extends AbstractDSpaceTest { public class IdentifyTest extends AbstractDSpaceTest {
public static final Date EARLIEST_DATE = new Date(); public static final Date EARLIEST_DATE = new Date();
@@ -24,26 +24,27 @@ public class IdentifyTest extends AbstractDSpaceTest {
@Test @Test
public void requestForIdentifyWithoutRequiredConfigurationAdminEmailSetShouldFail() throws Exception { public void requestForIdentifyWithoutRequiredConfigurationAdminEmailSetShouldFail() throws Exception {
given(theDSpaceConfiguration() given(theDSpaceConfiguration()
.withoutProperty("mail.admin")); .withoutProperty("mail.admin"));
and(given(theConfiguration().withContextConfigurations(aContext("request")))); and(given(theConfiguration().withContextConfigurations(aContext("request"))));
againstTheDataProvider().perform(get("/request?verb=Identify")) againstTheDataProvider().perform(get("/request?verb=Identify"))
.andExpect(status().isInternalServerError()); .andExpect(status().isInternalServerError());
} }
@Test @Test
public void requestForIdentifyShouldReturnTheConfiguredValues() throws Exception { public void requestForIdentifyShouldReturnTheConfiguredValues() throws Exception {
given(theDSpaceConfiguration() given(theDSpaceConfiguration()
.hasProperty("dspace.name", "Test") .hasProperty("dspace.name", "Test")
.hasProperty("mail.admin", "test@test.com")); .hasProperty("mail.admin", "test@test.com"));
and(given(theEarlistEarliestDate().is(EARLIEST_DATE))); and(given(theEarlistEarliestDate().is(EARLIEST_DATE)));
and(given(theConfiguration().withContextConfigurations(aContext("request")))); and(given(theConfiguration().withContextConfigurations(aContext("request"))));
againstTheDataProvider().perform(get("/request?verb=Identify")) againstTheDataProvider().perform(get("/request?verb=Identify"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(oaiXPath("//repositoryName").string("Test")) .andExpect(oaiXPath("//repositoryName").string("Test"))
.andExpect(oaiXPath("//adminEmail").string("test@test.com")) .andExpect(oaiXPath("//adminEmail").string("test@test.com"))
.andExpect(oaiXPath("//earliestDatestamp").string(is(representationOfDate(EARLIEST_DATE)))); .andExpect(
oaiXPath("//earliestDatestamp").string(is(representationOfDate(EARLIEST_DATE))));
} }
} }

View File

@@ -7,8 +7,6 @@
*/ */
package org.dspace.xoai.tests.integration.xoai; package org.dspace.xoai.tests.integration.xoai;
import org.junit.Test;
import static org.dspace.xoai.tests.helpers.SyntacticSugar.and; import static org.dspace.xoai.tests.helpers.SyntacticSugar.and;
import static org.dspace.xoai.tests.helpers.SyntacticSugar.given; import static org.dspace.xoai.tests.helpers.SyntacticSugar.given;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.is;
@@ -16,50 +14,52 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
public class ListSetsTest extends AbstractDSpaceTest { public class ListSetsTest extends AbstractDSpaceTest {
@Test @Test
public void listSetsWithLessSetsThenMaxSetsPerPage () throws Exception { public void listSetsWithLessSetsThenMaxSetsPerPage() throws Exception {
given(theConfiguration() given(theConfiguration()
.withMaxListSetsSize(100) .withMaxListSetsSize(100)
.withContextConfigurations(aContext("request"))); .withContextConfigurations(aContext("request")));
and(given(theSetRepository() and(given(theSetRepository()
.doesSupportSets() .doesSupportSets()
.withSet("name", "spec"))); .withSet("name", "spec")));
againstTheDataProvider().perform(get("/request?verb=ListSets")) againstTheDataProvider().perform(get("/request?verb=ListSets"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andDo(print()) .andDo(print())
.andExpect(responseDate().exists()) .andExpect(responseDate().exists())
.andExpect(verb(is("ListSets"))) .andExpect(verb(is("ListSets")))
.andExpect(oaiXPath("//set").nodeCount(1)) .andExpect(oaiXPath("//set").nodeCount(1))
.andExpect(oaiXPath("//set/setSpec").string("spec")) .andExpect(oaiXPath("//set/setSpec").string("spec"))
.andExpect(oaiXPath("//set/setName").string("name")) .andExpect(oaiXPath("//set/setName").string("name"))
.andExpect(resumptionToken().doesNotExist()); .andExpect(resumptionToken().doesNotExist());
} }
@Test @Test
public void listSetsWithMoreSetsThenMaxSetsPerPage () throws Exception { public void listSetsWithMoreSetsThenMaxSetsPerPage() throws Exception {
given(theConfiguration() given(theConfiguration()
.withMaxListSetsSize(10) .withMaxListSetsSize(10)
.withContextConfigurations(aContext("request"))); .withContextConfigurations(aContext("request")));
and(given(theSetRepository() and(given(theSetRepository()
.doesSupportSets() .doesSupportSets()
.withRandomlyGeneratedSets(20))); .withRandomlyGeneratedSets(20)));
againstTheDataProvider().perform(get("/request?verb=ListSets")) againstTheDataProvider().perform(get("/request?verb=ListSets"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(responseDate().exists()) .andExpect(responseDate().exists())
.andExpect(verb(is("ListSets"))) .andExpect(verb(is("ListSets")))
.andExpect(oaiXPath("//set").nodeCount(10)) .andExpect(oaiXPath("//set").nodeCount(10))
.andExpect(resumptionToken().string("////10")) .andExpect(resumptionToken().string("////10"))
.andExpect(oaiXPath("//resumptionToken/@completeListSize").number(Double.valueOf(20))); .andExpect(oaiXPath("//resumptionToken/@completeListSize").number(Double.valueOf(20)));
and(againstTheDataProvider().perform(get("/request?verb=ListSets&resumptionToken=////10")) and(againstTheDataProvider().perform(get("/request?verb=ListSets&resumptionToken=////10"))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(responseDate().exists()) .andExpect(responseDate().exists())
.andExpect(verb(is("ListSets"))) .andExpect(verb(is("ListSets")))
.andExpect(oaiXPath("//set").nodeCount(10)) .andExpect(oaiXPath("//set").nodeCount(10))
.andExpect(resumptionToken().string(""))); .andExpect(resumptionToken().string("")));
} }
} }

View File

@@ -7,29 +7,29 @@
*/ */
package org.dspace.xoai.tests.integration.xoai; package org.dspace.xoai.tests.integration.xoai;
import org.junit.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
public class OAIContextTest extends AbstractDSpaceTest { public class OAIContextTest extends AbstractDSpaceTest {
public static final String ROOT_URL = "/"; public static final String ROOT_URL = "/";
@Test @Test
public void requestToRootShouldGiveListOfContextsWithBadRequestError() throws Exception { public void requestToRootShouldGiveListOfContextsWithBadRequestError() throws Exception {
againstTheDataProvider().perform(get(ROOT_URL)) againstTheDataProvider().perform(get(ROOT_URL))
.andDo(print()) .andDo(print())
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(model().attributeExists("contexts")); .andExpect(model().attributeExists("contexts"));
} }
@Test @Test
public void requestForUnknownContextShouldGiveListOfContextsWithBadRequestError() throws Exception { public void requestForUnknownContextShouldGiveListOfContextsWithBadRequestError() throws Exception {
againstTheDataProvider().perform(get("/unexistentContext")) againstTheDataProvider().perform(get("/unexistentContext"))
.andDo(print()) .andDo(print())
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(model().attributeExists("contexts")); .andExpect(model().attributeExists("contexts"));
} }
} }

View File

@@ -8,31 +8,31 @@
package org.dspace.xoai.tests.integration.xoai; package org.dspace.xoai.tests.integration.xoai;
import com.lyncode.xoai.util.XSLPipeline;
import org.junit.Test;
import org.parboiled.common.FileUtils;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import static com.lyncode.test.matchers.xml.XPathMatchers.xPath; import static com.lyncode.test.matchers.xml.XPathMatchers.xPath;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import java.io.InputStream;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import com.lyncode.xoai.util.XSLPipeline;
import org.junit.Test;
import org.parboiled.common.FileUtils;
public class PipelineTest { public class PipelineTest {
private static TransformerFactory factory = TransformerFactory.newInstance(); private static TransformerFactory factory = TransformerFactory.newInstance();
@Test @Test
public void pipelineTest () throws Exception { public void pipelineTest() throws Exception {
InputStream input = PipelineTest.class.getClassLoader().getResourceAsStream("item.xml"); InputStream input = PipelineTest.class.getClassLoader().getResourceAsStream("item.xml");
InputStream xslt = PipelineTest.class.getClassLoader().getResourceAsStream("oai_dc.xsl"); InputStream xslt = PipelineTest.class.getClassLoader().getResourceAsStream("oai_dc.xsl");
String output = FileUtils.readAllText(new XSLPipeline(input, true) String output = FileUtils.readAllText(new XSLPipeline(input, true)
.apply(factory.newTransformer(new StreamSource(xslt))) .apply(factory.newTransformer(new StreamSource(xslt)))
.getTransformed()); .getTransformed());
assertThat(output, xPath("/oai_dc:dc/dc:title", equalTo("Teste"))); assertThat(output, xPath("/oai_dc:dc/dc:title", equalTo("Teste")));
input.close(); input.close();
input = null; input = null;
xslt.close(); xslt.close();

View File

@@ -7,25 +7,25 @@
*/ */
package org.dspace.xoai.tests.stylesheets; package org.dspace.xoai.tests.stylesheets;
import org.apache.commons.io.IOUtils;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.IOUtils;
public abstract class AbstractXSLTest { public abstract class AbstractXSLTest {
private static final TransformerFactory factory = TransformerFactory.newInstance(); private static final TransformerFactory factory = TransformerFactory.newInstance();
protected TransformBuilder apply (String xslLocation) throws Exception { protected TransformBuilder apply(String xslLocation) throws Exception {
return new TransformBuilder(xslLocation); return new TransformBuilder(xslLocation);
} }
protected InputStream resource (String location) throws Exception { protected InputStream resource(String location) throws Exception {
return print(this.getClass().getClassLoader().getResourceAsStream(location)); return print(this.getClass().getClassLoader().getResourceAsStream(location));
} }
@@ -42,7 +42,8 @@ public abstract class AbstractXSLTest {
private final Transformer transformer; private final Transformer transformer;
public TransformBuilder(String xslLocation) throws Exception { public TransformBuilder(String xslLocation) throws Exception {
this.transformer = factory.newTransformer(new StreamSource(new File("../dspace/config/crosswalks/oai/metadataFormats", xslLocation))); this.transformer = factory.newTransformer(
new StreamSource(new File("../dspace/config/crosswalks/oai/metadataFormats", xslLocation)));
} }
public String to(InputStream input) throws Exception { public String to(InputStream input) throws Exception {

View File

@@ -7,14 +7,14 @@
*/ */
package org.dspace.xoai.tests.stylesheets; package org.dspace.xoai.tests.stylesheets;
import org.dspace.xoai.tests.support.XmlMatcherBuilder;
import org.junit.Test;
import static org.dspace.xoai.tests.support.XmlMatcherBuilder.xml; import static org.dspace.xoai.tests.support.XmlMatcherBuilder.xml;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is; import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsEqual.equalTo;
import org.dspace.xoai.tests.support.XmlMatcherBuilder;
import org.junit.Test;
public class QDCXslTest extends AbstractXSLTest { public class QDCXslTest extends AbstractXSLTest {
@Test @Test
@@ -24,11 +24,11 @@ public class QDCXslTest extends AbstractXSLTest {
assertThat(result, is(qdc().withXPath("//dc:title", equalTo("Test Webpage")))); assertThat(result, is(qdc().withXPath("//dc:title", equalTo("Test Webpage"))));
} }
private XmlMatcherBuilder qdc () { private XmlMatcherBuilder qdc() {
return xml() return xml()
.withNamespace("dqc", "http://dspace.org/qualifieddc/") .withNamespace("dqc", "http://dspace.org/qualifieddc/")
.withNamespace("dcterms", "http://purl.org/dc/terms/") .withNamespace("dcterms", "http://purl.org/dc/terms/")
.withNamespace("dc", "http://purl.org/dc/elements/1.1/") .withNamespace("dc", "http://purl.org/dc/elements/1.1/")
; ;
} }
} }

View File

@@ -7,14 +7,14 @@
*/ */
package org.dspace.xoai.tests.support; package org.dspace.xoai.tests.support;
import java.util.ArrayList;
import java.util.Collection;
import org.hamcrest.BaseMatcher; import org.hamcrest.BaseMatcher;
import org.hamcrest.Description; import org.hamcrest.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.core.AllOf; import org.hamcrest.core.AllOf;
import java.util.ArrayList;
import java.util.Collection;
public class MatcherBuilder<M extends MatcherBuilder, T> extends BaseMatcher<T> { public class MatcherBuilder<M extends MatcherBuilder, T> extends BaseMatcher<T> {
private final Collection<Matcher<? super T>> matchers = new ArrayList<>(); private final Collection<Matcher<? super T>> matchers = new ArrayList<>();
@@ -32,7 +32,7 @@ public class MatcherBuilder<M extends MatcherBuilder, T> extends BaseMatcher<T>
description.appendDescriptionOf(matcher()); description.appendDescriptionOf(matcher());
} }
protected M with (Matcher<? super T> matcher) { protected M with(Matcher<? super T> matcher) {
matchers.add(matcher); matchers.add(matcher);
return (M) this; return (M) this;
} }

View File

@@ -7,18 +7,22 @@
*/ */
package org.dspace.xoai.tests.support; package org.dspace.xoai.tests.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
import org.hamcrest.Description; import org.hamcrest.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher; import org.hamcrest.TypeSafeMatcher;
import org.xmlmatchers.XmlMatchers; import org.xmlmatchers.XmlMatchers;
import org.xmlmatchers.transform.StringSource; import org.xmlmatchers.transform.StringSource;
import javax.xml.namespace.NamespaceContext;
import java.util.*;
public class XmlMatcherBuilder extends MatcherBuilder<XmlMatcherBuilder, String> { public class XmlMatcherBuilder extends MatcherBuilder<XmlMatcherBuilder, String> {
public static XmlMatcherBuilder xml () { public static XmlMatcherBuilder xml() {
return new XmlMatcherBuilder(); return new XmlMatcherBuilder();
} }
@@ -63,8 +67,8 @@ public class XmlMatcherBuilder extends MatcherBuilder<XmlMatcherBuilder, String>
@Override @Override
protected boolean matchesSafely(String item) { protected boolean matchesSafely(String item) {
return XmlMatchers return XmlMatchers
.hasXPath(xPath, namespaces, subMatcher) .hasXPath(xPath, namespaces, subMatcher)
.matches(StringSource.toSource(item)); .matches(StringSource.toSource(item));
} }
@Override @Override
@@ -74,7 +78,7 @@ public class XmlMatcherBuilder extends MatcherBuilder<XmlMatcherBuilder, String>
}); });
} }
public XmlMatcherBuilder withNamespace (String prefix, String uri) { public XmlMatcherBuilder withNamespace(String prefix, String uri) {
namespaces.with(prefix, uri); namespaces.with(prefix, uri);
return this; return this;
} }
@@ -91,16 +95,20 @@ public class XmlMatcherBuilder extends MatcherBuilder<XmlMatcherBuilder, String>
public String getPrefix(String namespaceURI) { public String getPrefix(String namespaceURI) {
Iterator<String> prefixes = getPrefixes(namespaceURI); Iterator<String> prefixes = getPrefixes(namespaceURI);
if (!prefixes.hasNext()) return null; if (!prefixes.hasNext()) {
else return prefixes.next(); return null;
} else {
return prefixes.next();
}
} }
@Override @Override
public Iterator getPrefixes(String namespaceURI) { public Iterator getPrefixes(String namespaceURI) {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
for (Map.Entry<String, String> stringStringEntry : namespace.entrySet()) { for (Map.Entry<String, String> stringStringEntry : namespace.entrySet()) {
if (stringStringEntry.getValue().equals(namespaceURI)) if (stringStringEntry.getValue().equals(namespaceURI)) {
list.add(stringStringEntry.getKey()); list.add(stringStringEntry.getKey());
}
} }
return list.iterator(); return list.iterator();

View File

@@ -7,6 +7,10 @@
*/ */
package org.dspace.xoai.tests.unit.services.impl; package org.dspace.xoai.tests.unit.services.impl;
import static org.mockito.Mockito.mock;
import java.util.Date;
import com.lyncode.builder.DateBuilder; import com.lyncode.builder.DateBuilder;
import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider; import com.lyncode.xoai.dataprovider.services.impl.BaseDateProvider;
import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.client.solrj.util.ClientUtils;
@@ -21,10 +25,6 @@ import org.junit.Before;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Date;
import static org.mockito.Mockito.mock;
public abstract class AbstractQueryResolverTest { public abstract class AbstractQueryResolverTest {
private final BaseDateProvider baseDateProvider = new BaseDateProvider(); private final BaseDateProvider baseDateProvider = new BaseDateProvider();
protected HandleResolver handleResolver = mock(HandleResolver.class); protected HandleResolver handleResolver = mock(HandleResolver.class);
@@ -32,10 +32,10 @@ public abstract class AbstractQueryResolverTest {
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
@Before @Before
public void setUp () { public void setUp() {
applicationContext = new AnnotationConfigApplicationContext(DSpaceBasicTestConfiguration.class); applicationContext = new AnnotationConfigApplicationContext(DSpaceBasicTestConfiguration.class);
} }
@After @After
public void tearDown() { public void tearDown() {
//Nullify all resoruces so that JUnit cleans them up //Nullify all resoruces so that JUnit cleans them up
@@ -53,15 +53,17 @@ public abstract class AbstractQueryResolverTest {
return applicationContext.getBean(DSpaceFilterResolver.class); return applicationContext.getBean(DSpaceFilterResolver.class);
} }
protected StubbedFieldResolver theFieldResolver () { protected StubbedFieldResolver theFieldResolver() {
return (StubbedFieldResolver) applicationContext.getBean(FieldResolver.class); return (StubbedFieldResolver) applicationContext.getBean(FieldResolver.class);
} }
protected String escapedFromDate(Date date) { protected String escapedFromDate(Date date) {
return ClientUtils.escapeQueryChars(baseDateProvider.format(new DateBuilder(date).setMinMilliseconds().build()).replace("Z", ".000Z")); return ClientUtils.escapeQueryChars(
baseDateProvider.format(new DateBuilder(date).setMinMilliseconds().build()).replace("Z", ".000Z"));
} }
protected String escapedUntilDate(Date date) { protected String escapedUntilDate(Date date) {
return ClientUtils.escapeQueryChars(baseDateProvider.format(new DateBuilder(date).setMaxMilliseconds().build()).replace("Z", ".999Z")); return ClientUtils.escapeQueryChars(
baseDateProvider.format(new DateBuilder(date).setMaxMilliseconds().build()).replace("Z", ".999Z"));
} }
} }

View File

@@ -7,6 +7,13 @@
*/ */
package org.dspace.xoai.tests.unit.services.impl.solr; package org.dspace.xoai.tests.unit.services.impl.solr;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.lyncode.xoai.dataprovider.data.Filter; import com.lyncode.xoai.dataprovider.data.Filter;
import com.lyncode.xoai.dataprovider.filter.Scope; import com.lyncode.xoai.dataprovider.filter.Scope;
import com.lyncode.xoai.dataprovider.filter.ScopedFilter; import com.lyncode.xoai.dataprovider.filter.ScopedFilter;
@@ -26,23 +33,17 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class DSpaceSolrQueryResolverTest extends AbstractQueryResolverTest { public class DSpaceSolrQueryResolverTest extends AbstractQueryResolverTest {
private static final Date DATE = new Date(); private static final Date DATE = new Date();
private static final String SET = "col_testSet"; private static final String SET = "col_testSet";
private static final String FIELD_1 = "dc.title"; private static final String FIELD_1 = "dc.title";
private static final String FIELD_2 = "dc.type"; private static final String FIELD_2 = "dc.type";
private DSpaceSolrQueryResolver underTest = new DSpaceSolrQueryResolver();; private DSpaceSolrQueryResolver underTest = new DSpaceSolrQueryResolver();
;
@Before @Before
public void autowire () { public void autowire() {
autowire(underTest); autowire(underTest);
} }
@@ -50,7 +51,7 @@ public class DSpaceSolrQueryResolverTest extends AbstractQueryResolverTest {
public void cleanup() { public void cleanup() {
underTest = null; underTest = null;
} }
@Test @Test
public void fromFilterQuery() throws Exception { public void fromFilterQuery() throws Exception {
List<ScopedFilter> scopedFilters = new ArrayList<ScopedFilter>(); List<ScopedFilter> scopedFilters = new ArrayList<ScopedFilter>();
@@ -82,48 +83,49 @@ public class DSpaceSolrQueryResolverTest extends AbstractQueryResolverTest {
} }
}; };
scopedFilters.add(new ScopedFilter(new AndCondition(getFilterResolver(), scopedFilters.add(new ScopedFilter(new AndCondition(getFilterResolver(),
fromCondition, untilCondition), Scope.Query)); fromCondition, untilCondition), Scope.Query));
String result = underTest.buildQuery(scopedFilters); String result = underTest.buildQuery(scopedFilters);
assertThat(result, is("(((item.lastmodified:["+escapedFromDate(DATE)+" TO *]) AND (item.lastmodified:[* TO "+escapedUntilDate(DATE)+"])))")); assertThat(result, is("(((item.lastmodified:[" + escapedFromDate(
DATE) + " TO *]) AND (item.lastmodified:[* TO " + escapedUntilDate(DATE) + "])))"));
} }
@Test @Test
public void customConditionForMetadataExistsFilterWithOneSingleValue() throws Exception { public void customConditionForMetadataExistsFilterWithOneSingleValue() throws Exception {
List<ScopedFilter> scopedFilters = new ArrayList<ScopedFilter>(); List<ScopedFilter> scopedFilters = new ArrayList<ScopedFilter>();
ParameterMap filterConfiguration = new ParameterMap().withValues(new StringValue() ParameterMap filterConfiguration = new ParameterMap().withValues(new StringValue()
.withValue(FIELD_1) .withValue(FIELD_1)
.withName("fields")); .withName("fields"));
scopedFilters.add(new ScopedFilter(new CustomCondition(getFilterResolver(), scopedFilters.add(new ScopedFilter(new CustomCondition(getFilterResolver(),
DSpaceMetadataExistsFilter.class, DSpaceMetadataExistsFilter.class,
filterConfiguration), filterConfiguration),
Scope.Query)); Scope.Query));
String result = underTest.buildQuery(scopedFilters); String result = underTest.buildQuery(scopedFilters);
assertThat(result, is("(((metadata."+FIELD_1+":[* TO *])))")); assertThat(result, is("(((metadata." + FIELD_1 + ":[* TO *])))"));
} }
@Test @Test
public void customConditionForMetadataExistsFilterWithMultipleValues() throws Exception { public void customConditionForMetadataExistsFilterWithMultipleValues() throws Exception {
List<ScopedFilter> scopedFilters = new ArrayList<ScopedFilter>(); List<ScopedFilter> scopedFilters = new ArrayList<ScopedFilter>();
ParameterMap filterConfiguration = new ParameterMap().withValues(new ParameterList() ParameterMap filterConfiguration = new ParameterMap().withValues(new ParameterList()
.withValues( .withValues(
new StringValue().withValue(FIELD_1), new StringValue().withValue(FIELD_1),
new StringValue().withValue(FIELD_2) new StringValue().withValue(FIELD_2)
) )
.withName("fields")); .withName("fields"));
scopedFilters.add(new ScopedFilter(new CustomCondition(getFilterResolver(), scopedFilters.add(new ScopedFilter(new CustomCondition(getFilterResolver(),
DSpaceMetadataExistsFilter.class, DSpaceMetadataExistsFilter.class,
filterConfiguration), filterConfiguration),
Scope.Query)); Scope.Query));
String result = underTest.buildQuery(scopedFilters); String result = underTest.buildQuery(scopedFilters);
assertThat(result, is("(((metadata."+FIELD_1+":[* TO *] OR metadata."+FIELD_2+":[* TO *])))")); assertThat(result, is("(((metadata." + FIELD_1 + ":[* TO *] OR metadata." + FIELD_2 + ":[* TO *])))"));
} }
@Test @Test
@@ -159,7 +161,8 @@ public class DSpaceSolrQueryResolverTest extends AbstractQueryResolverTest {
String result = underTest.buildQuery(scopedFilters); String result = underTest.buildQuery(scopedFilters);
assertThat(result, is("((item.lastmodified:[" + escapedFromDate(DATE) + " TO *])) AND ((item.collections:"+SET+"))")); assertThat(result, is("((item.lastmodified:[" + escapedFromDate(
DATE) + " TO *])) AND ((item.collections:" + SET + "))"));
} }
} }

View File

@@ -8,7 +8,8 @@
http://www.dspace.org/license/ http://www.dspace.org/license/
--> -->
<metadata xmlns="http://www.lyncode.com/xoai" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.lyncode.com/xoai http://www.lyncode.com/xsd/xoai.xsd"> <metadata xmlns="http://www.lyncode.com/xoai" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.lyncode.com/xoai http://www.lyncode.com/xsd/xoai.xsd">
<element name="dc"> <element name="dc">
<element name="creator"> <element name="creator">
<element name="en_US"> <element name="en_US">