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>

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;
@@ -82,9 +82,10 @@ 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() {

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,8 +22,6 @@ 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( { @Import( {
BasicConfiguration.class BasicConfiguration.class
}) })
@@ -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)
*/ */
@@ -140,8 +147,9 @@ public class XOAI {
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();
@@ -207,7 +215,9 @@ public class XOAI {
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,12 +240,14 @@ 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);
@@ -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();
@@ -385,7 +401,9 @@ public class XOAI {
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)) {
@@ -413,14 +431,13 @@ 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();
} }
} }
}
private static void cleanCompiledItems(XOAIItemCacheService itemCacheService) throws IOException { private static void cleanCompiledItems(XOAIItemCacheService itemCacheService) throws IOException {
System.out.println("Purging compiled items"); System.out.println("Purging compiled items");
@@ -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,36 +45,25 @@ 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();
@@ -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");
@@ -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();
@@ -121,7 +129,8 @@ public class DSpaceOAIDataProvider
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);
@@ -145,9 +154,10 @@ 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) {

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,16 +20,10 @@ 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)));
} }
@@ -42,11 +40,15 @@ public abstract class DSpaceItem implements Item
private static List<String> values(List<Element> input) { private static List<String> values(List<Element> input) {
List<String> elems = new ArrayList<String>(); List<String> elems = new ArrayList<String>();
for (Element e : input) for (Element e : input) {
if (e.getElement() != null && !e.getElement().isEmpty() && e.getElement().get(0).getField() != null) if (e.getElement() != null && !e.getElement().isEmpty() && e.getElement().get(0).getField() != null) {
for (Field f : e.getElement().get(0).getField()) for (Field f : e.getElement().get(0).getField()) {
if (f.getName() != null && f.getName().equals("value")) if (f.getName() != null && f.getName().equals("value")) {
elems.add(f.getValue()); elems.add(f.getValue());
}
}
}
}
return elems; return elems;
} }
@@ -63,39 +65,44 @@ public abstract class DSpaceItem implements Item
private static String _prefix = null; private static String _prefix = null;
public static String buildIdentifier(String handle) { public static String buildIdentifier(String handle) {
if (_prefix == null) 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) { public static String parseHandle(String oaiIdentifier) {
String[] parts = oaiIdentifier.split(Pattern.quote(":")); String[] parts = oaiIdentifier.split(Pattern.quote(":"));
if (parts.length > 0) return parts[parts.length - 1]; if (parts.length > 0) {
else return null; // Contract 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 @Override
public List<About> getAbout() public List<About> getAbout() {
{
return new ArrayList<About>(); return new ArrayList<About>();
} }
protected abstract String getHandle(); protected abstract String getHandle();
@Override @Override
public String getIdentifier() public String getIdentifier() {
{
return buildIdentifier(getHandle()); return buildIdentifier(getHandle());
} }
@@ -108,9 +115,13 @@ public abstract class DSpaceItem implements Item
@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,21 +7,20 @@
*/ */
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;
} }

View File

@@ -8,23 +8,20 @@
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);
@@ -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,7 +44,9 @@ 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<>();
@@ -59,58 +60,71 @@ public class DSpaceAtLeastOneMetadataFilter extends DSpaceFilter {
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,9 +137,10 @@ 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 "));

View File

@@ -22,11 +22,9 @@ 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
@@ -36,32 +34,29 @@ public class DSpaceAuthorizationFilter extends DSpaceFilter
= 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
@@ -37,16 +36,19 @@ public class DSpaceMetadataExistsFilter extends DSpaceFilter {
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());
} }
}
} }
return fields; return fields;
@@ -56,9 +58,10 @@ 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,9 +71,10 @@ 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(")");
return new SolrFilterResult(cond.toString()); return new SolrFilterResult(cond.toString());

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

@@ -24,8 +24,7 @@ import org.dspace.xoai.filter.results.SolrFilterResult;
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,32 +16,27 @@ 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)

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,37 +16,30 @@ 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 "

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

@@ -11,5 +11,6 @@ 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

@@ -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); boolean hasCache(String requestID);
void handle(String requestID, OutputStream out) throws IOException; void handle(String requestID, OutputStream out) throws IOException;
void store(String requestID, OAIPMH response) throws IOException; void store(String requestID, OAIPMH response) throws IOException;
void delete(String requestID); void delete(String requestID);
void deleteAll() throws IOException; 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; Metadata get(Item item) throws IOException;
void put(Item item, Metadata metadata) throws IOException; void put(Item item, Metadata metadata) throws IOException;
void delete(Item item); void delete(Item item);
void deleteAll() throws IOException; void deleteAll() throws IOException;
} }

View File

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

View File

@@ -9,6 +9,8 @@ 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

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

@@ -15,6 +15,8 @@ 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; String toSetSpec(Collection collection) throws InvalidSetSpecException;
DSpaceObject fromSetSpec(String setSpec) 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

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

@@ -7,22 +7,22 @@
*/ */
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 {
@@ -31,8 +31,7 @@ public class DSpaceCollectionsService implements CollectionsService {
@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,81 +39,85 @@ 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;
} }
@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;
} }
@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);
@@ -35,16 +35,14 @@ 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,9 +17,6 @@ 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;
@@ -25,31 +25,30 @@ public class DSpaceFieldResolver implements FieldResolver {
@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,8 +16,6 @@ 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())

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)));
@@ -81,9 +76,6 @@ public class DSpaceXOAIItemCacheService implements XOAIItemCacheService {
} }
@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));

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,6 +14,10 @@ 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 {
@@ -31,10 +31,8 @@ public class DSpaceXOAILastCompilationCacheService implements XOAILastCompilatio
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

@@ -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,19 +11,16 @@ 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();
@@ -31,15 +28,13 @@ public class DSpaceResourceResolver implements ResourceResolver
"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);
@@ -87,7 +92,8 @@ public class DSpaceSetSpecResolver implements SetSpecResolver {
} }
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,11 +25,13 @@ 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;

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);
@@ -32,10 +39,13 @@ public class BaseDSpaceFilterResolver implements DSpaceFilterResolver {
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,34 +57,30 @@ 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";
} }
@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);
} }

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);
@@ -66,8 +61,7 @@ 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));
@@ -77,8 +71,7 @@ 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, 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),
@@ -88,8 +81,7 @@ public abstract class DSpaceItemRepository implements ItemRepository
@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);
} }
@@ -97,8 +89,7 @@ public abstract class DSpaceItemRepository implements ItemRepository
@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));
@@ -107,16 +98,14 @@ 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, 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);
@@ -124,8 +113,7 @@ 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, 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,8 +121,7 @@ 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));
@@ -143,8 +130,7 @@ 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, 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),
@@ -154,16 +140,14 @@ public abstract class DSpaceItemRepository implements ItemRepository
@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));

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;

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,10 +67,8 @@ 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())
@@ -85,9 +79,7 @@ public class DSpaceItemSolrRepository extends DSpaceItemRepository
} }
}); });
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,15 +87,11 @@ 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>());
} }
@@ -115,9 +103,11 @@ public class DSpaceItemSolrRepository extends DSpaceItemRepository
.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,39 +42,38 @@ 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(), "");
} }
@@ -85,45 +82,35 @@ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration
} }
@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";
} }
} }
@@ -140,15 +127,19 @@ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration
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) { for (String path : descriptionFiles) {
try { try {
File f = new File(path); File f = new File(path);
if (f.exists()) if (f.exists()) {
result.add(FileUtils.readFileToString(f)); result.add(FileUtils.readFileToString(f));
}
} catch (IOException e) { } catch (IOException e) {
log.debug(e.getMessage(), e); log.debug(e.getMessage(), e);
} }
@@ -157,8 +148,9 @@ public class DSpaceRepositoryConfiguration implements RepositoryConfiguration
} else { } else {
try { try {
File f = new File(descriptionFile); File f = new File(descriptionFile);
if (f.exists()) if (f.exists()) {
result.add(FileUtils.readFileToString(f)); result.add(FileUtils.readFileToString(f));
}
} catch (IOException e) { } catch (IOException e) {
log.debug(e.getMessage(), e); log.debug(e.getMessage(), e);
} }

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,8 +16,6 @@ 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
@@ -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,20 +128,16 @@ 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: "
@@ -174,42 +148,33 @@ public class DSpaceSetRepository implements SetRepository
} }
@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;
} }
catch (SQLException ex) return true;
{ } 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;
} }
catch (SQLException ex) return true;
{ } 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,8 +35,7 @@ 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
@@ -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,38 +7,40 @@
*/ */
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
@@ -50,37 +52,42 @@ public class ItemUtils
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
@@ -88,8 +95,7 @@ public class ItemUtils
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) {
@@ -98,32 +104,27 @@ public class ItemUtils
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,21 +154,20 @@ 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!
// Now adding bitstream info // Now adding bitstream info
Element bundles = create("bundles"); Element bundles = create("bundles");
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()
@@ -181,8 +176,7 @@ public class ItemUtils
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 = "";
@@ -194,29 +188,23 @@ public class ItemUtils
// 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,15 +214,18 @@ 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()));
@@ -250,9 +241,7 @@ public class ItemUtils
+ "")); + ""));
} }
} }
} } catch (SQLException e1) {
catch (SQLException e1)
{
e1.printStackTrace(); e1.printStackTrace();
} }
@@ -282,19 +271,15 @@ public class ItemUtils
// 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);
@@ -302,17 +287,13 @@ public class ItemUtils
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);
} }

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);
/**
* Default constructor
*/
private URLUtils() { }
public static String encode(String value) { public static String encode(String value) {
try try {
{
return Util.encodeBitstreamName(value, Constants.DEFAULT_ENCODING); return Util.encodeBitstreamName(value, Constants.DEFAULT_ENCODING);
} } catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException e)
{
log.warn(e.getMessage(), e); log.warn(e.getMessage(), e);
return value; return value;
} }

View File

@@ -11,9 +11,7 @@
<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"/>

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,8 +19,6 @@ 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 {

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,6 +100,7 @@ public class DSpaceTestConfiguration extends WebMvcConfigurerAdapter {
} }
}; };
} }
@Bean @Bean
public SetRepositoryResolver setRepositoryResolver() { public SetRepositoryResolver setRepositoryResolver() {
return new SetRepositoryResolver() { return new SetRepositoryResolver() {
@@ -108,6 +110,7 @@ public class DSpaceTestConfiguration extends WebMvcConfigurerAdapter {
} }
}; };
} }
@Bean @Bean
public IdentifyResolver identifyResolver() { public IdentifyResolver identifyResolver() {
return new DSpaceIdentifyResolver(); return new DSpaceIdentifyResolver();

View File

@@ -7,11 +7,11 @@
*/ */
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();

View File

@@ -11,9 +11,11 @@ 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;
@@ -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);
@@ -91,14 +94,17 @@ public class ItemRepositoryBuilder {
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;
@@ -108,6 +114,7 @@ public class ItemRepositoryBuilder {
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;

View File

@@ -7,11 +7,11 @@
*/ */
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>();
@@ -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,13 +7,13 @@
*/ */
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();

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,7 +17,8 @@ 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;

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;
@@ -84,7 +91,9 @@ 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;
} }
@@ -116,11 +125,14 @@ 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;
} }
@@ -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();
@@ -44,6 +44,7 @@ public class IdentifyTest extends AbstractDSpaceTest {
.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,6 +14,8 @@ 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 {

View File

@@ -7,13 +7,13 @@
*/ */
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 = "/";

View File

@@ -8,18 +8,18 @@
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();

View File

@@ -7,16 +7,16 @@
*/ */
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();
@@ -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

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

View File

@@ -7,15 +7,19 @@
*/ */
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() {
@@ -91,17 +95,21 @@ 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);
@@ -58,10 +58,12 @@ public abstract class AbstractQueryResolverTest {
} }
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,20 +33,14 @@ 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() {
@@ -86,7 +87,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.lastmodified:[* TO "+escapedUntilDate(DATE)+"])))")); assertThat(result, is("(((item.lastmodified:[" + escapedFromDate(
DATE) + " TO *]) AND (item.lastmodified:[* TO " + escapedUntilDate(DATE) + "])))"));
} }
@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">