DS-2701 Reformat code according to DSpace code conventions

This commit is contained in:
Andrea Schweer
2015-08-24 09:50:39 +12:00
parent 09270f922f
commit eb63f024f0
77 changed files with 10667 additions and 9247 deletions

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -37,5 +37,6 @@ public abstract class ATOMCollectionGenerator
* @param dso
* @throws DSpaceSWORDException
*/
public abstract Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException;
public abstract Collection buildCollection(DSpaceObject dso)
throws DSpaceSWORDException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -73,9 +73,12 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry
String bsurl = urlManager.getBitstreamUrl(this.bitstream);
BitstreamFormat bf = null;
try {
try
{
bf = this.bitstream.getFormat(swordService.getContext());
} catch (SQLException e) {
}
catch (SQLException e)
{
log.error("Exception caught: ", e);
throw new DSpaceSWORDException(e);
}
@@ -120,7 +123,6 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry
return;
}
SWORDUrlManager urlManager = swordService.getUrlManager();
// for a bitstream, we just use the url for the bitstream
@@ -152,9 +154,12 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry
String bsurl = urlManager.getBitstreamUrl(this.bitstream);
BitstreamFormat bf;
try {
try
{
bf = this.bitstream.getFormat(swordService.getContext());
} catch (SQLException e) {
}
catch (SQLException e)
{
log.error("Exception caught: ", e);
throw new DSpaceSWORDException(e);
}
@@ -182,7 +187,6 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry
// do nothing
}
/**
* Add rights information. This attaches an href to the URL
* of the item's licence file
@@ -194,7 +198,8 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry
try
{
// work our way up to the item
List<BundleBitstream> bundle2bitstreams = this.bitstream.getBundles();
List<BundleBitstream> bundle2bitstreams = this.bitstream
.getBundles();
if (bundle2bitstreams.isEmpty())
{
log.error("Found orphaned bitstream: " + bitstream.getID());
@@ -213,14 +218,16 @@ public class BitstreamEntryGenerator extends DSpaceATOMEntry
SWORDUrlManager urlManager = swordService.getUrlManager();
StringBuilder rightsString = new StringBuilder();
List<Bundle> lbundles = item.getBundles();
for (Bundle lbundle : lbundles) {
for (Bundle lbundle : lbundles)
{
if (!Constants.LICENSE_BUNDLE_NAME.equals(lbundle.getName()))
{
// skip non-license bundles
continue;
}
List<BundleBitstream> bss = lbundle.getBitstreams();
for (BundleBitstream b2b : bss) {
for (BundleBitstream b2b : bss)
{
Bitstream bs = b2b.getBitstream();
String url = urlManager.getBitstreamUrl(bs);
rightsString.append(url).append(" ");

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -25,8 +25,11 @@ import java.util.List;
public class CollectionCollectionGenerator extends ATOMCollectionGenerator
{
/** logger */
private static Logger log = Logger.getLogger(CollectionCollectionGenerator.class);
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
private static Logger log = Logger
.getLogger(CollectionCollectionGenerator.class);
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
/**
* Construct an object taking the sword service instance an argument
@@ -44,12 +47,15 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator
* @param dso
* @throws DSpaceSWORDException
*/
public Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException
public Collection buildCollection(DSpaceObject dso)
throws DSpaceSWORDException
{
if (!(dso instanceof org.dspace.content.Collection))
{
log.error("buildCollection passed argument which is not of type Collection");
throw new DSpaceSWORDException("Incorrect ATOMCollectionGenerator instantiated");
log.error(
"buildCollection passed argument which is not of type Collection");
throw new DSpaceSWORDException(
"Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
@@ -73,7 +79,8 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator
// String treatment = " ";
// abstract is the short description of the collection
String dcAbstract = collectionService.getMetadata(col, "short_description");
String dcAbstract = collectionService
.getMetadata(col, "short_description");
// we just do support mediation
boolean mediation = swordConfig.isMediated();
@@ -105,7 +112,8 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator
scol.setMediation(mediation);
List<String> accepts = swordService.getSwordConfig().getCollectionAccepts();
List<String> accepts = swordService.getSwordConfig()
.getCollectionAccepts();
for (String accept : accepts)
{
scol.addAccepts(accept);
@@ -120,7 +128,8 @@ public class CollectionCollectionGenerator extends ATOMCollectionGenerator
// should we offer the items in the collection up as deposit
// targets?
boolean itemService = ConfigurationManager.getBooleanProperty("sword-server", "expose-items");
boolean itemService = ConfigurationManager
.getBooleanProperty("sword-server", "expose-items");
if (itemService)
{
String subService = urlManager.constructSubServiceUrl(col);

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -43,10 +43,17 @@ public class CollectionDepositor extends Depositor
/** logger */
private static Logger log = Logger.getLogger(CollectionDepositor.class);
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
/**
* The DSpace Collection we are depositing into
@@ -69,7 +76,8 @@ public class CollectionDepositor extends Depositor
if (!(dso instanceof Collection))
{
throw new DSpaceSWORDException("You tried to initialise the collection depositor with something" +
throw new DSpaceSWORDException(
"You tried to initialise the collection depositor with something" +
"other than a collection object");
}
@@ -97,24 +105,34 @@ public class CollectionDepositor extends Depositor
// the throw a 415 (ERROR_CONTENT) until further notice
//
// determine if this is an acceptable file format
if (!swordConfig.isAcceptableContentType(context, deposit.getContentType(), collection))
if (!swordConfig
.isAcceptableContentType(context, deposit.getContentType(),
collection))
{
log.error("Unacceptable content type detected: " + deposit.getContentType() + " for collection " + collection.getID());
log.error("Unacceptable content type detected: " +
deposit.getContentType() + " for collection " +
collection.getID());
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable content type in deposit request: " + deposit.getContentType());
"Unacceptable content type in deposit request: " +
deposit.getContentType());
}
// determine if this is an acceptable packaging type for the deposit
// if not, we throw a 415 HTTP error (Unsupported Media Type, ERROR_CONTENT)
if (!swordConfig.isSupportedMediaType(deposit.getPackaging(), this.collection))
if (!swordConfig
.isSupportedMediaType(deposit.getPackaging(), this.collection))
{
log.error("Unacceptable packaging type detected: " + deposit.getPackaging() + "for collection" + collection.getID());
log.error("Unacceptable packaging type detected: " +
deposit.getPackaging() + "for collection" +
collection.getID());
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable packaging type in deposit request: " + deposit.getPackaging());
"Unacceptable packaging type in deposit request: " +
deposit.getPackaging());
}
// Obtain the relevant ingester from the factory
SWORDIngester si = SWORDIngesterFactory.getInstance(context, deposit, collection);
SWORDIngester si = SWORDIngesterFactory
.getInstance(context, deposit, collection);
swordService.message("Loaded ingester: " + si.getClass().getName());
// do the deposit
@@ -127,14 +145,16 @@ public class CollectionDepositor extends Depositor
{
if (swordConfig.isKeepOriginal())
{
swordService.message("DSpace will store an original copy of the deposit, " +
swordService.message(
"DSpace will store an original copy of the deposit, " +
"as well as ingesting the item into the archive");
// in order to be allowed to add the file back to the item, we need to ignore authorisations
// for a moment
context.turnOffAuthorisationSystem();
String bundleName = ConfigurationManager.getProperty("sword-server", "bundle.name");
String bundleName = ConfigurationManager
.getProperty("sword-server", "bundle.name");
if (bundleName == null || "".equals(bundleName))
{
bundleName = "SWORD";
@@ -153,7 +173,8 @@ public class CollectionDepositor extends Depositor
}
if (swordBundle == null)
{
swordBundle = bundleService.create(context, item, bundleName);
swordBundle = bundleService
.create(context, item, bundleName);
}
String fn = swordService.getFilename(context, deposit, true);
@@ -163,7 +184,8 @@ public class CollectionDepositor extends Depositor
try
{
fis = new FileInputStream(deposit.getFile());
bitstream = bitstreamService.create(context, swordBundle, fis);
bitstream = bitstreamService
.create(context, swordBundle, fis);
}
finally
{
@@ -176,7 +198,8 @@ public class CollectionDepositor extends Depositor
bitstream.setName(context, fn);
bitstream.setDescription(context, "SWORD deposit package");
BitstreamFormat bf = bitstreamFormatService.findByMIMEType(context, deposit.getContentType());
BitstreamFormat bf = bitstreamFormatService
.findByMIMEType(context, deposit.getContentType());
if (bf != null)
{
bitstreamService.setFormat(context, bitstream, bf);
@@ -186,7 +209,8 @@ public class CollectionDepositor extends Depositor
bundleService.update(context, swordBundle);
itemService.update(context, item);
swordService.message("Original package stored as " + fn + ", in item bundle " + swordBundle);
swordService.message("Original package stored as " + fn +
", in item bundle " + swordBundle);
// now reset the context ignore authorisation
context.restoreAuthSystemState();

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -34,7 +34,8 @@ public class CollectionLocation
/** Log4j logger */
public static final Logger log = Logger.getLogger(CollectionLocation.class);
protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService();
/**
* Obtain the deposit URL for the given collection. These URLs
@@ -84,7 +85,8 @@ public class CollectionLocation
if (!(dso instanceof Collection))
{
throw new DSpaceSWORDException("The deposit URL does not resolve to a valid collection");
throw new DSpaceSWORDException(
"The deposit URL does not resolve to a valid collection");
}
return (Collection) dso;
@@ -92,7 +94,8 @@ public class CollectionLocation
catch (SQLException e)
{
log.error("Caught exception:", e);
throw new DSpaceSWORDException("There was a problem resolving the collection", e);
throw new DSpaceSWORDException(
"There was a problem resolving the collection", e);
}
}
@@ -115,26 +118,31 @@ public class CollectionLocation
private String getBaseUrl()
throws DSpaceSWORDException
{
String depositUrl = ConfigurationManager.getProperty("sword-server", "deposit.url");
String depositUrl = ConfigurationManager
.getProperty("sword-server", "deposit.url");
if (depositUrl == null || "".equals(depositUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
String dspaceUrl = ConfigurationManager
.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to missing/invalid config in sword.deposit.url and/or dspace.baseUrl");
throw new DSpaceSWORDException(
"Unable to construct deposit urls, due to missing/invalid config in sword.deposit.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
depositUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/deposit").toString();
depositUrl = new URL(url.getProtocol(), url.getHost(),
url.getPort(), "/sword/deposit").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to invalid dspace.baseUrl " + e.getMessage(),e);
throw new DSpaceSWORDException(
"Unable to construct deposit urls, due to invalid dspace.baseUrl " +
e.getMessage(), e);
}
}
return depositUrl;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -20,9 +20,11 @@ import java.util.List;
public class CommunityCollectionGenerator extends ATOMCollectionGenerator
{
private static Logger log = Logger.getLogger(CommunityCollectionGenerator.class);
private static Logger log = Logger
.getLogger(CommunityCollectionGenerator.class);
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CommunityService communityService = ContentServiceFactory
.getInstance().getCommunityService();
public CommunityCollectionGenerator(SWORDService service)
{
@@ -35,8 +37,10 @@ public class CommunityCollectionGenerator extends ATOMCollectionGenerator
{
if (!(dso instanceof Community))
{
log.error("buildCollection passed something other than a Community object");
throw new DSpaceSWORDException("Incorrect ATOMCollectionGenerator instantiated");
log.error(
"buildCollection passed something other than a Community object");
throw new DSpaceSWORDException(
"Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
@@ -62,7 +66,8 @@ public class CommunityCollectionGenerator extends ATOMCollectionGenerator
// String collectionPolicy = col.getLicense();
// abstract is the short description of the collection
List<MetadataValue> abstracts = communityService.getMetadataByMetadataString(com, "short_description");
List<MetadataValue> abstracts = communityService
.getMetadataByMetadataString(com, "short_description");
if (abstracts != null && !abstracts.isEmpty())
{
String firstValue = abstracts.get(0).getValue();

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -93,7 +93,8 @@ public abstract class DSpaceATOMEntry
}
else
{
throw new DSpaceSWORDException("Can only recover a sword entry for a bitstream via this method");
throw new DSpaceSWORDException(
"Can only recover a sword entry for a bitstream via this method");
}
this.constructEntry();
@@ -196,7 +197,8 @@ public abstract class DSpaceATOMEntry
*/
protected void addGenerator()
{
boolean identify = ConfigurationManager.getBooleanProperty("sword-server", "identify-version");
boolean identify = ConfigurationManager
.getBooleanProperty("sword-server", "identify-version");
SWORDUrlManager urlManager = swordService.getUrlManager();
String softwareUri = urlManager.getGeneratorUrl();
if (identify)
@@ -270,7 +272,6 @@ public abstract class DSpaceATOMEntry
*/
abstract void addContentElement() throws DSpaceSWORDException;
/**
* Add the identifier for the item. If the item object has
* a handle already assigned, this is used, otherwise, the

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -13,29 +13,37 @@ package org.dspace.sword;
public interface DSpaceSWORDErrorCodes
{
/** if unpackaging the package fails */
public static final String UNPACKAGE_FAIL = SWORDProperties.SOFTWARE_URI + "/errors/UnpackageFail";
public static final String UNPACKAGE_FAIL =
SWORDProperties.SOFTWARE_URI + "/errors/UnpackageFail";
/** if the url of the request does not resolve to something meaningful */
public static final String BAD_URL = SWORDProperties.SOFTWARE_URI + "/errors/BadUrl";
public static final String BAD_URL =
SWORDProperties.SOFTWARE_URI + "/errors/BadUrl";
/** if the media requested is unavailable */
public static final String MEDIA_UNAVAILABLE = SWORDProperties.SOFTWARE_URI + "/errors/MediaUnavailable";
public static final String MEDIA_UNAVAILABLE =
SWORDProperties.SOFTWARE_URI + "/errors/MediaUnavailable";
/* additional codes */
/** Invalid package */
public static final String PACKAGE_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/PackageError";
public static final String PACKAGE_ERROR =
SWORDProperties.SOFTWARE_URI + "/errors/PackageError";
/** Missing resources in package */
public static final String PACKAGE_VALIDATION_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/PackageValidationError";
public static final String PACKAGE_VALIDATION_ERROR =
SWORDProperties.SOFTWARE_URI + "/errors/PackageValidationError";
/** Crosswalk error */
public static final String CROSSWALK_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/CrosswalkError";
public static final String CROSSWALK_ERROR =
SWORDProperties.SOFTWARE_URI + "/errors/CrosswalkError";
/** Invalid collection for linking */
public static final String COLLECTION_LINK_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/CollectionLinkError";
public static final String COLLECTION_LINK_ERROR =
SWORDProperties.SOFTWARE_URI + "/errors/CollectionLinkError";
/** Database or IO Error when installing new item */
public static final String REPOSITORY_ERROR = SWORDProperties.SOFTWARE_URI + "/errors/RepositoryError";
public static final String REPOSITORY_ERROR =
SWORDProperties.SOFTWARE_URI + "/errors/RepositoryError";
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -43,7 +43,8 @@ public class DSpaceSWORDServer implements SWORDServer
* @see org.purl.sword.SWORDServer#doServiceDocument(org.purl.sword.base.ServiceDocumentRequest)
*/
public ServiceDocument doServiceDocument(ServiceDocumentRequest request)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
throws SWORDAuthenticationException, SWORDException,
SWORDErrorException
{
// gah. bloody variable scoping.
// set up a dummy sword context for the "finally" block
@@ -59,23 +60,31 @@ public class DSpaceSWORDServer implements SWORDServer
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_do_service_document", ""));
log.debug(LogManager
.getHeader(context, "sword_do_service_document", ""));
}
// log the request
log.info(LogManager.getHeader(context, "sword_service_document_request", "username=" + request.getUsername() + ",on_behalf_of=" + request.getOnBehalfOf()));
log.info(LogManager
.getHeader(context, "sword_service_document_request",
"username=" + request.getUsername() +
",on_behalf_of=" +
request.getOnBehalfOf()));
// prep the service request, then get the service document out of it
SWORDService service = new SWORDService(sc);
ServiceDocumentManager manager = new ServiceDocumentManager(service);
ServiceDocument doc = manager.getServiceDocument(request.getLocation());
ServiceDocumentManager manager = new ServiceDocumentManager(
service);
ServiceDocument doc = manager
.getServiceDocument(request.getLocation());
return doc;
}
catch (DSpaceSWORDException e)
{
log.error("caught exception: ", e);
throw new SWORDException("The DSpace SWORD interface experienced an error", e);
throw new SWORDException(
"The DSpace SWORD interface experienced an error", e);
}
finally
{
@@ -91,7 +100,8 @@ public class DSpaceSWORDServer implements SWORDServer
* @see org.purl.sword.SWORDServer#doSWORDDeposit(org.purl.sword.server.Deposit)
*/
public DepositResponse doDeposit(Deposit deposit)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
throws SWORDAuthenticationException, SWORDException,
SWORDErrorException
{
// gah. bloody variable scoping.
// set up a dummy sword context for the "finally" block
@@ -107,11 +117,14 @@ public class DSpaceSWORDServer implements SWORDServer
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_do_deposit", ""));
log.debug(
LogManager.getHeader(context, "sword_do_deposit", ""));
}
// log the request
log.info(LogManager.getHeader(context, "sword_deposit_request", "username=" + deposit.getUsername() + ",on_behalf_of=" + deposit.getOnBehalfOf()));
log.info(LogManager.getHeader(context, "sword_deposit_request",
"username=" + deposit.getUsername() + ",on_behalf_of=" +
deposit.getOnBehalfOf()));
// prep and execute the deposit
SWORDService service = new SWORDService(sc);
@@ -127,7 +140,8 @@ public class DSpaceSWORDServer implements SWORDServer
catch (DSpaceSWORDException e)
{
log.error("caught exception:", e);
throw new SWORDException("There was a problem depositing the item", e);
throw new SWORDException("There was a problem depositing the item",
e);
}
finally
{
@@ -144,7 +158,8 @@ public class DSpaceSWORDServer implements SWORDServer
* @see org.purl.sword.SWORDServer#doSWORDDeposit(org.purl.sword.server.Deposit)
*/
public AtomDocumentResponse doAtomDocument(AtomDocumentRequest adr)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
throws SWORDAuthenticationException, SWORDException,
SWORDErrorException
{
// gah. bloody variable scoping.
// set up a dummy sword context for the "finally" block
@@ -160,11 +175,14 @@ public class DSpaceSWORDServer implements SWORDServer
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_do_atom_document", ""));
log.debug(LogManager
.getHeader(context, "sword_do_atom_document", ""));
}
// log the request
log.info(LogManager.getHeader(context, "sword_atom_document_request", "username=" + adr.getUsername()));
log.info(LogManager
.getHeader(context, "sword_atom_document_request",
"username=" + adr.getUsername()));
// prep the service request, then get the service document out of it
SWORDService service = new SWORDService(sc);
@@ -175,7 +193,8 @@ public class DSpaceSWORDServer implements SWORDServer
catch (DSpaceSWORDException e)
{
log.error("caught exception: ", e);
throw new SWORDException("The DSpace SWORD interface experienced an error", e);
throw new SWORDException(
"The DSpace SWORD interface experienced an error", e);
}
finally
{

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -70,13 +70,18 @@ public class DepositManager
if (dso instanceof Collection)
{
CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
swordService.message("Location resolves to collection with handle: " + dso.getHandle() +
" and name: " + collectionService.getName((Collection) dso));
CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
swordService.message(
"Location resolves to collection with handle: " +
dso.getHandle() +
" and name: " +
collectionService.getName((Collection) dso));
}
else if (dso instanceof Item)
{
swordService.message("Location resolves to item with handle: " + dso.getHandle());
swordService.message("Location resolves to item with handle: " +
dso.getHandle());
}
return dso;
@@ -91,7 +96,8 @@ public class DepositManager
* @throws DSpaceSWORDException
*/
public DepositResponse deposit(Deposit deposit)
throws DSpaceSWORDException, SWORDErrorException, SWORDAuthenticationException
throws DSpaceSWORDException, SWORDErrorException,
SWORDAuthenticationException
{
// start the timer, and initialise the verboseness of the request
Date start = new Date();
@@ -115,35 +121,45 @@ public class DepositManager
{
oboEmail = swordContext.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "deposit_failed_authorisation", "user=" +
swordContext.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SWORDAuthenticationException("Cannot submit to the given collection with this context");
log.info(LogManager
.getHeader(context, "deposit_failed_authorisation",
"user=" +
swordContext.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SWORDAuthenticationException(
"Cannot submit to the given collection with this context");
}
// make a note of the authentication in the verbose string
swordService.message("Authenticated user: " + swordContext.getAuthenticated().getEmail());
swordService.message("Authenticated user: " +
swordContext.getAuthenticated().getEmail());
if (swordContext.getOnBehalfOf() != null)
{
swordService.message("Depositing on behalf of: " + swordContext.getOnBehalfOf().getEmail());
swordService.message("Depositing on behalf of: " +
swordContext.getOnBehalfOf().getEmail());
}
// determine which deposit engine we initialise
Depositor dep = null;
if (dso instanceof Collection)
{
swordService.message("Initialising depositor for an Item in a Collection");
swordService.message(
"Initialising depositor for an Item in a Collection");
dep = new CollectionDepositor(swordService, dso);
}
else if (dso instanceof Item)
{
swordService.message("Initialising depositor for a Bitstream in an Item");
swordService.message(
"Initialising depositor for a Bitstream in an Item");
dep = new ItemDepositor(swordService, dso);
}
if (dep == null)
{
log.error("The specified deposit target does not exist, or is not a collection or an item");
throw new DSpaceSWORDException("Deposit target is not a collection or an item");
log.error(
"The specified deposit target does not exist, or is not a collection or an item");
throw new DSpaceSWORDException(
"Deposit target is not a collection or an item");
}
DepositResult result = null;
@@ -160,7 +176,7 @@ public class DepositManager
{
storePackageAsFile(deposit);
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
}
@@ -186,18 +202,21 @@ public class DepositManager
DSpaceATOMEntry dsatom = null;
if (result.getItem() != null)
{
swordService.message("Initialising ATOM entry generator for an Item");
swordService
.message("Initialising ATOM entry generator for an Item");
dsatom = new ItemEntryGenerator(swordService);
}
else if (result.getBitstream() != null)
{
swordService.message("Initialising ATOM entry generator for a Bitstream");
swordService.message(
"Initialising ATOM entry generator for a Bitstream");
dsatom = new BitstreamEntryGenerator(swordService);
}
if (dsatom == null)
{
log.error("The deposit failed, see exceptions for explanation");
throw new DSpaceSWORDException("Result of deposit did not yield an Item or a Bitstream");
throw new DSpaceSWORDException(
"Result of deposit did not yield an Item or a Bitstream");
}
SWORDEntry entry = dsatom.getSWORDEntry(result, deposit);
@@ -206,15 +225,18 @@ public class DepositManager
if (deposit.isNoOp())
{
dep.undoDeposit(result);
swordService.message("NoOp Requested: Removed all traces of submission");
swordService.message(
"NoOp Requested: Removed all traces of submission");
}
entry.setNoOp(deposit.isNoOp());
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
swordService.message("Total time for deposit processing: " + delta + " ms");
entry.setVerboseDescription(swordService.getVerboseDescription().toString());
swordService
.message("Total time for deposit processing: " + delta + " ms");
entry.setVerboseDescription(
swordService.getVerboseDescription().toString());
response.setEntry(entry);
@@ -234,22 +256,27 @@ public class DepositManager
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory())
{
throw new IOException("Directory does not exist for writing packages on ingest error.");
throw new IOException(
"Directory does not exist for writing packages on ingest error.");
}
String filenameBase = "sword-" + deposit.getUsername() + "-" + (new Date()).getTime();
String filenameBase =
"sword-" + deposit.getUsername() + "-" + (new Date()).getTime();
File packageFile = new File(path, filenameBase);
File headersFile = new File(path, filenameBase + "-headers");
InputStream is = new BufferedInputStream(new FileInputStream(deposit.getFile()));
OutputStream fos = new BufferedOutputStream(new FileOutputStream(packageFile));
InputStream is = new BufferedInputStream(
new FileInputStream(deposit.getFile()));
OutputStream fos = new BufferedOutputStream(
new FileOutputStream(packageFile));
Utils.copy(is, fos);
fos.close();
is.close();
//write companion file with headers
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(headersFile)));
PrintWriter pw = new PrintWriter(
new BufferedWriter(new FileWriter(headersFile)));
pw.println("Content-Disposition=" + deposit.getContentDisposition());
pw.println("Content-Type=" + deposit.getContentType());

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -35,7 +35,6 @@ public class DepositResult
/** The media linkto the created object */
private String mediaLink;
public Bitstream getBitstream()
{
return bitstream;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -43,7 +43,8 @@ public abstract class Depositor
* @throws SWORDErrorException
* @throws DSpaceSWORDException
*/
public abstract DepositResult doDeposit(Deposit deposit) throws SWORDErrorException, DSpaceSWORDException;
public abstract DepositResult doDeposit(Deposit deposit)
throws SWORDErrorException, DSpaceSWORDException;
/**
* Undo any changes to the archive effected by the deposit
@@ -51,5 +52,6 @@ public abstract class Depositor
* @param result
* @throws DSpaceSWORDException
*/
public abstract void undoDeposit(DepositResult result) throws DSpaceSWORDException;
public abstract void undoDeposit(DepositResult result)
throws DSpaceSWORDException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -24,7 +24,8 @@ import java.util.List;
*/
public class ItemCollectionGenerator extends ATOMCollectionGenerator
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
public ItemCollectionGenerator(SWORDService service)
{
@@ -39,11 +40,13 @@ public class ItemCollectionGenerator extends ATOMCollectionGenerator
* @param dso the dso for which the collection should be build
* @throws DSpaceSWORDException if the dso is not an instance of Item
*/
public Collection buildCollection(DSpaceObject dso) throws DSpaceSWORDException
public Collection buildCollection(DSpaceObject dso)
throws DSpaceSWORDException
{
if (!(dso instanceof Item))
{
throw new DSpaceSWORDException("Incorrect ATOMCollectionGenerator instantiated");
throw new DSpaceSWORDException(
"Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
@@ -60,7 +63,8 @@ public class ItemCollectionGenerator extends ATOMCollectionGenerator
// the item title is the sword collection title, or "untitled" otherwise
String title = "Untitled";
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, "dc.title");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.title");
if (!dcv.isEmpty())
{
String firstValue = dcv.get(0).getValue();
@@ -77,7 +81,8 @@ public class ItemCollectionGenerator extends ATOMCollectionGenerator
// abstract is the short description of the item, if it exists
String dcAbstract = "";
List<MetadataValue> dcva = itemService.getMetadataByMetadataString(item, "dc.description.abstract");
List<MetadataValue> dcva = itemService
.getMetadataByMetadataString(item, "dc.description.abstract");
if (!dcva.isEmpty())
{
String firstValue = dcva.get(0).getValue();

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -29,10 +29,17 @@ import java.util.List;
public class ItemDepositor extends Depositor
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
private Item item;
@@ -43,14 +50,16 @@ public class ItemDepositor extends Depositor
if (!(dso instanceof Item))
{
throw new DSpaceSWORDException("You tried to initialise the item depositor with something" +
throw new DSpaceSWORDException(
"You tried to initialise the item depositor with something" +
"other than an item object");
}
this.item = (Item) dso;
}
public DepositResult doDeposit(Deposit deposit) throws SWORDErrorException, DSpaceSWORDException
public DepositResult doDeposit(Deposit deposit)
throws SWORDErrorException, DSpaceSWORDException
{
// get the things out of the service that we need
Context context = swordService.getContext();
@@ -61,22 +70,28 @@ public class ItemDepositor extends Depositor
// the throw a 415 (ERROR_CONTENT) until further notice
//
// determine if this is an acceptable file format
if (!swordConfig.isAcceptableContentType(context, deposit.getContentType(), item))
if (!swordConfig
.isAcceptableContentType(context, deposit.getContentType(),
item))
{
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable content type in deposit request: " + deposit.getContentType());
"Unacceptable content type in deposit request: " +
deposit.getContentType());
}
// determine if this is an acceptable packaging type for the deposit
// if not, we throw a 415 HTTP error (Unsupported Media Type, ERROR_CONTENT)
if (!swordConfig.isSupportedMediaType(deposit.getPackaging(), this.item))
if (!swordConfig
.isSupportedMediaType(deposit.getPackaging(), this.item))
{
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"Unacceptable packaging type in deposit request: " + deposit.getPackaging());
"Unacceptable packaging type in deposit request: " +
deposit.getPackaging());
}
// Obtain the relevant ingester from the factory
SWORDIngester si = SWORDIngesterFactory.getInstance(context, deposit, item);
SWORDIngester si = SWORDIngesterFactory
.getInstance(context, deposit, item);
swordService.message("Loaded ingester: " + si.getClass().getName());
// do the deposit
@@ -89,14 +104,16 @@ public class ItemDepositor extends Depositor
{
if (swordConfig.isKeepOriginal())
{
swordService.message("DSpace will store an original copy of the deposit file, " +
swordService.message(
"DSpace will store an original copy of the deposit file, " +
"as well as attaching it to the item");
// in order to be allowed to add the file back to the item, we need to ignore authorisations
// for a moment
context.turnOffAuthorisationSystem();
String bundleName = ConfigurationManager.getProperty("sword-server", "bundle.name");
String bundleName = ConfigurationManager
.getProperty("sword-server", "bundle.name");
if (StringUtils.isBlank(bundleName))
{
bundleName = "SWORD";
@@ -115,7 +132,8 @@ public class ItemDepositor extends Depositor
}
if (swordBundle == null)
{
swordBundle = bundleService.create(context, item, bundleName);
swordBundle = bundleService
.create(context, item, bundleName);
}
String fn = swordService.getFilename(context, deposit, true);
@@ -125,7 +143,8 @@ public class ItemDepositor extends Depositor
try
{
fis = new FileInputStream(deposit.getFile());
bitstream = bitstreamService.create(context, swordBundle, fis);
bitstream = bitstreamService
.create(context, swordBundle, fis);
}
finally
{
@@ -135,9 +154,11 @@ public class ItemDepositor extends Depositor
}
}
bitstream.setName(context, fn);
bitstream.setDescription(context, "Original file deposited via SWORD");
bitstream.setDescription(context,
"Original file deposited via SWORD");
BitstreamFormat bf = bitstreamFormatService.findByMIMEType(context, deposit.getContentType());
BitstreamFormat bf = bitstreamFormatService
.findByMIMEType(context, deposit.getContentType());
if (bf != null)
{
bitstreamService.setFormat(context, bitstream, bf);
@@ -147,7 +168,8 @@ public class ItemDepositor extends Depositor
bundleService.update(context, swordBundle);
itemService.update(context, item);
swordService.message("Original package stored as " + fn + ", in item bundle " + swordBundle);
swordService.message("Original package stored as " + fn +
", in item bundle " + swordBundle);
// now reset the context ignore authorisation
context.restoreAuthSystemState();
@@ -158,7 +180,8 @@ public class ItemDepositor extends Depositor
else
{
// set the media link for the created item using the archived version (since it's just a file)
result.setMediaLink(urlManager.getMediaLink(result.getBitstream()));
result.setMediaLink(
urlManager.getMediaLink(result.getBitstream()));
}
}
catch (SQLException | AuthorizeException | IOException e)
@@ -174,7 +197,8 @@ public class ItemDepositor extends Depositor
try
{
SWORDContext sc = swordService.getSwordContext();
BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
// obtain the bitstream's owning bundles and remove the bitstream
// from them. This will ensure that the bitstream is physically

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -31,8 +31,11 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
/** logger */
private static Logger log = Logger.getLogger(ItemEntryGenerator.class);
protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected ItemEntryGenerator(SWORDService service)
{
@@ -46,10 +49,12 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
*/
protected void addCategories()
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, "dc.subject.*");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.subject.*");
if (dcv != null)
{
for (MetadataValue aDcv : dcv) {
for (MetadataValue aDcv : dcv)
{
entry.addCategory(aDcv.getValue());
}
}
@@ -78,8 +83,11 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
if (StringUtils.isNotBlank(handle))
{
boolean keepOriginal = ConfigurationManager.getBooleanProperty("sword-server", "keep-original-package");
String swordBundle = ConfigurationManager.getProperty("sword-server", "bundle.name");
boolean keepOriginal = ConfigurationManager
.getBooleanProperty("sword-server",
"keep-original-package");
String swordBundle = ConfigurationManager
.getProperty("sword-server", "bundle.name");
if (StringUtils.isBlank(swordBundle))
{
swordBundle = "SWORD";
@@ -93,18 +101,25 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
List<Bundle> bundles = item.getBundles();
for (Bundle bundle : bundles)
{
if (swordBundle.equals(bundle.getName())) {
List<BundleBitstream> bss = bundle.getBitstreams();
for (BundleBitstream bs : bss) {
BitstreamFormat bf = bs.getBitstream().getFormat(swordService.getContext());
if (swordBundle.equals(bundle.getName()))
{
List<BundleBitstream> bss = bundle
.getBitstreams();
for (BundleBitstream bs : bss)
{
BitstreamFormat bf = bs.getBitstream()
.getFormat(
swordService.getContext());
String format = "application/octet-stream";
if (bf != null) {
if (bf != null)
{
format = bf.getMIMEType();
}
con.setType(format);
// calculate the bitstream link.
String bsLink = urlManager.getBitstreamUrl(bs.getBitstream());
String bsLink = urlManager
.getBitstreamUrl(bs.getBitstream());
con.setSource(bsLink);
entry.setContent(con);
@@ -118,7 +133,8 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
// return a link to the DSpace entry page
Content content = new Content();
content.setType("text/html");
content.setSource(handleService.getCanonicalForm(handle));
content.setSource(
handleService.getCanonicalForm(handle));
entry.setContent(content);
}
}
@@ -193,17 +209,23 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
// link to all the files in the item
List<Bundle> bundles = item.getBundles();
for (Bundle bundle : bundles) {
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName())) {
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
{
List<BundleBitstream> bss = bundle.getBitstreams();
for (BundleBitstream bs : bss) {
for (BundleBitstream bs : bss)
{
Link link = new Link();
String url = urlManager.getBitstreamUrl(bs.getBitstream());
String url = urlManager
.getBitstreamUrl(bs.getBitstream());
link.setHref(url);
link.setRel("part");
BitstreamFormat bsf = bs.getBitstream().getFormat(swordService.getContext());
if (bsf != null) {
BitstreamFormat bsf = bs.getBitstream()
.getFormat(swordService.getContext());
if (bsf != null)
{
link.setType(bsf.getMIMEType());
}
@@ -232,14 +254,14 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
*/
protected void addPublishDate()
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, "dc.date.issued");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.date.issued");
if (dcv != null && !dcv.isEmpty())
{
entry.setPublished(dcv.get(0).getValue());
}
}
/**
* Add rights information. This attaches an href to the URL
* of the item's licence file
@@ -268,7 +290,8 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
StringBuilder rightsString = new StringBuilder();
List<Bundle> bundles = item.getBundles();
for (Bundle bundle : bundles) {
for (Bundle bundle : bundles)
{
if (Constants.LICENSE_BUNDLE_NAME.equals(bundle.getName()))
{
List<BundleBitstream> bss = bundle.getBitstreams();
@@ -293,7 +316,8 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
*/
protected void addSummary()
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, "dc.description.abstract");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.description.abstract");
if (dcv != null)
{
for (MetadataValue aDcv : dcv)
@@ -312,7 +336,8 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
*/
protected void addTitle()
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, "dc.title");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.title");
if (dcv != null)
{
for (MetadataValue aDcv : dcv)
@@ -331,8 +356,10 @@ public class ItemEntryGenerator extends DSpaceATOMEntry
*/
protected void addLastUpdatedDate()
{
String config = ConfigurationManager.getProperty("sword-server", "updated.field");
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, config);
String config = ConfigurationManager
.getProperty("sword-server", "updated.field");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, config);
if (dcv != null && dcv.size() == 1)
{
DCDate dcd = new DCDate(dcv.get(0).getValue());

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -32,10 +32,11 @@ public class LoadDSpaceConfig extends HttpServlet
{
public void init()
{
if(!ConfigurationManager.isConfigured())
if (!ConfigurationManager.isConfigured())
{
// Get config parameter
String config = getServletContext().getInitParameter("dspace-config");
String config = getServletContext()
.getInitParameter("dspace-config");
// Load in DSpace config
ConfigurationManager.loadConfig(config);

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -52,7 +52,9 @@ public class MediaEntryManager
// FIXME: what do we actually do about this situation?
// throwing an error for the time being
throw new SWORDErrorException(DSpaceSWORDErrorCodes.MEDIA_UNAVAILABLE, "The media link you requested is not available");
throw new SWORDErrorException(
DSpaceSWORDErrorCodes.MEDIA_UNAVAILABLE,
"The media link you requested is not available");
}
// extract the thing that we are trying to get a media entry on
@@ -61,7 +63,8 @@ public class MediaEntryManager
// now, the media entry should always be to an actual file, so we only care that this is a bitstream
if (!(dso instanceof Bitstream))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The url you provided does not resolve to an appropriate object");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"The url you provided does not resolve to an appropriate object");
}
// now construct the atom entry for the bitstream

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -33,7 +33,8 @@ public class SWORDAuthentication
*/
public boolean authenticates(Context context, String un, String pw)
{
AuthenticationService authService = AuthenticateServiceFactory.getInstance().getAuthenticationService();
AuthenticationService authService = AuthenticateServiceFactory
.getInstance().getAuthenticationService();
int auth = authService.authenticate(context, un, pw, null, null);
return auth == AuthenticationMethod.SUCCESS;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -50,12 +50,23 @@ public class SWORDAuthenticator
/** logger */
private static Logger log = Logger.getLogger(SWORDAuthenticator.class);
protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected AuthenticationService authenticationService = AuthenticateServiceFactory
.getInstance().getAuthenticationService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory
.getInstance().getAuthorizeService();
protected EPersonService ePersonService = EPersonServiceFactory
.getInstance().getEPersonService();
protected CommunityService communityService = ContentServiceFactory
.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
/**
* Does the given username and password authenticate for the
@@ -68,7 +79,8 @@ public class SWORDAuthenticator
*/
public boolean authenticates(Context context, String un, String pw)
{
int auth = authenticationService.authenticate(context, un, pw, null, null);
int auth = authenticationService
.authenticate(context, un, pw, null, null);
return auth == AuthenticationMethod.SUCCESS;
}
@@ -101,7 +113,8 @@ public class SWORDAuthenticator
* @throws SWORDAuthenticationException
*/
public SWORDContext authenticate(ServiceDocumentRequest request)
throws SWORDException, SWORDErrorException, SWORDAuthenticationException
throws SWORDException, SWORDErrorException,
SWORDAuthenticationException
{
Context context = this.constructContext(request.getIPAddress());
SWORDContext sc;
@@ -131,7 +144,8 @@ public class SWORDAuthenticator
* @throws SWORDAuthenticationException
*/
public SWORDContext authenticate(AtomDocumentRequest request)
throws SWORDException, SWORDErrorException, SWORDAuthenticationException
throws SWORDException, SWORDErrorException,
SWORDAuthenticationException
{
Context context = this.constructContext(request.getIPAddress());
SWORDContext sc = null;
@@ -160,10 +174,13 @@ public class SWORDAuthenticator
* @throws org.purl.sword.base.SWORDAuthenticationException
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, AtomDocumentRequest request)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
private SWORDContext authenticate(Context context,
AtomDocumentRequest request)
throws SWORDAuthenticationException, SWORDException,
SWORDErrorException
{
return this.authenticate(context, request.getUsername(), request.getPassword(), null, request.getIPAddress());
return this.authenticate(context, request.getUsername(),
request.getPassword(), null, request.getIPAddress());
}
/**
@@ -176,10 +193,14 @@ public class SWORDAuthenticator
* @throws org.purl.sword.base.SWORDAuthenticationException
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, ServiceDocumentRequest request)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
private SWORDContext authenticate(Context context,
ServiceDocumentRequest request)
throws SWORDAuthenticationException, SWORDException,
SWORDErrorException
{
return this.authenticate(context, request.getUsername(), request.getPassword(), request.getOnBehalfOf(), request.getIPAddress());
return this.authenticate(context, request.getUsername(),
request.getPassword(), request.getOnBehalfOf(),
request.getIPAddress());
}
/**
@@ -191,7 +212,8 @@ public class SWORDAuthenticator
* @throws SWORDAuthenticationException
*/
public SWORDContext authenticate(Deposit deposit)
throws SWORDException, SWORDErrorException, SWORDAuthenticationException
throws SWORDException, SWORDErrorException,
SWORDAuthenticationException
{
Context context = this.constructContext(deposit.getIPAddress());
SWORDContext sc = null;
@@ -221,9 +243,12 @@ public class SWORDAuthenticator
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, Deposit deposit)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
throws SWORDAuthenticationException, SWORDException,
SWORDErrorException
{
return this.authenticate(context, deposit.getUsername(), deposit.getPassword(), deposit.getOnBehalfOf(), deposit.getIPAddress());
return this.authenticate(context, deposit.getUsername(),
deposit.getPassword(), deposit.getOnBehalfOf(),
deposit.getIPAddress());
}
/**
@@ -239,8 +264,10 @@ public class SWORDAuthenticator
* @throws SWORDAuthenticationException
* @throws SWORDException
*/
private SWORDContext authenticate(Context context, String un, String pw, String obo, String ip)
throws SWORDAuthenticationException, SWORDException, SWORDErrorException
private SWORDContext authenticate(Context context, String un, String pw,
String obo, String ip)
throws SWORDAuthenticationException, SWORDException,
SWORDErrorException
{
// smooth out the OnBehalfOf request, so that empty strings are
// treated as null
@@ -250,15 +277,19 @@ public class SWORDAuthenticator
}
// first find out if we support on-behalf-of deposit
boolean mediated = ConfigurationManager.getBooleanProperty("sword-server", "on-behalf-of.enable");
boolean mediated = ConfigurationManager
.getBooleanProperty("sword-server", "on-behalf-of.enable");
if (!mediated && obo != null)
{
// user is trying to do a mediated deposit on a repository which does not support it
log.error("Attempted mediated deposit on service not configured to do so");
throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED, "Mediated deposit to this service is not permitted");
log.error(
"Attempted mediated deposit on service not configured to do so");
throw new SWORDErrorException(ErrorCodes.MEDIATION_NOT_ALLOWED,
"Mediated deposit to this service is not permitted");
}
log.info(LogManager.getHeader(context, "sword_authenticate", "username=" + un + ",on_behalf_of=" + obo));
log.info(LogManager.getHeader(context, "sword_authenticate",
"username=" + un + ",on_behalf_of=" + obo));
try
{
@@ -276,7 +307,8 @@ public class SWORDAuthenticator
authenticated = true;
sc.setAuthenticated(ep);
// Set any special groups - invoke the authentication mgr.
List<Group> groups = authenticationService.getSpecialGroups(context, null);
List<Group> groups = authenticationService
.getSpecialGroups(context, null);
for (Group group : groups)
{
@@ -306,19 +338,23 @@ public class SWORDAuthenticator
Context oboContext = this.constructContext(ip);
oboContext.setCurrentUser(epObo);
// Set any special groups - invoke the authentication mgr.
List<Group> groups = authenticationService.getSpecialGroups(oboContext, null);
List<Group> groups = authenticationService
.getSpecialGroups(oboContext, null);
for (Group group : groups)
{
oboContext.setSpecialGroup(group.getID());
log.debug("Adding Special Group id=" + group.getID());
log.debug(
"Adding Special Group id=" + group.getID());
}
sc.setContext(oboContext);
}
else
{
authenticated = false;
throw new SWORDErrorException(ErrorCodes.TARGET_OWNER_UKNOWN, "unable to identify on-behalf-of user: " + obo);
throw new SWORDErrorException(
ErrorCodes.TARGET_OWNER_UKNOWN,
"unable to identify on-behalf-of user: " + obo);
}
}
}
@@ -328,15 +364,21 @@ public class SWORDAuthenticator
// decide what kind of error to throw
if (ep != null)
{
log.info(LogManager.getHeader(context, "sword_unable_to_set_user", "username=" + un));
throw new SWORDAuthenticationException("Unable to authenticate the supplied used");
log.info(LogManager
.getHeader(context, "sword_unable_to_set_user",
"username=" + un));
throw new SWORDAuthenticationException(
"Unable to authenticate the supplied used");
}
else
{
// FIXME: this shouldn't ever happen now, but may as well leave it in just in case
// there's a bug elsewhere
log.info(LogManager.getHeader(context, "sword_unable_to_set_on_behalf_of", "username=" + un + ",on_behalf_of=" + obo));
throw new SWORDAuthenticationException("Unable to authenticate the onBehalfOf account");
log.info(LogManager.getHeader(context,
"sword_unable_to_set_on_behalf_of",
"username=" + un + ",on_behalf_of=" + obo));
throw new SWORDAuthenticationException(
"Unable to authenticate the onBehalfOf account");
}
}
@@ -345,7 +387,9 @@ public class SWORDAuthenticator
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new SWORDException("There was a problem accessing the repository user database", e);
throw new SWORDException(
"There was a problem accessing the repository user database",
e);
}
}
@@ -359,7 +403,8 @@ public class SWORDAuthenticator
* @return true if yes, false if not
* @throws DSpaceSWORDException
*/
public boolean canSubmit(SWORDService swordService, Deposit deposit, DSpaceObject dso)
public boolean canSubmit(SWORDService swordService, Deposit deposit,
DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException
{
// get the things we need out of the service
@@ -374,7 +419,8 @@ public class SWORDAuthenticator
}
else
{
swordService.message("User is not authorised to submit to collection");
swordService
.message("User is not authorised to submit to collection");
}
return submit;
@@ -395,7 +441,8 @@ public class SWORDAuthenticator
try
{
EPerson authenticated = swordContext.getAuthenticated();
return authenticated != null && authorizeService.isAdmin(swordContext.getAuthenticatorContext());
return authenticated != null && authorizeService
.isAdmin(swordContext.getAuthenticatorContext());
}
catch (SQLException e)
{
@@ -419,7 +466,8 @@ public class SWORDAuthenticator
EPerson onBehalfOf = swordContext.getOnBehalfOf();
try
{
return onBehalfOf != null && authorizeService.isAdmin(swordContext.getOnBehalfOfContext());
return onBehalfOf != null && authorizeService
.isAdmin(swordContext.getOnBehalfOfContext());
}
catch (SQLException e)
{
@@ -434,7 +482,8 @@ public class SWORDAuthenticator
*
* @param group
*/
public boolean isUserInGroup(SWORDContext swordContext, Group group) {
public boolean isUserInGroup(SWORDContext swordContext, Group group)
{
EPerson authenticated = swordContext.getAuthenticated();
return authenticated != null && isInGroup(group, authenticated);
}
@@ -445,7 +494,8 @@ public class SWORDAuthenticator
*
* @param group
*/
public boolean isOnBehalfOfInGroup(SWORDContext swordContext, Group group) {
public boolean isOnBehalfOfInGroup(SWORDContext swordContext, Group group)
{
EPerson onBehalfOf = swordContext.getOnBehalfOf();
return onBehalfOf != null && isInGroup(group, onBehalfOf);
}
@@ -537,7 +587,8 @@ public class SWORDAuthenticator
boolean oboAllowed = false;
// check for obo null
if (swordContext.getOnBehalfOf() == null) {
if (swordContext.getOnBehalfOf() == null)
{
oboAllowed = true;
}
@@ -545,14 +596,18 @@ public class SWORDAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), comm, Constants.READ);
authAllowed = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), comm,
Constants.READ);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), comm, Constants.READ);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), comm,
Constants.READ);
}
// final check to see if we are allowed to READ
@@ -592,7 +647,8 @@ public class SWORDAuthenticator
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<Community> getCommunities(SWORDContext swordContext, Community community)
public List<Community> getCommunities(SWORDContext swordContext,
Community community)
throws DSpaceSWORDException
{
// a community is allowed if the following conditions are met
@@ -625,14 +681,18 @@ public class SWORDAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), comm, Constants.READ);
authAllowed = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), comm,
Constants.READ);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), comm, Constants.READ);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), comm,
Constants.READ);
}
// final check to see if we are allowed to READ
@@ -665,7 +725,8 @@ public class SWORDAuthenticator
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<org.dspace.content.Collection> getAllowedCollections(SWORDContext swordContext)
public List<org.dspace.content.Collection> getAllowedCollections(
SWORDContext swordContext)
throws DSpaceSWORDException
{
return this.getAllowedCollections(swordContext, null);
@@ -690,7 +751,8 @@ public class SWORDAuthenticator
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<org.dspace.content.Collection> getAllowedCollections(SWORDContext swordContext, Community community)
public List<org.dspace.content.Collection> getAllowedCollections(
SWORDContext swordContext, Community community)
throws DSpaceSWORDException
{
// a collection is allowed if the following conditions are met
@@ -710,7 +772,8 @@ public class SWORDAuthenticator
Context authContext = swordContext.getAuthenticatorContext();
// short cut by obtaining the collections to which the authenticated user can submit
List<Collection> cols = collectionService.findAuthorized(authContext, community, Constants.ADD);
List<Collection> cols = collectionService
.findAuthorized(authContext, community, Constants.ADD);
List<org.dspace.content.Collection> allowed = new ArrayList<>();
// now find out if the obo user is allowed to submit to any of these collections
@@ -728,7 +791,9 @@ public class SWORDAuthenticator
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), col, Constants.ADD);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), col,
Constants.ADD);
}
// final check to see if we are allowed to READ
@@ -766,7 +831,8 @@ public class SWORDAuthenticator
* @return the array of allowed collections
* @throws DSpaceSWORDException
*/
public List<Item> getAllowedItems(SWORDContext swordContext, org.dspace.content.Collection collection)
public List<Item> getAllowedItems(SWORDContext swordContext,
org.dspace.content.Collection collection)
throws DSpaceSWORDException
{
// an item is allowed if the following conditions are met
@@ -783,7 +849,8 @@ public class SWORDAuthenticator
try
{
List<Item> allowed = new ArrayList<>();
Iterator<Item> ii = itemService.findByCollection(swordContext.getContext(), collection);
Iterator<Item> ii = itemService
.findByCollection(swordContext.getContext(), collection);
while (ii.hasNext())
{
@@ -805,14 +872,19 @@ public class SWORDAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
boolean write = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), item, Constants.WRITE);
boolean write = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), item,
Constants.WRITE);
boolean add = false;
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
if (Constants.CONTENT_BUNDLE_NAME
.equals(bundle.getName()))
{
add = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), bundle, Constants.ADD);
add = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(),
bundle, Constants.ADD);
if (!add)
{
break;
@@ -827,13 +899,18 @@ public class SWORDAuthenticator
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
boolean write = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), item, Constants.WRITE);
boolean write = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), item,
Constants.WRITE);
boolean add = false;
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
add = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), bundle, Constants.ADD);
if (Constants.CONTENT_BUNDLE_NAME
.equals(bundle.getName()))
add = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), bundle,
Constants.ADD);
if (!add)
{
break;
@@ -877,7 +954,8 @@ public class SWORDAuthenticator
* @param collection
* @throws DSpaceSWORDException
*/
public boolean canSubmitTo(SWORDContext swordContext, org.dspace.content.Collection collection)
public boolean canSubmitTo(SWORDContext swordContext,
org.dspace.content.Collection collection)
throws DSpaceSWORDException
{
// a user can submit to a collection in the following conditions:
@@ -906,14 +984,18 @@ public class SWORDAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), collection, Constants.ADD);
authAllowed = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), collection,
Constants.ADD);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), collection, Constants.ADD);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), collection,
Constants.ADD);
}
// final check to see if we are allowed to READ
@@ -979,14 +1061,18 @@ public class SWORDAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
boolean write = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), item, Constants.WRITE);
boolean write = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), item,
Constants.WRITE);
boolean add = false;
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
{
add = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), bundle, Constants.ADD);
add = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), bundle,
Constants.ADD);
if (!add)
{
break;
@@ -1001,14 +1087,18 @@ public class SWORDAuthenticator
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
boolean write = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), item, Constants.WRITE);
boolean write = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), item,
Constants.WRITE);
boolean add = false;
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
{
add = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), bundle, Constants.ADD);
add = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), bundle,
Constants.ADD);
if (!add)
{
break;
@@ -1045,7 +1135,8 @@ public class SWORDAuthenticator
{
if (dso instanceof org.dspace.content.Collection)
{
return this.canSubmitTo(context, (org.dspace.content.Collection) dso);
return this
.canSubmitTo(context, (org.dspace.content.Collection) dso);
}
else
{

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -48,7 +48,8 @@ public class SWORDConfiguration
/** logger */
public static final Logger log = Logger.getLogger(SWORDConfiguration.class);
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
/** whether we can support noOp */
private boolean noOp = true;
@@ -84,33 +85,41 @@ public class SWORDConfiguration
public SWORDConfiguration()
{
// set the max upload size
int mus = ConfigurationManager.getIntProperty("sword-server", "max-upload-size");
int mus = ConfigurationManager
.getIntProperty("sword-server", "max-upload-size");
if (mus > 0)
{
this.maxUploadSize = mus;
}
// set the mediation value
this.mediated = ConfigurationManager.getBooleanProperty("sword-server", "on-behalf-of.enable");
this.mediated = ConfigurationManager
.getBooleanProperty("sword-server", "on-behalf-of.enable");
// find out if we keep the original as bitstream
this.keepOriginal = ConfigurationManager.getBooleanProperty("sword-server", "keep-original-package");
this.keepOriginal = ConfigurationManager
.getBooleanProperty("sword-server", "keep-original-package");
// get the sword bundle
String bundle = ConfigurationManager.getProperty("sword-server", "bundle.name");
String bundle = ConfigurationManager
.getProperty("sword-server", "bundle.name");
if (bundle != null && "".equals(bundle))
{
this.swordBundle = bundle;
}
// find out if we keep the package as a file in specified directory
this.keepPackageOnFailedIngest = ConfigurationManager.getBooleanProperty("sword-server", "keep-package-on-fail", false);
this.keepPackageOnFailedIngest = ConfigurationManager
.getBooleanProperty("sword-server", "keep-package-on-fail",
false);
// get directory path and name
this.failedPackageDir = ConfigurationManager.getProperty("sword-server", "failed-package.dir");
this.failedPackageDir = ConfigurationManager
.getProperty("sword-server", "failed-package.dir");
// Get the accepted formats
String acceptsProperty = ConfigurationManager.getProperty("sword-server", "accepts");
String acceptsProperty = ConfigurationManager
.getProperty("sword-server", "accepts");
swordaccepts = new ArrayList<String>();
if (acceptsProperty == null)
{
@@ -287,8 +296,10 @@ public class SWORDConfiguration
}
else if (dso instanceof Item)
{
List<BitstreamFormat> bfs = bitstreamFormatService.findNonInternal(context);
for (BitstreamFormat bf : bfs) {
List<BitstreamFormat> bfs = bitstreamFormatService
.findNonInternal(context);
for (BitstreamFormat bf : bfs)
{
accepts.add(bf.getMIMEType());
}
}
@@ -421,7 +432,8 @@ public class SWORDConfiguration
if (dso instanceof Collection)
{
Map<String, Float> accepts = this.getAcceptPackaging((Collection) dso);
Map<String, Float> accepts = this
.getAcceptPackaging((Collection) dso);
for (String accept : accepts.keySet())
{
if (accept.equals(mediaType))
@@ -445,7 +457,8 @@ public class SWORDConfiguration
* @param dso
* @throws DSpaceSWORDException
*/
public boolean isAcceptableContentType(Context context, String type, DSpaceObject dso)
public boolean isAcceptableContentType(Context context, String type,
DSpaceObject dso)
throws DSpaceSWORDException
{
List<String> accepts = this.getAccepts(context, dso);
@@ -461,6 +474,8 @@ public class SWORDConfiguration
throws DSpaceSWORDException
{
return (ConfigurationManager.getProperty("upload.temp.dir") != null)
? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir");
?
ConfigurationManager.getProperty("upload.temp.dir") :
System.getProperty("java.io.tmpdir");
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -30,5 +30,7 @@ public interface SWORDIngester
* @return the result of the deposit
* @throws DSpaceSWORDException
*/
DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject target) throws DSpaceSWORDException, SWORDErrorException;
DepositResult ingest(SWORDService service, Deposit deposit,
DSpaceObject target)
throws DSpaceSWORDException, SWORDErrorException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -40,28 +40,36 @@ public class SWORDIngesterFactory
* @param deposit
* @throws DSpaceSWORDException
*/
public static SWORDIngester getInstance(Context context, Deposit deposit, DSpaceObject dso)
public static SWORDIngester getInstance(Context context, Deposit deposit,
DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException
{
if (dso instanceof Collection)
{
SWORDIngester ingester = (SWORDIngester) PluginManager.getNamedPlugin("sword-server", SWORDIngester.class, deposit.getPackaging());
SWORDIngester ingester = (SWORDIngester) PluginManager
.getNamedPlugin("sword-server", SWORDIngester.class,
deposit.getPackaging());
if (ingester == null)
{
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT, "No ingester configured for this package type");
throw new SWORDErrorException(ErrorCodes.ERROR_CONTENT,
"No ingester configured for this package type");
}
return ingester;
}
else if (dso instanceof Item)
{
SWORDIngester ingester = (SWORDIngester) PluginManager.getNamedPlugin("sword-server", SWORDIngester.class, "SimpleFileIngester");
SWORDIngester ingester = (SWORDIngester) PluginManager
.getNamedPlugin("sword-server", SWORDIngester.class,
"SimpleFileIngester");
if (ingester == null)
{
throw new DSpaceSWORDException("SimpleFileIngester is not configured in plugin manager");
throw new DSpaceSWORDException(
"SimpleFileIngester is not configured in plugin manager");
}
return ingester;
}
throw new DSpaceSWORDException("No ingester could be found which works for this DSpace Object");
throw new DSpaceSWORDException(
"No ingester could be found which works for this DSpace Object");
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -33,7 +33,9 @@ import org.purl.sword.base.SWORDErrorException;
public class SWORDMETSIngester implements SWORDIngester
{
private SWORDService swordService;
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
/** Log4j logger */
public static final Logger log = Logger.getLogger(SWORDMETSIngester.class);
@@ -41,7 +43,8 @@ public class SWORDMETSIngester implements SWORDIngester
/* (non-Javadoc)
* @see org.dspace.sword.SWORDIngester#ingest(org.dspace.core.Context, org.purl.sword.base.Deposit)
*/
public DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject dso)
public DepositResult ingest(SWORDService service, Deposit deposit,
DSpaceObject dso)
throws DSpaceSWORDException, SWORDErrorException
{
try
@@ -49,7 +52,8 @@ public class SWORDMETSIngester implements SWORDIngester
// first, make sure this is the right kind of ingester, and set the collection
if (!(dso instanceof Collection))
{
throw new DSpaceSWORDException("Tried to run an ingester on wrong target type");
throw new DSpaceSWORDException(
"Tried to run an ingester on wrong target type");
}
Collection collection = (Collection) dso;
@@ -63,15 +67,18 @@ public class SWORDMETSIngester implements SWORDIngester
File depositFile = deposit.getFile();
// load the plugin manager for the required configuration
String cfg = ConfigurationManager.getProperty("sword-server", "mets-ingester.package-ingester");
String cfg = ConfigurationManager.getProperty("sword-server",
"mets-ingester.package-ingester");
if (cfg == null || "".equals(cfg))
{
cfg = "METS"; // default to METS
}
swordService.message("Using package manifest format: " + cfg);
PackageIngester pi = (PackageIngester) PluginManager.getNamedPlugin(PackageIngester.class, cfg);
swordService.message("Loaded package ingester: " + pi.getClass().getName());
PackageIngester pi = (PackageIngester) PluginManager
.getNamedPlugin(PackageIngester.class, cfg);
swordService.message(
"Loaded package ingester: " + pi.getClass().getName());
// the licence is either in the zip or the mets manifest. Either way
// it's none of our business here
@@ -84,26 +91,36 @@ public class SWORDMETSIngester implements SWORDIngester
params.setWorkflowEnabled(true);
// Should restore mode be enabled, i.e. keep existing handle?
if (ConfigurationManager.getBooleanProperty("sword-server", "restore-mode.enable",false))
if (ConfigurationManager
.getBooleanProperty("sword-server", "restore-mode.enable",
false))
{
params.setRestoreModeEnabled(true);
}
// Whether or not to use the collection template
params.setUseCollectionTemplate(ConfigurationManager.getBooleanProperty("mets.default.ingest.useCollectionTemplate", false));
params.setUseCollectionTemplate(ConfigurationManager
.getBooleanProperty(
"mets.default.ingest.useCollectionTemplate",
false));
// ingest the item from the temp file
DSpaceObject ingestedObject = pi.ingest(context, collection, depositFile, params, licence);
DSpaceObject ingestedObject = pi
.ingest(context, collection, depositFile, params, licence);
if (ingestedObject == null)
{
swordService.message("Failed to ingest the package; throwing exception");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.UNPACKAGE_FAIL, "METS package ingester failed to unpack package");
swordService.message(
"Failed to ingest the package; throwing exception");
throw new SWORDErrorException(
DSpaceSWORDErrorCodes.UNPACKAGE_FAIL,
"METS package ingester failed to unpack package");
}
//Verify we have an Item as a result -- SWORD can only ingest Items
if (!(ingestedObject instanceof Item))
{
throw new DSpaceSWORDException("DSpace Ingester returned wrong object type -- not an Item result.");
throw new DSpaceSWORDException(
"DSpace Ingester returned wrong object type -- not an Item result.");
}
else
{
@@ -112,7 +129,7 @@ public class SWORDMETSIngester implements SWORDIngester
}
// get reference to item so that we can report on it
Item installedItem = (Item)ingestedObject;
Item installedItem = (Item) ingestedObject;
// update the item metadata to inclue the current time as
// the updated date
@@ -132,18 +149,22 @@ public class SWORDMETSIngester implements SWORDIngester
// for some reason, DSpace will not give you the handle automatically,
// so we have to look it up
HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService();
String handle = handleService.findHandle(context, installedItem);
swordService.message("Ingest successful");
swordService.message("Item created with internal identifier: " + installedItem.getID());
swordService.message("Item created with internal identifier: " +
installedItem.getID());
if (handle != null)
{
swordService.message("Item created with external identifier: " + handle);
swordService.message(
"Item created with external identifier: " + handle);
}
else
{
swordService.message("No external identifier available at this stage (item in workflow)");
swordService.message(
"No external identifier available at this stage (item in workflow)");
}
DepositResult dr = new DepositResult();
@@ -178,23 +199,31 @@ public class SWORDMETSIngester implements SWORDIngester
private void setUpdatedDate(Context context, Item item)
throws DSpaceSWORDException
{
String field = ConfigurationManager.getProperty("sword-server", "updated.field");
String field = ConfigurationManager
.getProperty("sword-server", "updated.field");
if (field == null || "".equals(field))
{
throw new DSpaceSWORDException("No configuration, or configuration is invalid for: sword.updated.field");
throw new DSpaceSWORDException(
"No configuration, or configuration is invalid for: sword.updated.field");
}
MetadataFieldInfo dc = this.configToDC(field, null);
try {
itemService.clearMetadata(context, item, dc.schema, dc.element, dc.qualifier, Item.ANY);
try
{
itemService.clearMetadata(context, item, dc.schema, dc.element,
dc.qualifier, Item.ANY);
DCDate date = new DCDate(new Date());
itemService.addMetadata(context, item, dc.schema, dc.element, dc.qualifier, null, date.toString());
} catch (SQLException e) {
itemService.addMetadata(context, item, dc.schema, dc.element,
dc.qualifier, null, date.toString());
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
swordService.message("Updated date added to response from item metadata where available");
swordService.message(
"Updated date added to response from item metadata where available");
}
/**
@@ -216,17 +245,25 @@ public class SWORDMETSIngester implements SWORDIngester
return;
}
String field = ConfigurationManager.getProperty("sword-server", "slug.field");
String field = ConfigurationManager
.getProperty("sword-server", "slug.field");
if (field == null || "".equals(field))
{
throw new DSpaceSWORDException("No configuration, or configuration is invalid for: sword.slug.field");
throw new DSpaceSWORDException(
"No configuration, or configuration is invalid for: sword.slug.field");
}
MetadataFieldInfo mfi = this.configToDC(field, null);
try {
itemService.clearMetadata(swordService.getContext(), item, mfi.schema, mfi.element, mfi.qualifier, Item.ANY);
itemService.addMetadata(swordService.getContext(), item, mfi.schema, mfi.element, mfi.qualifier, null, slugVal);
} catch (SQLException e) {
try
{
itemService
.clearMetadata(swordService.getContext(), item, mfi.schema,
mfi.element, mfi.qualifier, Item.ANY);
itemService.addMetadata(swordService.getContext(), item, mfi.schema,
mfi.element, mfi.qualifier, null, slugVal);
}
catch (SQLException e)
{
log.error("Caught exception: ", e);
throw new DSpaceSWORDException(e);
}
@@ -250,7 +287,7 @@ public class SWORDMETSIngester implements SWORDIngester
{
MetadataFieldInfo mfi = new MetadataFieldInfo();
mfi.schema = def;
mfi.element= def;
mfi.element = def;
mfi.qualifier = def;
StringTokenizer stz = new StringTokenizer(config, ".");
@@ -279,9 +316,12 @@ public class SWORDMETSIngester implements SWORDIngester
"an identifier leading to an HTML splash page.";
}
private class MetadataFieldInfo {
private class MetadataFieldInfo
{
private String schema;
private String element;
private String qualifier;
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -37,7 +37,8 @@ public class SWORDService
/** Log4j logging instance */
public static final Logger log = Logger.getLogger(SWORDService.class);
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
/** The SWORD context of the request */
private SWORDContext swordContext;
@@ -67,7 +68,8 @@ public class SWORDService
{
this.swordContext = sc;
this.swordConfig = new SWORDConfiguration();
this.urlManager = new SWORDUrlManager(this.swordConfig, this.swordContext.getContext());
this.urlManager = new SWORDUrlManager(this.swordConfig,
this.swordContext.getContext());
dateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.S]");
}
@@ -152,12 +154,14 @@ public class SWORDService
* @param original
* @throws DSpaceSWORDException
*/
public String getFilename(Context context, Deposit deposit, boolean original)
public String getFilename(Context context, Deposit deposit,
boolean original)
throws DSpaceSWORDException
{
try
{
BitstreamFormat bf = bitstreamFormatService.findByMIMEType(context, deposit.getContentType());
BitstreamFormat bf = bitstreamFormatService
.findByMIMEType(context, deposit.getContentType());
List<String> exts = null;
if (bf != null)
{

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -36,8 +36,12 @@ public class SWORDUrlManager
/** the active dspace context */
private Context context;
protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
public SWORDUrlManager(SWORDConfiguration config, Context context)
{
@@ -51,7 +55,8 @@ public class SWORDUrlManager
*/
public String getGeneratorUrl()
{
String cfg = ConfigurationManager.getProperty("sword-server", "generator.url");
String cfg = ConfigurationManager
.getProperty("sword-server", "generator.url");
if (cfg == null || "".equals(cfg))
{
return SWORDProperties.SOFTWARE_URI;
@@ -125,7 +130,8 @@ public class SWORDUrlManager
String baseUrl = this.getBaseDepositUrl();
if (baseUrl.length() == location.length())
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"The deposit URL is incomplete");
}
String handle = location.substring(baseUrl.length());
if (handle.startsWith("/"))
@@ -134,14 +140,16 @@ public class SWORDUrlManager
}
if ("".equals(handle))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"The deposit URL is incomplete");
}
DSpaceObject dso = handleService.resolveToObject(context, handle);
if (!(dso instanceof Collection))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL does not resolve to a valid collection");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"The deposit URL does not resolve to a valid collection");
}
return (Collection) dso;
@@ -149,7 +157,8 @@ public class SWORDUrlManager
catch (SQLException e)
{
// log.error("Caught exception:", e);
throw new DSpaceSWORDException("There was a problem resolving the collection", e);
throw new DSpaceSWORDException(
"There was a problem resolving the collection", e);
}
}
@@ -170,7 +179,8 @@ public class SWORDUrlManager
String baseUrl = this.getBaseDepositUrl();
if (baseUrl.length() == location.length())
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"The deposit URL is incomplete");
}
String handle = location.substring(baseUrl.length());
if (handle.startsWith("/"))
@@ -179,14 +189,16 @@ public class SWORDUrlManager
}
if ("".equals(handle))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL is incomplete");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"The deposit URL is incomplete");
}
DSpaceObject dso = handleService.resolveToObject(context, handle);
if (!(dso instanceof Collection) && !(dso instanceof Item))
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL, "The deposit URL does not resolve to a valid deposit target");
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"The deposit URL does not resolve to a valid deposit target");
}
return dso;
@@ -194,7 +206,8 @@ public class SWORDUrlManager
catch (SQLException e)
{
// log.error("Caught exception:", e);
throw new DSpaceSWORDException("There was a problem resolving the collection", e);
throw new DSpaceSWORDException(
"There was a problem resolving the collection", e);
}
}
@@ -292,7 +305,8 @@ public class SWORDUrlManager
else
{
throw new SWORDErrorException(DSpaceSWORDErrorCodes.BAD_URL,
"Unable to recognise URL as a valid service document: " + url);
"Unable to recognise URL as a valid service document: " +
url);
}
}
catch (SQLException e)
@@ -309,28 +323,32 @@ public class SWORDUrlManager
public String getBaseServiceDocumentUrl()
throws DSpaceSWORDException
{
String depositUrl = ConfigurationManager.getProperty("sword-server", "servicedocument.url");
String depositUrl = ConfigurationManager
.getProperty("sword-server", "servicedocument.url");
if (depositUrl == null || "".equals(depositUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
String dspaceUrl = ConfigurationManager
.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct service document urls, due to missing/invalid " +
throw new DSpaceSWORDException(
"Unable to construct service document urls, due to missing/invalid " +
"config in sword.servicedocument.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
depositUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/servicedocument").toString();
depositUrl = new URL(url.getProtocol(), url.getHost(),
url.getPort(), "/sword/servicedocument").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct service document urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
throw new DSpaceSWORDException(
"Unable to construct service document urls, due to invalid dspace.baseUrl " +
e.getMessage(), e);
}
}
return depositUrl;
}
@@ -354,28 +372,32 @@ public class SWORDUrlManager
public String getBaseDepositUrl()
throws DSpaceSWORDException
{
String depositUrl = ConfigurationManager.getProperty("sword-server", "deposit.url");
String depositUrl = ConfigurationManager
.getProperty("sword-server", "deposit.url");
if (depositUrl == null || "".equals(depositUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
String dspaceUrl = ConfigurationManager
.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to missing/invalid config in " +
throw new DSpaceSWORDException(
"Unable to construct deposit urls, due to missing/invalid config in " +
"sword.deposit.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
depositUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/deposit").toString();
depositUrl = new URL(url.getProtocol(), url.getHost(),
url.getPort(), "/sword/deposit").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct deposit urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
throw new DSpaceSWORDException(
"Unable to construct deposit urls, due to invalid dspace.baseUrl " +
e.getMessage(), e);
}
}
return depositUrl;
}
@@ -424,7 +446,8 @@ public class SWORDUrlManager
}
else
{
throw new DSpaceSWORDException("Encountered orphaned bitstream");
throw new DSpaceSWORDException(
"Encountered orphaned bitstream");
}
List<Item> items = parent.getItems();
@@ -443,7 +466,8 @@ public class SWORDUrlManager
if (handle != null && !"".equals(handle))
{
bsLink = bsLink + "/bitstream/" + handle + "/" + bitstream.getSequenceID() + "/" + bitstream.getName();
bsLink = bsLink + "/bitstream/" + handle + "/" +
bitstream.getSequenceID() + "/" + bitstream.getName();
}
else
{
@@ -466,28 +490,32 @@ public class SWORDUrlManager
public String getBaseMediaLinkUrl()
throws DSpaceSWORDException
{
String mlUrl = ConfigurationManager.getProperty("sword-server", "media-link.url");
String mlUrl = ConfigurationManager
.getProperty("sword-server", "media-link.url");
if (StringUtils.isBlank(mlUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
String dspaceUrl = ConfigurationManager
.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSWORDException("Unable to construct media-link urls, due to missing/invalid config in " +
throw new DSpaceSWORDException(
"Unable to construct media-link urls, due to missing/invalid config in " +
"media-link.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
mlUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/sword/media-link").toString();
mlUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(),
"/sword/media-link").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSWORDException("Unable to construct media-link urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
throw new DSpaceSWORDException(
"Unable to construct media-link urls, due to invalid dspace.baseUrl " +
e.getMessage(), e);
}
}
return mlUrl;
}
@@ -530,7 +558,8 @@ public class SWORDUrlManager
}
else
{
throw new DSpaceSWORDException("Encountered orphaned bitstream");
throw new DSpaceSWORDException(
"Encountered orphaned bitstream");
}
List<Item> items = parent.getItems();

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -26,8 +26,11 @@ import java.util.List;
public class ServiceDocumentManager
{
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
protected CommunityService communityService = ContentServiceFactory
.getInstance().getCommunityService();
private SWORDService swordService;
@@ -63,24 +66,30 @@ public class ServiceDocumentManager
SWORDUrlManager urlManager = swordService.getUrlManager();
// construct the ATOM collection generators that we might use
ATOMCollectionGenerator comGen = new CommunityCollectionGenerator(swordService);
ATOMCollectionGenerator colGen = new CollectionCollectionGenerator(swordService);
ATOMCollectionGenerator itemGen = new ItemCollectionGenerator(swordService);
ATOMCollectionGenerator comGen = new CommunityCollectionGenerator(
swordService);
ATOMCollectionGenerator colGen = new CollectionCollectionGenerator(
swordService);
ATOMCollectionGenerator itemGen = new ItemCollectionGenerator(
swordService);
// first check that the context and sword context have
// been set
if (context == null)
{
throw new DSpaceSWORDException("The Context is null; please set it before calling getServiceDocument");
throw new DSpaceSWORDException(
"The Context is null; please set it before calling getServiceDocument");
}
if (swordContext == null)
{
throw new DSpaceSWORDException("The SWORD Context is null; please set it before calling getServiceDocument");
throw new DSpaceSWORDException(
"The SWORD Context is null; please set it before calling getServiceDocument");
}
// construct a new service document
Service service = new Service(SWORDProperties.VERSION, swordConfig.isNoOp(), swordConfig.isVerbose());
Service service = new Service(SWORDProperties.VERSION,
swordConfig.isNoOp(), swordConfig.isVerbose());
// set the max upload size
service.setMaxUploadSize(swordConfig.getMaxUploadSize());
@@ -99,23 +108,28 @@ public class ServiceDocumentManager
workspace.setTitle(ws);
// next thing to do is determine whether the default is communities or collections
boolean swordCommunities = ConfigurationManager.getBooleanProperty("sword-server", "expose-communities");
boolean swordCommunities = ConfigurationManager
.getBooleanProperty("sword-server", "expose-communities");
if (swordCommunities)
{
List<Community> comms = swordAuth.getAllowedCommunities(swordContext);
List<Community> comms = swordAuth
.getAllowedCommunities(swordContext);
for (Community comm : comms)
{
org.purl.sword.base.Collection scol = comGen.buildCollection(comm);
org.purl.sword.base.Collection scol = comGen
.buildCollection(comm);
workspace.addCollection(scol);
}
}
else
{
List<Collection> cols = swordAuth.getAllowedCollections(swordContext);
List<Collection> cols = swordAuth
.getAllowedCollections(swordContext);
for (Collection col : cols)
{
org.purl.sword.base.Collection scol = colGen.buildCollection(col);
org.purl.sword.base.Collection scol = colGen
.buildCollection(col);
workspace.addCollection(scol);
}
}
@@ -131,12 +145,15 @@ public class ServiceDocumentManager
{
Collection collection = (Collection) dso;
Workspace workspace = new Workspace();
workspace.setTitle(collectionService.getMetadata(collection, "name"));
workspace.setTitle(
collectionService.getMetadata(collection, "name"));
List<Item> items = swordAuth.getAllowedItems(swordContext, collection);
List<Item> items = swordAuth
.getAllowedItems(swordContext, collection);
for (Item item : items)
{
org.purl.sword.base.Collection scol = itemGen.buildCollection(item);
org.purl.sword.base.Collection scol = itemGen
.buildCollection(item);
workspace.addCollection(scol);
}
@@ -146,19 +163,24 @@ public class ServiceDocumentManager
{
Community community = (Community) dso;
Workspace workspace = new Workspace();
workspace.setTitle(communityService.getMetadata(community, "name"));
workspace.setTitle(
communityService.getMetadata(community, "name"));
List<Collection> collections = swordAuth.getAllowedCollections(swordContext, community);
List<Collection> collections = swordAuth
.getAllowedCollections(swordContext, community);
for (Collection collection : collections)
{
org.purl.sword.base.Collection scol = colGen.buildCollection(collection);
org.purl.sword.base.Collection scol = colGen
.buildCollection(collection);
workspace.addCollection(scol);
}
List<Community> communities = swordAuth.getCommunities(swordContext, community);
List<Community> communities = swordAuth
.getCommunities(swordContext, community);
for (Community comm : communities)
{
org.purl.sword.base.Collection scol = comGen.buildCollection(comm);
org.purl.sword.base.Collection scol = comGen
.buildCollection(comm);
workspace.addCollection(scol);
}
@@ -176,7 +198,8 @@ public class ServiceDocumentManager
*/
private void addGenerator(Service service)
{
boolean identify = ConfigurationManager.getBooleanProperty("sword-server", "identify-version", false);
boolean identify = ConfigurationManager
.getBooleanProperty("sword-server", "identify-version", false);
SWORDUrlManager urlManager = swordService.getUrlManager();
String softwareUri = urlManager.getGeneratorUrl();
if (identify)

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword;
@@ -39,10 +39,17 @@ import java.util.List;
public class SimpleFileIngester implements SWORDIngester
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
/**
* Perform the ingest using the given deposit object onto the specified
@@ -54,14 +61,16 @@ public class SimpleFileIngester implements SWORDIngester
* @throws DSpaceSWORDException
* @throws SWORDErrorException
*/
public DepositResult ingest(SWORDService service, Deposit deposit, DSpaceObject target)
public DepositResult ingest(SWORDService service, Deposit deposit,
DSpaceObject target)
throws DSpaceSWORDException, SWORDErrorException
{
try
{
if (!(target instanceof Item))
{
throw new DSpaceSWORDException("SimpleFileIngester can only be loaded for deposit onto DSpace Items");
throw new DSpaceSWORDException(
"SimpleFileIngester can only be loaded for deposit onto DSpace Items");
}
Item item = (Item) target;
@@ -84,7 +93,8 @@ public class SimpleFileIngester implements SWORDIngester
}
if (original == null)
{
original = bundleService.create(context, item, Constants.CONTENT_BUNDLE_NAME);
original = bundleService
.create(context, item, Constants.CONTENT_BUNDLE_NAME);
}
Bitstream bs;
@@ -108,7 +118,8 @@ public class SimpleFileIngester implements SWORDIngester
swordService.message("File created in item with filename " + fn);
BitstreamFormat bf = bitstreamFormatService.findByMIMEType(context, deposit.getContentType());
BitstreamFormat bf = bitstreamFormatService
.findByMIMEType(context, deposit.getContentType());
if (bf != null)
{
bs.setFormat(context, bf);

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
@@ -22,9 +22,11 @@ import java.util.Properties;
public class AbstractSimpleDC
{
protected HashMap<String, String> dcMap = null;
protected HashMap<String, String> atomMap = null;
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected void loadMetadataMaps()
{
@@ -32,7 +34,8 @@ public class AbstractSimpleDC
{
// we should load our DC map from configuration
this.dcMap = new HashMap<>();
Properties props = ConfigurationManager.getProperties("swordv2-server");
Properties props = ConfigurationManager
.getProperties("swordv2-server");
for (Object key : props.keySet())
{
String keyString = (String) key;
@@ -48,7 +51,8 @@ public class AbstractSimpleDC
if (this.atomMap == null)
{
this.atomMap = new HashMap<>();
Properties props = ConfigurationManager.getProperties("swordv2-server");
Properties props = ConfigurationManager
.getProperties("swordv2-server");
for (Object key : props.keySet())
{
String keyString = (String) key;
@@ -67,12 +71,14 @@ public class AbstractSimpleDC
this.loadMetadataMaps();
SimpleDCMetadata md = new SimpleDCMetadata();
List<MetadataValue> all = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
List<MetadataValue> all = itemService
.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (MetadataValue dcv : all)
{
MetadataField field = dcv.getMetadataField();
String valueMatch = field.getMetadataSchema().getName() + "." + field.getElement();
String valueMatch = field.getMetadataSchema().getName() + "." +
field.getElement();
if (field.getQualifier() != null)
{
valueMatch += "." + field.getQualifier();

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -24,38 +24,56 @@ import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
public abstract class AbstractSwordContentIngester implements SwordContentIngester
public abstract class AbstractSwordContentIngester
implements SwordContentIngester
{
public static final Logger log = Logger.getLogger(AbstractSwordContentIngester.class);
public static final Logger log = Logger
.getLogger(AbstractSwordContentIngester.class);
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
public DepositResult ingest(Context context, Deposit deposit, DSpaceObject dso, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
public DepositResult ingest(Context context, Deposit deposit,
DSpaceObject dso, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
return this.ingest(context, deposit, dso, verboseDescription, null);
}
public DepositResult ingest(Context context, Deposit deposit, DSpaceObject dso, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingest(Context context, Deposit deposit,
DSpaceObject dso, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
if (dso instanceof Collection)
{
return this.ingestToCollection(context, deposit, (Collection) dso, verboseDescription, result);
return this.ingestToCollection(context, deposit, (Collection) dso,
verboseDescription, result);
}
else if (dso instanceof Item)
{
return this.ingestToItem(context, deposit, (Item) dso, verboseDescription, result);
return this.ingestToItem(context, deposit, (Item) dso,
verboseDescription, result);
}
return null;
}
public abstract DepositResult ingestToCollection(Context context, Deposit deposit, Collection collection, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException;
public abstract DepositResult ingestToCollection(Context context,
Deposit deposit, Collection collection,
VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException;
public abstract DepositResult ingestToItem(Context context, Deposit deposit, Item item, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException;
public abstract DepositResult ingestToItem(Context context, Deposit deposit,
Item item, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException;
protected BitstreamFormat getFormat(Context context, String fileName)
throws SQLException
@@ -97,26 +115,35 @@ public abstract class AbstractSwordContentIngester implements SwordContentIngest
* @param item
* @throws DSpaceSwordException
*/
protected void setUpdatedDate(Context context, Item item, VerboseDescription verboseDescription)
protected void setUpdatedDate(Context context, Item item,
VerboseDescription verboseDescription)
throws DSpaceSwordException
{
String field = ConfigurationManager.getProperty("swordv2-server", "updated.field");
String field = ConfigurationManager
.getProperty("swordv2-server", "updated.field");
if (field == null || "".equals(field))
{
throw new DSpaceSwordException("No configuration, or configuration is invalid for: sword.updated.field");
throw new DSpaceSwordException(
"No configuration, or configuration is invalid for: sword.updated.field");
}
MetadataFieldInfo info = this.configToDC(field, null);
try {
itemService.clearMetadata(context, item, info.schema, info.element, info.qualifier, Item.ANY);
try
{
itemService.clearMetadata(context, item, info.schema, info.element,
info.qualifier, Item.ANY);
DCDate date = new DCDate(new Date());
itemService.addMetadata(context, item, info.schema, info.element, info.qualifier, null, date.toString());
} catch (SQLException e) {
itemService.addMetadata(context, item, info.schema, info.element,
info.qualifier, null, date.toString());
}
catch (SQLException e)
{
log.error("Caught exception trying to set update date", e);
throw new DSpaceSwordException(e);
}
verboseDescription.append("Updated date added to response from item metadata where available");
verboseDescription
.append("Updated date added to response from item metadata where available");
}
/**
@@ -131,7 +158,8 @@ public abstract class AbstractSwordContentIngester implements SwordContentIngest
* @param slugVal
* @throws DSpaceSwordException
*/
protected void setSlug(Context context, Item item, String slugVal, VerboseDescription verboseDescription)
protected void setSlug(Context context, Item item, String slugVal,
VerboseDescription verboseDescription)
throws DSpaceSwordException
{
// if there isn't a slug value, don't set it
@@ -140,17 +168,24 @@ public abstract class AbstractSwordContentIngester implements SwordContentIngest
return;
}
String field = ConfigurationManager.getProperty("swordv2-server", "slug.field");
String field = ConfigurationManager
.getProperty("swordv2-server", "slug.field");
if (field == null || "".equals(field))
{
throw new DSpaceSwordException("No configuration, or configuration is invalid for: sword.slug.field");
throw new DSpaceSwordException(
"No configuration, or configuration is invalid for: sword.slug.field");
}
MetadataFieldInfo info = this.configToDC(field, null);
try {
itemService.clearMetadata(context, item, info.schema, info.element, info.qualifier, Item.ANY);
itemService.addMetadata(context, item, info.schema, info.element, info.qualifier, null, slugVal);
} catch (SQLException e) {
try
{
itemService.clearMetadata(context, item, info.schema, info.element,
info.qualifier, Item.ANY);
itemService.addMetadata(context, item, info.schema, info.element,
info.qualifier, null, slugVal);
}
catch (SQLException e)
{
log.error("Caught exception trying to set slug", e);
throw new DSpaceSwordException(e);
}
@@ -173,7 +208,7 @@ public abstract class AbstractSwordContentIngester implements SwordContentIngest
{
MetadataFieldInfo mfi = new MetadataFieldInfo();
mfi.schema = def;
mfi.element= def;
mfi.element = def;
mfi.qualifier = def;
StringTokenizer stz = new StringTokenizer(config, ".");
@@ -187,9 +222,12 @@ public abstract class AbstractSwordContentIngester implements SwordContentIngest
return mfi;
}
private class MetadataFieldInfo {
private class MetadataFieldInfo
{
private String schema;
private String element;
private String qualifier;
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -25,5 +25,6 @@ public interface AtomCollectionGenerator
* @param dso
* @throws DSpaceSwordException
*/
public SwordCollection buildCollection(Context context, DSpaceObject dso, SwordConfigurationDSpace config) throws DSpaceSwordException;
public SwordCollection buildCollection(Context context, DSpaceObject dso,
SwordConfigurationDSpace config) throws DSpaceSwordException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -20,18 +20,25 @@ import org.swordapp.server.SwordServerException;
import java.util.List;
public class AtomStatementDisseminator extends GenericStatementDisseminator implements SwordStatementDisseminator
public class AtomStatementDisseminator extends GenericStatementDisseminator
implements SwordStatementDisseminator
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
public Statement disseminate(Context context, Item item) throws DSpaceSwordException, SwordError, SwordServerException
public Statement disseminate(Context context, Item item)
throws DSpaceSwordException, SwordError, SwordServerException
{
SwordUrlManager urlManager = new SwordUrlManager(new SwordConfigurationDSpace(), context);
SwordUrlManager urlManager = new SwordUrlManager(
new SwordConfigurationDSpace(), context);
String feedUri = urlManager.getAtomStatementUri(item);
String authorField = ConfigurationManager.getProperty("swordv2-server", "author.field");
String titleField = ConfigurationManager.getProperty("swordv2-server", "title.field");
String updatedField = ConfigurationManager.getProperty("swordv2-server", "updated.field");
String authorField = ConfigurationManager
.getProperty("swordv2-server", "author.field");
String titleField = ConfigurationManager
.getProperty("swordv2-server", "title.field");
String updatedField = ConfigurationManager
.getProperty("swordv2-server", "updated.field");
String author = this.stringMetadata(item, authorField);
String title = this.stringMetadata(item, titleField);
@@ -49,7 +56,8 @@ public class AtomStatementDisseminator extends GenericStatementDisseminator impl
return null;
}
List<MetadataValue> dcvs = itemService.getMetadataByMetadataString(item, field);
List<MetadataValue> dcvs = itemService
.getMetadataByMetadataString(item, field);
if (dcvs == null || dcvs.isEmpty())
{
return null;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -33,13 +33,23 @@ import java.util.List;
public class BinaryContentIngester extends AbstractSwordContentIngester
{
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory
.getInstance().getWorkspaceItemService();
public DepositResult ingestToCollection(Context context, Deposit deposit, Collection collection, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
public DepositResult ingestToCollection(Context context, Deposit deposit,
Collection collection, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
try
{
@@ -61,16 +71,22 @@ public class BinaryContentIngester extends AbstractSwordContentIngester
item = wsi.getItem();
}
Bitstream bs = itemService.createSingleBitstream(context, deposit.getInputStream(), item);
BitstreamFormat format = this.getFormat(context, deposit.getFilename());
Bitstream bs = itemService
.createSingleBitstream(context, deposit.getInputStream(),
item);
BitstreamFormat format = this
.getFormat(context, deposit.getFilename());
bs.setName(context, deposit.getFilename());
bs.setFormat(context, format);
bitstreamService.update(context, bs);
// now we have an item in the workspace, and we need to consider adding some metadata to it,
// but since the binary file didn't contain anything, what do we do?
itemService.addMetadata(context, item, "dc", "title", null, null, "Untitled: " + deposit.getFilename());
itemService.addMetadata(context, item, "dc", "description", null, null, "Zip file deposted by SWORD without accompanying metadata");
itemService.addMetadata(context, item, "dc", "title", null, null,
"Untitled: " + deposit.getFilename());
itemService
.addMetadata(context, item, "dc", "description", null, null,
"Zip file deposted by SWORD without accompanying metadata");
// update the item metadata to inclue the current time as
// the updated date
@@ -89,7 +105,9 @@ public class BinaryContentIngester extends AbstractSwordContentIngester
context.restoreAuthSystemState();
verboseDescription.append("Ingest successful");
verboseDescription.append("Item created with internal identifier: " + item.getID());
verboseDescription
.append("Item created with internal identifier: " +
item.getID());
result.setItem(item);
result.setTreatment(this.getTreatment());
@@ -107,8 +125,11 @@ public class BinaryContentIngester extends AbstractSwordContentIngester
}
}
public DepositResult ingestToItem(Context context, Deposit deposit, Item item, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingestToItem(Context context, Deposit deposit,
Item item, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
try
{
@@ -130,11 +151,14 @@ public class BinaryContentIngester extends AbstractSwordContentIngester
}
if (original == null)
{
original = bundleService.create(context, item, Constants.CONTENT_BUNDLE_NAME);
original = bundleService
.create(context, item, Constants.CONTENT_BUNDLE_NAME);
}
Bitstream bs = bitstreamService.create(context, original, deposit.getInputStream());
BitstreamFormat format = this.getFormat(context, deposit.getFilename());
Bitstream bs = bitstreamService
.create(context, original, deposit.getInputStream());
BitstreamFormat format = this
.getFormat(context, deposit.getFilename());
bs.setFormat(context, format);
bs.setName(context, deposit.getFilename());
bitstreamService.update(context, bs);
@@ -169,7 +193,6 @@ public class BinaryContentIngester extends AbstractSwordContentIngester
}
}
/**
* The human readable description of the treatment this ingester has
* put the deposit through

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -29,9 +29,11 @@ import java.util.List;
*/
public class CollectionCollectionGenerator implements AtomCollectionGenerator
{
private static Logger log = Logger.getLogger(CommunityCollectionGenerator.class);
private static Logger log = Logger
.getLogger(CommunityCollectionGenerator.class);
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
/**
* Build the collection for the given DSpaceObject. In this implementation,
@@ -40,17 +42,21 @@ public class CollectionCollectionGenerator implements AtomCollectionGenerator
* @return
* @throws DSpaceSwordException
*/
public SwordCollection buildCollection(Context context, DSpaceObject dso, SwordConfigurationDSpace swordConfig)
public SwordCollection buildCollection(Context context, DSpaceObject dso,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException
{
if (!(dso instanceof org.dspace.content.Collection))
{
log.error("buildCollection passed argument which is not of type Collection");
throw new DSpaceSwordException("Incorrect ATOMCollectionGenerator instantiated");
log.error(
"buildCollection passed argument which is not of type Collection");
throw new DSpaceSwordException(
"Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
SwordUrlManager urlManager = swordConfig.getUrlManager(context, swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(context, swordConfig);
Collection col = (Collection) dso;
SwordCollection scol = new SwordCollection();
@@ -68,7 +74,8 @@ public class CollectionCollectionGenerator implements AtomCollectionGenerator
// String treatment = " ";
// abstract is the short description of the collection
List<MetadataValue> dcAbstracts = collectionService.getMetadataByMetadataString(col, "short_description");
List<MetadataValue> dcAbstracts = collectionService
.getMetadataByMetadataString(col, "short_description");
// we just do support mediation
boolean mediation = swordConfig.isMediated();
@@ -120,7 +127,8 @@ public class CollectionCollectionGenerator implements AtomCollectionGenerator
// should we offer the items in the collection up as deposit
// targets?
boolean itemService = ConfigurationManager.getBooleanProperty("sword.expose-items");
boolean itemService = ConfigurationManager
.getBooleanProperty("sword.expose-items");
if (itemService)
{
String subService = urlManager.constructSubServiceUrl(col);

View File

@@ -2,58 +2,38 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService;
import org.dspace.core.*;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.CollectionDepositManager;
import org.swordapp.server.Deposit;
import org.swordapp.server.DepositReceipt;
import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
import org.swordapp.server.UriRegistry;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.swordapp.server.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements CollectionDepositManager
public class CollectionDepositManagerDSpace extends DSpaceSwordAPI
implements CollectionDepositManager
{
/** logger */
private static Logger log = Logger.getLogger(CollectionDepositManagerDSpace.class);
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
/**
* logger
*/
private static Logger log = Logger
.getLogger(CollectionDepositManagerDSpace.class);
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
private VerboseDescription verboseDescription = new VerboseDescription();
public DepositReceipt createNew(String collectionUri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt createNew(String collectionUri, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
@@ -74,11 +54,13 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_create_new", ""));
log.debug(
LogManager.getHeader(context, "sword_create_new", ""));
}
// get the deposit target
Collection collection = this.getDepositTarget(context, collectionUri, config);
Collection collection = this
.getDepositTarget(context, collectionUri, config);
if (collection == null)
{
throw new SwordError(404);
@@ -99,16 +81,22 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "deposit_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot submit to the given collection with this context");
log.info(LogManager
.getHeader(context, "deposit_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot submit to the given collection with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
DepositResult result = null;
@@ -116,18 +104,22 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
{
if (deposit.isBinaryOnly())
{
result = this.createNewFromBinary(sc, collection, deposit, authCredentials, config);
result = this.createNewFromBinary(sc, collection, deposit,
authCredentials, config);
}
else if (deposit.isEntryOnly())
{
result = this.createNewFromEntry(sc, collection, deposit, authCredentials, config);
result = this.createNewFromEntry(sc, collection, deposit,
authCredentials, config);
}
else if (deposit.isMultipart())
{
result = this.createNewFromMultipart(sc, collection, deposit, authCredentials, config);
result = this
.createNewFromMultipart(sc, collection, deposit,
authCredentials, config);
}
}
catch(DSpaceSwordException e)
catch (DSpaceSwordException | SwordError e)
{
if (config.isKeepPackageOnFailedIngest())
{
@@ -135,46 +127,23 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
{
if (deposit.isBinaryOnly())
{
this.storePackageAsFile(deposit, authCredentials, config);
this.storePackageAsFile(deposit, authCredentials,
config);
}
else if (deposit.isEntryOnly())
{
this.storeEntryAsFile(deposit, authCredentials, config);
this.storeEntryAsFile(deposit, authCredentials,
config);
}
else if (deposit.isMultipart())
{
this.storePackageAsFile(deposit, authCredentials, config);
this.storeEntryAsFile(deposit, authCredentials, config);
this.storePackageAsFile(deposit, authCredentials,
config);
this.storeEntryAsFile(deposit, authCredentials,
config);
}
}
catch(IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
}
}
throw e;
}
catch(SwordError e)
{
if (config.isKeepPackageOnFailedIngest())
{
try
{
if (deposit.isBinaryOnly())
{
this.storePackageAsFile(deposit, authCredentials, config);
}
else if (deposit.isEntryOnly())
{
this.storeEntryAsFile(deposit, authCredentials, config);
}
else if (deposit.isMultipart())
{
this.storePackageAsFile(deposit, authCredentials, config);
this.storeEntryAsFile(deposit, authCredentials, config);
}
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
}
@@ -186,12 +155,15 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
wfm.resolveState(context, deposit, result, this.verboseDescription);
ReceiptGenerator genny = new ReceiptGenerator();
DepositReceipt receipt = genny.createReceipt(context, result, config);
DepositReceipt receipt = genny
.createReceipt(context, result, config);
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for deposit processing: " + delta + " ms");
this.verboseDescription
.append("Total time for deposit processing: " + delta +
" ms");
this.addVerboseDescription(receipt, this.verboseDescription);
// if something hasn't killed it already (allowed), then complete the transaction
@@ -202,7 +174,8 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
finally
{
@@ -214,96 +187,131 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
}
}
protected DepositResult createNewFromBinary(SwordContext swordContext, Collection collection, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
protected DepositResult createNewFromBinary(SwordContext swordContext,
Collection collection, Deposit deposit,
AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// is the content acceptable? If not, this will throw an error
this.isAcceptable(swordConfig, context, deposit, collection);
// Obtain the relevant ingester from the factory
SwordContentIngester si = SwordIngesterFactory.getContentInstance(context, deposit, collection);
this.verboseDescription.append("Loaded ingester: " + si.getClass().getName());
SwordContentIngester si = SwordIngesterFactory
.getContentInstance(context, deposit, collection);
this.verboseDescription
.append("Loaded ingester: " + si.getClass().getName());
// do the deposit
DepositResult result = si.ingest(context, deposit, collection, this.verboseDescription);
DepositResult result = si
.ingest(context, deposit, collection, this.verboseDescription);
this.verboseDescription.append("Archive ingest completed successfully");
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
return result;
}
protected DepositResult createNewFromEntry(SwordContext swordContext, Collection collection, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
protected DepositResult createNewFromEntry(SwordContext swordContext,
Collection collection, Deposit deposit,
AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// Obtain the relevant ingester from the factory
SwordEntryIngester si = SwordIngesterFactory.getEntryInstance(context, deposit, collection);
this.verboseDescription.append("Loaded ingester: " + si.getClass().getName());
SwordEntryIngester si = SwordIngesterFactory
.getEntryInstance(context, deposit, collection);
this.verboseDescription
.append("Loaded ingester: " + si.getClass().getName());
// do the deposit
DepositResult result = si.ingest(context, deposit, collection, this.verboseDescription);
DepositResult result = si
.ingest(context, deposit, collection, this.verboseDescription);
this.verboseDescription.append("Archive ingest completed successfully");
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
return result;
}
protected DepositResult createNewFromMultipart(SwordContext swordContext, Collection collection, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
protected DepositResult createNewFromMultipart(SwordContext swordContext,
Collection collection, Deposit deposit,
AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// is the content acceptable? If not, this will throw an error
this.isAcceptable(swordConfig, context, deposit, collection);
// Obtain the relevant content ingester from the factory
SwordContentIngester sci = SwordIngesterFactory.getContentInstance(context, deposit, collection);
this.verboseDescription.append("Loaded content ingester: " + sci.getClass().getName());
SwordContentIngester sci = SwordIngesterFactory
.getContentInstance(context, deposit, collection);
this.verboseDescription
.append("Loaded content ingester: " + sci.getClass().getName());
// obtain the relevant entry intester from the factory
SwordEntryIngester sei = SwordIngesterFactory.getEntryInstance(context, deposit, collection);
this.verboseDescription.append("Loaded entry ingester: " + sei.getClass().getName());
SwordEntryIngester sei = SwordIngesterFactory
.getEntryInstance(context, deposit, collection);
this.verboseDescription
.append("Loaded entry ingester: " + sei.getClass().getName());
DepositResult result;
if (swordConfig.isEntryFirst())
{
// do the entry deposit
result = sei.ingest(context, deposit, collection, this.verboseDescription);
result = sei.ingest(context, deposit, collection,
this.verboseDescription);
// do the content deposit
result = sci.ingest(context, deposit, collection, this.verboseDescription, result);
this.verboseDescription.append("Archive ingest completed successfully");
result = sci.ingest(context, deposit, collection,
this.verboseDescription, result);
this.verboseDescription
.append("Archive ingest completed successfully");
}
else
{
// do the content deposit
result = sci.ingest(context, deposit, collection, this.verboseDescription);
result = sci.ingest(context, deposit, collection,
this.verboseDescription);
// do the entry deposit
result = sei.ingest(context, deposit, collection, this.verboseDescription, result, false);
this.verboseDescription.append("Archive ingest completed successfully");
result = sei.ingest(context, deposit, collection,
this.verboseDescription, result, false);
this.verboseDescription
.append("Archive ingest completed successfully");
}
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
return result;
}
protected Collection getDepositTarget(Context context, String depositUrl, SwordConfigurationDSpace config)
protected Collection getDepositTarget(Context context, String depositUrl,
SwordConfigurationDSpace config)
throws DSpaceSwordException, SwordError
{
SwordUrlManager urlManager = config.getUrlManager(context, config);
@@ -315,9 +323,12 @@ public class CollectionDepositManagerDSpace extends DSpaceSwordAPI implements Co
throw new SwordError(404);
}
this.verboseDescription.append("Performing deposit using deposit URL: " + depositUrl);
this.verboseDescription
.append("Performing deposit using deposit URL: " + depositUrl);
this.verboseDescription.append("Location resolves to collection with handle: " + collection.getHandle() +
this.verboseDescription
.append("Location resolves to collection with handle: " +
collection.getHandle() +
" and name: " + collectionService.getName(collection));
return collection;

View File

@@ -2,12 +2,11 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Entry;
@@ -32,13 +31,20 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CollectionListManagerDSpace extends DSpaceSwordAPI implements CollectionListManager
public class CollectionListManagerDSpace extends DSpaceSwordAPI
implements CollectionListManager
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
public Feed listCollectionContents(IRI colIRI, AuthCredentials authCredentials, SwordConfiguration swordConfig)
protected WorkspaceItemService workspaceItemService = ContentServiceFactory
.getInstance().getWorkspaceItemService();
protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory
.getInstance().getBasicWorkflowItemService();
public Feed listCollectionContents(IRI colIRI,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordServerException, SwordError, SwordAuthException
{
SwordContext sc = null;
@@ -49,7 +55,8 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI implements Colle
Context context = sc.getContext();
SwordUrlManager urlManager = config.getUrlManager(context, config);
Collection collection = urlManager.getCollection(context, colIRI.toString());
Collection collection = urlManager
.getCollection(context, colIRI.toString());
if (collection == null)
{
throw new SwordError(404);
@@ -72,11 +79,13 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI implements Colle
}
}
private Feed itemListToFeed(SwordContext sc, List<Item> items, SwordConfiguration swordConfig)
private Feed itemListToFeed(SwordContext sc, List<Item> items,
SwordConfiguration swordConfig)
throws DSpaceSwordException
{
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
SwordUrlManager urlManager = config.getUrlManager(sc.getContext(), config);
SwordUrlManager urlManager = config
.getUrlManager(sc.getContext(), config);
Abdera abdera = new Abdera();
Feed feed = abdera.newFeed();
@@ -85,26 +94,32 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI implements Colle
{
Entry entry = feed.addEntry();
entry.setId(urlManager.getEditIRI(item).toString());
String title = this.stringMetadata(item, ConfigurationManager.getProperty("swordv2-server", "title.field"));
title = title == null? "Untitled" : title;
String title = this.stringMetadata(item, ConfigurationManager
.getProperty("swordv2-server", "title.field"));
title = title == null ? "Untitled" : title;
entry.setTitle(title);
entry.addLink(urlManager.getContentUrl(item).toString(), "edit-media");
entry.addLink(urlManager.getContentUrl(item).toString(),
"edit-media");
}
return feed;
}
private List<Item> listItems(SwordContext sc, Collection collection, SwordConfiguration swordConfig)
private List<Item> listItems(SwordContext sc, Collection collection,
SwordConfiguration swordConfig)
throws DSpaceSwordException
{
try
{
EPerson person = sc.getOnBehalfOf() != null ? sc.getOnBehalfOf() : sc.getAuthenticated();
EPerson person = sc.getOnBehalfOf() != null ?
sc.getOnBehalfOf() :
sc.getAuthenticated();
List<Item> collectionItems = new ArrayList<Item>();
// first get the ones out of the archive
Iterator<Item> items = itemService.findBySubmitter(sc.getContext(), person);
while(items.hasNext())
Iterator<Item> items = itemService
.findBySubmitter(sc.getContext(), person);
while (items.hasNext())
{
Item item = items.next();
List<Collection> cols = item.getCollections();
@@ -119,7 +134,8 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI implements Colle
}
// now get the ones out of the workspace
List<WorkspaceItem> wsis = workspaceItemService.findByEPerson(sc.getContext(), person);
List<WorkspaceItem> wsis = workspaceItemService
.findByEPerson(sc.getContext(), person);
for (WorkspaceItem wsi : wsis)
{
Item item = wsi.getItem();
@@ -144,7 +160,8 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI implements Colle
}
// finally get the ones out of the workflow
List<BasicWorkflowItem> wfis = basicWorkflowItemService.findByOwner(sc.getContext(), person);
List<BasicWorkflowItem> wfis = basicWorkflowItemService
.findByOwner(sc.getContext(), person);
for (BasicWorkflowItem wfi : wfis)
{
Item item = wfi.getItem();
@@ -183,7 +200,8 @@ public class CollectionListManagerDSpace extends DSpaceSwordAPI implements Colle
return null;
}
List<MetadataValue> dcvs = itemService.getMetadataByMetadataString(item, field);
List<MetadataValue> dcvs = itemService
.getMetadataByMetadataString(item, field);
if (dcvs == null)
{
return null;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -25,22 +25,30 @@ import java.util.List;
public class CommunityCollectionGenerator implements AtomCollectionGenerator
{
private static Logger log = Logger.getLogger(CommunityCollectionGenerator.class);
private static Logger log = Logger
.getLogger(CommunityCollectionGenerator.class);
protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService();
public SwordCollection buildCollection(Context context, DSpaceObject dso, SwordConfigurationDSpace swordConfig)
protected CommunityService communityService = ContentServiceFactory
.getInstance().getCommunityService();
public SwordCollection buildCollection(Context context, DSpaceObject dso,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException
{
if (!(dso instanceof Community))
{
log.error("buildCollection passed something other than a Community object");
throw new DSpaceSwordException("Incorrect ATOMCollectionGenerator instantiated");
log.error(
"buildCollection passed something other than a Community object");
throw new DSpaceSwordException(
"Incorrect ATOMCollectionGenerator instantiated");
}
// get the things we need out of the service
SwordUrlManager urlManager = swordConfig.getUrlManager(context, swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(context, swordConfig);
Community com = (Community) dso;
SwordCollection scol = new SwordCollection();
@@ -65,7 +73,8 @@ public class CommunityCollectionGenerator implements AtomCollectionGenerator
// String collectionPolicy = col.getLicense();
// abstract is the short description of the collection
List<MetadataValue> abstracts = communityService.getMetadataByMetadataString(com, "short_description");
List<MetadataValue> abstracts = communityService
.getMetadataByMetadataString(com, "short_description");
if (abstracts != null && !abstracts.isEmpty())
{
String firstValue = abstracts.get(0).getValue();

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -31,18 +31,28 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerManager
public class ContainerManagerDSpace extends DSpaceSwordAPI
implements ContainerManager
{
private static Logger log = Logger.getLogger(ContainerManagerDSpace.class);
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected WorkflowItemService workflowItemService = WorkflowServiceFactory.getInstance().getWorkflowItemService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory
.getInstance().getAuthorizeService();
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
protected WorkflowItemService workflowItemService = WorkflowServiceFactory
.getInstance().getWorkflowItemService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory
.getInstance().getWorkspaceItemService();
private VerboseDescription verboseDescription = new VerboseDescription();
public boolean isStatementRequest(String editIRI, Map<String, String> accept, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public boolean isStatementRequest(String editIRI,
Map<String, String> accept, AuthCredentials authCredentials,
SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
SwordContext sc = null;
@@ -53,14 +63,16 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
Context context = sc.getContext();
String acceptContentType = this.getHeader(accept, "Accept", null);
TreeMap<Float, List<String>> analysed = this.analyseAccept(acceptContentType);
TreeMap<Float, List<String>> analysed = this
.analyseAccept(acceptContentType);
// a request is for a statement if the content negotiation asks for a format that the
// Statement disseminator supports
SwordStatementDisseminator disseminator = null;
try
{
disseminator = SwordDisseminatorFactory.getStatementInstance(analysed);
disseminator = SwordDisseminatorFactory
.getStatementInstance(analysed);
}
catch (SwordError swordError)
{
@@ -73,7 +85,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem determining the request type", e);
throw new SwordServerException(
"There was a problem determining the request type", e);
}
finally
{
@@ -85,7 +98,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
public DepositReceipt getEntry(String editIRI, Map<String, String> accept, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt getEntry(String editIRI, Map<String, String> accept,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordServerException, SwordError, SwordAuthException
{
SwordContext sc = null;
@@ -117,7 +131,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
catch (SQLException | DSpaceSwordException e)
{
throw new SwordServerException(e);
} finally
}
finally
{
// this is a read operation only, so there's never any need to commit the context
if (sc != null)
@@ -127,14 +142,16 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
public DepositReceipt replaceMetadata(String editIRI, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt replaceMetadata(String editIRI, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
Date start = new Date();
// store up the verbose description, which we can then give back at the end if necessary
this.verboseDescription.append("Initialising verbose replace of metadata");
this.verboseDescription
.append("Initialising verbose replace of metadata");
SwordContext sc = null;
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
@@ -172,22 +189,30 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "replace_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot replace the given item with this context");
log.info(LogManager
.getHeader(context, "replace_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot replace the given item with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
DepositResult result = null;
try
{
result = this.doReplaceMetadata(sc, item, deposit, authCredentials, config);
result = this
.doReplaceMetadata(sc, item, deposit, authCredentials,
config);
}
catch (DSpaceSwordException | SwordError e)
{
@@ -197,7 +222,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
this.storeEntryAsFile(deposit, authCredentials, config);
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD entry as file: " + e);
}
@@ -209,12 +234,15 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
wfm.resolveState(context, deposit, result, this.verboseDescription);
ReceiptGenerator genny = new ReceiptGenerator();
DepositReceipt receipt = genny.createReceipt(context, result, config);
DepositReceipt receipt = genny
.createReceipt(context, result, config);
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for deposit processing: " + delta + " ms");
this.verboseDescription
.append("Total time for deposit processing: " + delta +
" ms");
this.addVerboseDescription(receipt, this.verboseDescription);
// if something hasn't killed it already (allowed), then complete the transaction
@@ -225,7 +253,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
finally
{
@@ -237,14 +266,17 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
public DepositReceipt replaceMetadataAndMediaResource(String editIRI, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt replaceMetadataAndMediaResource(String editIRI,
Deposit deposit, AuthCredentials authCredentials,
SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
Date start = new Date();
// store up the verbose description, which we can then give back at the end if necessary
this.verboseDescription.append("Initialising verbose multipart replace");
this.verboseDescription
.append("Initialising verbose multipart replace");
SwordContext sc = null;
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
@@ -258,7 +290,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_create_new", ""));
log.debug(
LogManager.getHeader(context, "sword_create_new", ""));
}
// get the deposit target
@@ -283,22 +316,29 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "deposit_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot submit to the given collection with this context");
log.info(LogManager
.getHeader(context, "deposit_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot submit to the given collection with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
DepositResult result = null;
try
{
result = this.replaceFromMultipart(sc, item, deposit, authCredentials, config);
result = this.replaceFromMultipart(sc, item, deposit,
authCredentials, config);
}
catch (DSpaceSwordException | SwordError e)
{
@@ -306,10 +346,11 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
try
{
this.storePackageAsFile(deposit, authCredentials, config);
this.storePackageAsFile(deposit, authCredentials,
config);
this.storeEntryAsFile(deposit, authCredentials, config);
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
}
@@ -321,12 +362,15 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
wfm.resolveState(context, deposit, result, this.verboseDescription);
ReceiptGenerator genny = new ReceiptGenerator();
DepositReceipt receipt = genny.createReceipt(context, result, config);
DepositReceipt receipt = genny
.createReceipt(context, result, config);
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for deposit processing: " + delta + " ms");
this.verboseDescription
.append("Total time for deposit processing: " + delta +
" ms");
this.addVerboseDescription(receipt, this.verboseDescription);
// if something hasn't killed it already (allowed), then complete the transaction
@@ -337,7 +381,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
finally
{
@@ -349,20 +394,23 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
public DepositReceipt addMetadataAndResources(String s, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration config)
public DepositReceipt addMetadataAndResources(String s, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException
{
return null;
}
public DepositReceipt addMetadata(String editIRI, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt addMetadata(String editIRI, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
Date start = new Date();
// store up the verbose description, which we can then give back at the end if necessary
this.verboseDescription.append("Initialising verbose replace of metadata");
this.verboseDescription
.append("Initialising verbose replace of metadata");
SwordContext sc = null;
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
@@ -400,22 +448,29 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "replace_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot replace the given item with this context");
log.info(LogManager
.getHeader(context, "replace_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot replace the given item with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
DepositResult result = null;
try
{
result = this.doAddMetadata(sc, item, deposit, authCredentials, config);
result = this.doAddMetadata(sc, item, deposit, authCredentials,
config);
}
catch (DSpaceSwordException | SwordError e)
{
@@ -425,7 +480,7 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
this.storeEntryAsFile(deposit, authCredentials, config);
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD entry as file: " + e);
}
@@ -437,12 +492,15 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
wfm.resolveState(context, deposit, result, this.verboseDescription);
ReceiptGenerator genny = new ReceiptGenerator();
DepositReceipt receipt = genny.createReceipt(context, result, config);
DepositReceipt receipt = genny
.createReceipt(context, result, config);
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for deposit processing: " + delta + " ms");
this.verboseDescription
.append("Total time for deposit processing: " + delta +
" ms");
this.addVerboseDescription(receipt, this.verboseDescription);
// if something hasn't killed it already (allowed), then complete the transaction
@@ -453,7 +511,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
finally
{
@@ -465,13 +524,15 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
public DepositReceipt addResources(String s, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration config)
public DepositReceipt addResources(String s, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException
{
return null;
}
public void deleteContainer(String editIRI, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public void deleteContainer(String editIRI, AuthCredentials authCredentials,
SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
@@ -516,16 +577,22 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "replace_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot delete the given item with this context");
log.info(LogManager
.getHeader(context, "replace_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot delete the given item with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
this.doContainerDelete(sc, item, authCredentials, config);
@@ -533,7 +600,9 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for deposit processing: " + delta + " ms");
this.verboseDescription
.append("Total time for deposit processing: " + delta +
" ms");
// if something hasn't killed it already (allowed), then complete the transaction
sc.commit();
@@ -541,7 +610,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
finally
{
@@ -553,14 +623,16 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
public DepositReceipt useHeaders(String editIRI, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt useHeaders(String editIRI, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
Date start = new Date();
// store up the verbose description, which we can then give back at the end if necessary
this.verboseDescription.append("Initialising verbose empty request (headers only)");
this.verboseDescription
.append("Initialising verbose empty request (headers only)");
SwordContext sc = null;
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
@@ -572,7 +644,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_modify_by_headers", ""));
log.debug(LogManager
.getHeader(context, "sword_modify_by_headers", ""));
}
// get the deposit target
@@ -598,16 +671,22 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "modify_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot modify the given item with this context");
log.info(LogManager
.getHeader(context, "modify_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot modify the given item with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Modifying on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Modifying on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
DepositResult result = new DepositResult();
@@ -623,7 +702,9 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for modify processing: " + delta + " ms");
this.verboseDescription
.append("Total time for modify processing: " + delta +
" ms");
this.addVerboseDescription(receipt, this.verboseDescription);
// if something hasn't killed it already (allowed), then complete the transaction
@@ -634,7 +715,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
finally
{
@@ -646,23 +728,31 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
private DepositResult replaceFromMultipart(SwordContext swordContext, Item item, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
private DepositResult replaceFromMultipart(SwordContext swordContext,
Item item, Deposit deposit, AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// is the content acceptable? If not, this will throw an error
this.isAcceptable(swordConfig, context, deposit, item);
// Obtain the relevant content ingester from the factory
SwordContentIngester sci = SwordIngesterFactory.getContentInstance(context, deposit, item);
this.verboseDescription.append("Loaded content ingester: " + sci.getClass().getName());
SwordContentIngester sci = SwordIngesterFactory
.getContentInstance(context, deposit, item);
this.verboseDescription
.append("Loaded content ingester: " + sci.getClass().getName());
// obtain the relevant entry intester from the factory
SwordEntryIngester sei = SwordIngesterFactory.getEntryInstance(context, deposit, item);
this.verboseDescription.append("Loaded entry ingester: " + sei.getClass().getName());
SwordEntryIngester sei = SwordIngesterFactory
.getEntryInstance(context, deposit, item);
this.verboseDescription
.append("Loaded entry ingester: " + sei.getClass().getName());
try
{
@@ -684,58 +774,80 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
if (swordConfig.isEntryFirst())
{
// do the entry deposit
result = sei.ingest(context, deposit, item, this.verboseDescription, null, true);
result = sei.ingest(context, deposit, item, this.verboseDescription,
null, true);
// do the content deposit
result = sci.ingest(context, deposit, item, this.verboseDescription, result);
this.verboseDescription.append("Archive ingest completed successfully");
result = sci.ingest(context, deposit, item, this.verboseDescription,
result);
this.verboseDescription
.append("Archive ingest completed successfully");
}
else
{
// do the content deposit
result = sci.ingest(context, deposit, item, this.verboseDescription, null);
result = sci.ingest(context, deposit, item, this.verboseDescription,
null);
// do the entry deposit
result = sei.ingest(context, deposit, item, this.verboseDescription, result, true);
this.verboseDescription.append("Archive ingest completed successfully");
result = sei.ingest(context, deposit, item, this.verboseDescription,
result, true);
this.verboseDescription
.append("Archive ingest completed successfully");
}
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
return result;
}
private DepositResult doReplaceMetadata(SwordContext swordContext, Item item, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
private DepositResult doReplaceMetadata(SwordContext swordContext,
Item item, Deposit deposit, AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// Obtain the relevant ingester from the factory
SwordEntryIngester si = SwordIngesterFactory.getEntryInstance(context, deposit, null);
this.verboseDescription.append("Loaded ingester: " + si.getClass().getName());
SwordEntryIngester si = SwordIngesterFactory
.getEntryInstance(context, deposit, null);
this.verboseDescription
.append("Loaded ingester: " + si.getClass().getName());
// do the deposit
DepositResult result = si.ingest(context, deposit, item, this.verboseDescription, null, true);
DepositResult result = si
.ingest(context, deposit, item, this.verboseDescription, null,
true);
this.verboseDescription.append("Replace completed successfully");
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
return result;
}
protected DepositResult doAddMetadata(SwordContext swordContext, Item item, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
protected DepositResult doAddMetadata(SwordContext swordContext, Item item,
Deposit deposit, AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
return this.doAddMetadata(swordContext, item, deposit, authCredentials, swordConfig, null);
return this.doAddMetadata(swordContext, item, deposit, authCredentials,
swordConfig, null);
}
protected DepositResult doAddMetadata(SwordContext swordContext, Item item, Deposit deposit, AuthCredentials authCredentials,
protected DepositResult doAddMetadata(SwordContext swordContext, Item item,
Deposit deposit, AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
if (result == null)
{
@@ -744,23 +856,31 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// Obtain the relevant ingester from the factory
SwordEntryIngester si = SwordIngesterFactory.getEntryInstance(context, deposit, null);
this.verboseDescription.append("Loaded ingester: " + si.getClass().getName());
SwordEntryIngester si = SwordIngesterFactory
.getEntryInstance(context, deposit, null);
this.verboseDescription
.append("Loaded ingester: " + si.getClass().getName());
// do the deposit
result = si.ingest(context, deposit, item, this.verboseDescription, result, false);
result = si
.ingest(context, deposit, item, this.verboseDescription, result,
false);
this.verboseDescription.append("Replace completed successfully");
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
return result;
}
protected void doContainerDelete(SwordContext swordContext, Item item, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
protected void doContainerDelete(SwordContext swordContext, Item item,
AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordAuthException
{
try
@@ -793,7 +913,8 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
}
}
private Item getDSpaceTarget(Context context, String editUrl, SwordConfigurationDSpace config)
private Item getDSpaceTarget(Context context, String editUrl,
SwordConfigurationDSpace config)
throws DSpaceSwordException, SwordError
{
SwordUrlManager urlManager = config.getUrlManager(context, config);
@@ -805,8 +926,11 @@ public class ContainerManagerDSpace extends DSpaceSwordAPI implements ContainerM
throw new SwordError(404);
}
this.verboseDescription.append("Performing replace using edit-media URL: " + editUrl);
this.verboseDescription.append("Location resolves to item with handle: " + item.getHandle());
this.verboseDescription
.append("Performing replace using edit-media URL: " + editUrl);
this.verboseDescription
.append("Location resolves to item with handle: " +
item.getHandle());
return item;
}

View File

@@ -2,12 +2,11 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
@@ -55,10 +54,17 @@ public class DSpaceSwordAPI
{
private static Logger log = Logger.getLogger(DSpaceSwordAPI.class);
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
public SwordContext noAuthContext()
throws DSpaceSwordException
@@ -84,9 +90,14 @@ public class DSpaceSwordAPI
SwordContext sc = auth.authenticate(authCredentials);
// log the request
String un = authCredentials.getUsername() != null ? authCredentials.getUsername() : "NONE";
String obo = authCredentials.getOnBehalfOf() != null ? authCredentials.getOnBehalfOf() : "NONE";
log.info(LogManager.getHeader(sc.getContext(), "sword_auth_request", "username=" + un + ",on_behalf_of=" + obo));
String un = authCredentials.getUsername() != null ?
authCredentials.getUsername() :
"NONE";
String obo = authCredentials.getOnBehalfOf() != null ?
authCredentials.getOnBehalfOf() :
"NONE";
log.info(LogManager.getHeader(sc.getContext(), "sword_auth_request",
"username=" + un + ",on_behalf_of=" + obo));
return sc;
}
@@ -139,7 +150,8 @@ public class DSpaceSwordAPI
if (components[1].trim().startsWith("q="))
{
// "type;q"
q = Float.parseFloat(components[1].trim().substring(2)); //strip the "q=" from the start of the q value
q = Float.parseFloat(components[1].trim().substring(
2)); //strip the "q=" from the start of the q value
// if the q value is the highest one we've seen so far, record it
if (q > highest_q)
@@ -157,7 +169,8 @@ public class DSpaceSwordAPI
{
// "type;params;q"
params = components[1].trim();
q = Float.parseFloat(components[1].trim().substring(2)); // strip the "q=" from the start of the q value
q = Float.parseFloat(components[1].trim().substring(
2)); // strip the "q=" from the start of the q value
// if the q value is the highest one we've seen so far, record it
if (q > highest_q)
@@ -211,7 +224,7 @@ public class DSpaceSwordAPI
// otherwise, we have to calculate the q value using the following equation which creates a q value "qv"
// within "q_range" of 1.0 [the first part of the eqn] based on the fraction of the way through the total
// accept header list scaled by the q_range [the second part of the eqn]
float nq = (1 - q_range) + (((-1 * qv)/counter) * q_range);
float nq = (1 - q_range) + (((-1 * qv) / counter) * q_range);
if (sorted.containsKey(nq))
{
sorted.get(nq).add(contentType);
@@ -228,28 +241,36 @@ public class DSpaceSwordAPI
return sorted;
}
public void isAcceptable(SwordConfigurationDSpace swordConfig, Context context, Deposit deposit, DSpaceObject dso)
public void isAcceptable(SwordConfigurationDSpace swordConfig,
Context context, Deposit deposit, DSpaceObject dso)
throws SwordError, DSpaceSwordException
{
// determine if this is an acceptable file format
if (!swordConfig.isAcceptableContentType(context, deposit.getMimeType(), dso))
if (!swordConfig
.isAcceptableContentType(context, deposit.getMimeType(), dso))
{
log.error("Unacceptable content type detected: " + deposit.getMimeType() + " for object " + dso.getID());
log.error("Unacceptable content type detected: " +
deposit.getMimeType() + " for object " + dso.getID());
throw new SwordError(UriRegistry.ERROR_CONTENT,
"Unacceptable content type in deposit request: " + deposit.getMimeType());
"Unacceptable content type in deposit request: " +
deposit.getMimeType());
}
// determine if this is an acceptable packaging type for the deposit
// if not, we throw a 415 HTTP error (Unsupported Media Type, ERROR_CONTENT)
if (!swordConfig.isAcceptedPackaging(deposit.getPackaging(), dso))
{
log.error("Unacceptable packaging type detected: " + deposit.getPackaging() + " for object " + dso.getID());
log.error("Unacceptable packaging type detected: " +
deposit.getPackaging() + " for object " + dso.getID());
throw new SwordError(UriRegistry.ERROR_CONTENT,
"Unacceptable packaging type in deposit request: " + deposit.getPackaging());
"Unacceptable packaging type in deposit request: " +
deposit.getPackaging());
}
}
public void storeOriginals(SwordConfigurationDSpace swordConfig, Context context, VerboseDescription verboseDescription, Deposit deposit, DepositResult result)
public void storeOriginals(SwordConfigurationDSpace swordConfig,
Context context, VerboseDescription verboseDescription,
Deposit deposit, DepositResult result)
throws DSpaceSwordException, SwordServerException
{
// if there's an item availalble, and we want to keep the original
@@ -258,14 +279,16 @@ public class DSpaceSwordAPI
{
if (swordConfig.isKeepOriginal())
{
verboseDescription.append("DSpace will store an original copy of the deposit, " +
verboseDescription
.append("DSpace will store an original copy of the deposit, " +
"as well as ingesting the item into the archive");
// in order to be allowed to add the file back to the item, we need to ignore authorisations
// for a moment
context.turnOffAuthorisationSystem();
String bundleName = ConfigurationManager.getProperty("swordv2-server", "bundle.name");
String bundleName = ConfigurationManager
.getProperty("swordv2-server", "bundle.name");
if (bundleName == null || "".equals(bundleName))
{
bundleName = "SWORD";
@@ -283,20 +306,26 @@ public class DSpaceSwordAPI
}
if (swordBundle == null)
{
swordBundle = bundleService.create(context, item, bundleName);
swordBundle = bundleService
.create(context, item, bundleName);
}
if (deposit.isMultipart() || deposit.isEntryOnly())
{
String entry = deposit.getSwordEntry().toString();
ByteArrayInputStream bais = new ByteArrayInputStream(entry.getBytes());
Bitstream entryBitstream = bitstreamService.create(context, swordBundle, bais);
ByteArrayInputStream bais = new ByteArrayInputStream(
entry.getBytes());
Bitstream entryBitstream = bitstreamService
.create(context, swordBundle, bais);
String fn = this.createEntryFilename(context, deposit, true);
String fn = this
.createEntryFilename(context, deposit, true);
entryBitstream.setName(context, fn);
entryBitstream.setDescription(context, "Original SWORD entry document");
entryBitstream.setDescription(context,
"Original SWORD entry document");
BitstreamFormat bf = bitstreamFormatService.findByMIMEType(context, "application/xml");
BitstreamFormat bf = bitstreamFormatService
.findByMIMEType(context, "application/xml");
if (bf != null)
{
entryBitstream.setFormat(context, bf);
@@ -304,7 +333,8 @@ public class DSpaceSwordAPI
bitstreamService.update(context, entryBitstream);
verboseDescription.append("Original entry stored as " + fn + ", in item bundle " + swordBundle);
verboseDescription.append("Original entry stored as " + fn +
", in item bundle " + swordBundle);
}
if (deposit.isMultipart() || deposit.isBinaryOnly())
@@ -316,7 +346,8 @@ public class DSpaceSwordAPI
try
{
fis = deposit.getInputStream();
bitstream = bitstreamService.create(context, swordBundle, fis);
bitstream = bitstreamService
.create(context, swordBundle, fis);
}
finally
{
@@ -334,9 +365,11 @@ public class DSpaceSwordAPI
}
bitstream.setName(context, fn);
bitstream.setDescription(context, "Original SWORD deposit file");
bitstream.setDescription(context,
"Original SWORD deposit file");
BitstreamFormat bf = bitstreamFormatService.findByMIMEType(context, deposit.getMimeType());
BitstreamFormat bf = bitstreamFormatService
.findByMIMEType(context, deposit.getMimeType());
if (bf != null)
{
bitstream.setFormat(context, bf);
@@ -349,7 +382,9 @@ public class DSpaceSwordAPI
// shouldn't mess with it
result.setOriginalDeposit(bitstream);
}
verboseDescription.append("Original deposit stored as " + fn + ", in item bundle " + swordBundle);
verboseDescription
.append("Original deposit stored as " + fn +
", in item bundle " + swordBundle);
}
bundleService.update(context, swordBundle);
@@ -374,12 +409,14 @@ public class DSpaceSwordAPI
* @param original
* @throws DSpaceSwordException
*/
public String createFilename(Context context, Deposit deposit, boolean original)
public String createFilename(Context context, Deposit deposit,
boolean original)
throws DSpaceSwordException
{
try
{
BitstreamFormat bf = bitstreamFormatService.findByMIMEType(context, deposit.getMimeType());
BitstreamFormat bf = bitstreamFormatService
.findByMIMEType(context, deposit.getMimeType());
List<String> exts = null;
if (bf != null)
{
@@ -389,7 +426,8 @@ public class DSpaceSwordAPI
String fn = deposit.getFilename();
if (fn == null || "".equals(fn))
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
fn = "sword-" + sdf.format(new Date());
if (original)
{
@@ -409,7 +447,8 @@ public class DSpaceSwordAPI
}
}
public String createEntryFilename(Context context, Deposit deposit, boolean original)
public String createEntryFilename(Context context, Deposit deposit,
boolean original)
throws DSpaceSwordException
{
@@ -429,29 +468,35 @@ public class DSpaceSwordAPI
*
* @param deposit
*/
protected void storePackageAsFile(Deposit deposit, AuthCredentials auth, SwordConfigurationDSpace config) throws IOException
protected void storePackageAsFile(Deposit deposit, AuthCredentials auth,
SwordConfigurationDSpace config) throws IOException
{
String path = config.getFailedPackageDir();
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory())
{
throw new IOException("Directory does not exist for writing packages on ingest error.");
throw new IOException(
"Directory does not exist for writing packages on ingest error.");
}
String filenameBase = "sword-" + auth.getUsername() + "-" + (new Date()).getTime();
String filenameBase =
"sword-" + auth.getUsername() + "-" + (new Date()).getTime();
File packageFile = new File(path, filenameBase);
File headersFile = new File(path, filenameBase + "-headers");
InputStream is = new BufferedInputStream(new FileInputStream(deposit.getFile()));
OutputStream fos = new BufferedOutputStream(new FileOutputStream(packageFile));
InputStream is = new BufferedInputStream(
new FileInputStream(deposit.getFile()));
OutputStream fos = new BufferedOutputStream(
new FileOutputStream(packageFile));
Utils.copy(is, fos);
fos.close();
is.close();
//write companion file with headers
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(headersFile)));
PrintWriter pw = new PrintWriter(
new BufferedWriter(new FileWriter(headersFile)));
pw.println("Filename=" + deposit.getFilename());
pw.println("Content-Type=" + deposit.getMimeType());
@@ -468,30 +513,35 @@ public class DSpaceSwordAPI
*
* @param deposit
*/
protected void storeEntryAsFile(Deposit deposit, AuthCredentials auth, SwordConfigurationDSpace config) throws IOException
protected void storeEntryAsFile(Deposit deposit, AuthCredentials auth,
SwordConfigurationDSpace config) throws IOException
{
String path = config.getFailedPackageDir();
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory())
{
throw new IOException("Directory does not exist for writing packages on ingest error.");
throw new IOException(
"Directory does not exist for writing packages on ingest error.");
}
String filenameBase = "sword-" + auth.getUsername() + "-" + (new Date()).getTime();
String filenameBase =
"sword-" + auth.getUsername() + "-" + (new Date()).getTime();
File packageFile = new File(path, filenameBase);
File headersFile = new File(path, filenameBase + "-headers");
String entry = deposit.getSwordEntry().toString();
ByteArrayInputStream is = new ByteArrayInputStream(entry.getBytes());
OutputStream fos = new BufferedOutputStream(new FileOutputStream(packageFile));
OutputStream fos = new BufferedOutputStream(
new FileOutputStream(packageFile));
Utils.copy(is, fos);
fos.close();
is.close();
//write companion file with headers
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(headersFile)));
PrintWriter pw = new PrintWriter(
new BufferedWriter(new FileWriter(headersFile)));
pw.println("Filename=" + deposit.getFilename());
pw.println("Content-Type=" + deposit.getMimeType());
@@ -502,9 +552,12 @@ public class DSpaceSwordAPI
pw.close();
}
protected void addVerboseDescription(DepositReceipt receipt, VerboseDescription verboseDescription)
protected void addVerboseDescription(DepositReceipt receipt,
VerboseDescription verboseDescription)
{
boolean includeVerbose = ConfigurationManager.getBooleanProperty("swordv2-server", "verbose-description.receipt.enable");
boolean includeVerbose = ConfigurationManager
.getBooleanProperty("swordv2-server",
"verbose-description.receipt.enable");
if (includeVerbose)
{
receipt.setVerboseDescription(verboseDescription.toString());

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -12,32 +12,40 @@ public class DSpaceUriRegistry
public static final String DSPACE_SWORD_NS = "http://www.dspace.org/ns/sword/2.0/";
/** if unpackaging the package fails */
public static final String UNPACKAGE_FAIL = DSPACE_SWORD_NS + "errors/UnpackageFail";
public static final String UNPACKAGE_FAIL =
DSPACE_SWORD_NS + "errors/UnpackageFail";
/** if the url of the request does not resolve to something meaningful */
public static final String BAD_URL = DSPACE_SWORD_NS + "errors/BadUrl";
/** if the media requested is unavailable */
public static final String MEDIA_UNAVAILABLE = DSPACE_SWORD_NS + "errors/MediaUnavailable";
public static final String MEDIA_UNAVAILABLE =
DSPACE_SWORD_NS + "errors/MediaUnavailable";
/* additional codes */
/** Invalid package */
public static final String PACKAGE_ERROR = DSPACE_SWORD_NS + "errors/PackageError";
public static final String PACKAGE_ERROR =
DSPACE_SWORD_NS + "errors/PackageError";
/** Missing resources in package */
public static final String PACKAGE_VALIDATION_ERROR = DSPACE_SWORD_NS + "errors/PackageValidationError";
public static final String PACKAGE_VALIDATION_ERROR =
DSPACE_SWORD_NS + "errors/PackageValidationError";
/** Crosswalk error */
public static final String CROSSWALK_ERROR = DSPACE_SWORD_NS + "errors/CrosswalkError";
public static final String CROSSWALK_ERROR =
DSPACE_SWORD_NS + "errors/CrosswalkError";
/** Invalid collection for linking */
public static final String COLLECTION_LINK_ERROR = DSPACE_SWORD_NS + "errors/CollectionLinkError";
public static final String COLLECTION_LINK_ERROR =
DSPACE_SWORD_NS + "errors/CollectionLinkError";
/** Database or IO Error when installing new item */
public static final String REPOSITORY_ERROR = DSPACE_SWORD_NS + "errors/RepositoryError";
public static final String REPOSITORY_ERROR =
DSPACE_SWORD_NS + "errors/RepositoryError";
// FIXME: this is being withdrawn from all 406 responses for the time being, in preference
// for ErrorContent as per the spec (whether that is right or wrong)
public static final String NOT_ACCEPTABLE = DSPACE_SWORD_NS + "errors/NotAcceptable";
public static final String NOT_ACCEPTABLE =
DSPACE_SWORD_NS + "errors/NotAcceptable";
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -26,7 +26,8 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
public class FeedContentDisseminator extends AbstractSimpleDC implements SwordContentDisseminator
public class FeedContentDisseminator extends AbstractSimpleDC
implements SwordContentDisseminator
{
public InputStream disseminate(Context context, Item item)
throws DSpaceSwordException, SwordError, SwordServerException
@@ -43,10 +44,13 @@ public class FeedContentDisseminator extends AbstractSimpleDC implements SwordCo
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
{
List<BundleBitstream> bundleBitstreams = bundle.getBitstreams();
for (BundleBitstream bundleBitstream : bundleBitstreams) {
List<BundleBitstream> bundleBitstreams = bundle
.getBitstreams();
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
Entry entry = feed.addEntry();
this.populateEntry(context, entry, bundleBitstream.getBitstream());
this.populateEntry(context, entry,
bundleBitstream.getBitstream());
}
}
}
@@ -90,13 +94,17 @@ public class FeedContentDisseminator extends AbstractSimpleDC implements SwordCo
}
}
private void populateEntry(Context context, Entry entry, Bitstream bitstream)
private void populateEntry(Context context, Entry entry,
Bitstream bitstream)
throws DSpaceSwordException
{
BitstreamFormat format = null;
try {
try
{
format = bitstream.getFormat(context);
} catch (SQLException e) {
}
catch (SQLException e)
{
throw new DSpaceSwordException(e);
}
String contentType = null;
@@ -105,7 +113,8 @@ public class FeedContentDisseminator extends AbstractSimpleDC implements SwordCo
contentType = format.getMIMEType();
}
SwordUrlManager urlManager = new SwordUrlManager(new SwordConfigurationDSpace(), context);
SwordUrlManager urlManager = new SwordUrlManager(
new SwordConfigurationDSpace(), context);
String bsUrl = urlManager.getBitstreamUrl(bitstream);
entry.setId(bsUrl);
@@ -133,10 +142,12 @@ public class FeedContentDisseminator extends AbstractSimpleDC implements SwordCo
public boolean disseminatesContentType(String contentType)
throws DSpaceSwordException, SwordError, SwordServerException
{
return "application/atom+xml".equals(contentType) || "application/atom+xml;type=feed".equals(contentType);
return "application/atom+xml".equals(contentType) ||
"application/atom+xml;type=feed".equals(contentType);
}
public boolean disseminatesPackage(String contentType) throws DSpaceSwordException, SwordError, SwordServerException
public boolean disseminatesPackage(String contentType)
throws DSpaceSwordException, SwordError, SwordServerException
{
// we're just going to ignore packaging formats here
return true;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -24,21 +24,25 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class GenericStatementDisseminator implements SwordStatementDisseminator
public abstract class GenericStatementDisseminator
implements SwordStatementDisseminator
{
protected SwordUrlManager urlManager;
protected void populateStatement(Context context, Item item, Statement statement)
protected void populateStatement(Context context, Item item,
Statement statement)
throws DSpaceSwordException
{
this.urlManager = new SwordUrlManager(new SwordConfigurationDSpace(), context);
this.urlManager = new SwordUrlManager(new SwordConfigurationDSpace(),
context);
List<String> includeBundles = this.getIncludeBundles();
String originalDepositBundle = this.getOriginalDepositsBundle();
// we only list the original deposits in full if the sword bundle is in the includeBundles
if (includeBundles.contains(originalDepositBundle))
{
List<OriginalDeposit> originalDeposits = this.getOriginalDeposits(context, item, originalDepositBundle);
List<OriginalDeposit> originalDeposits = this
.getOriginalDeposits(context, item, originalDepositBundle);
statement.setOriginalDeposits(originalDeposits);
}
@@ -47,14 +51,16 @@ public abstract class GenericStatementDisseminator implements SwordStatementDiss
// remove the original deposit bundle from the include bundles
includeBundles.remove(originalDepositBundle);
List<ResourcePart> resources = this.getResourceParts(context, item, includeBundles);
List<ResourcePart> resources = this
.getResourceParts(context, item, includeBundles);
statement.setResources(resources);
Date lastModified = this.getLastModified(context, item);
statement.setLastModified(lastModified);
}
protected List<OriginalDeposit> getOriginalDeposits(Context context, Item item, String swordBundle)
protected List<OriginalDeposit> getOriginalDeposits(Context context,
Item item, String swordBundle)
throws DSpaceSwordException
{
try
@@ -70,11 +76,16 @@ public abstract class GenericStatementDisseminator implements SwordStatementDiss
{
if (swordBundle.equals(bundle.getName()))
{
List<BundleBitstream> bundleBitstreams = bundle.getBitstreams();
for (BundleBitstream bundleBitstream : bundleBitstreams) {
List<BundleBitstream> bundleBitstreams = bundle
.getBitstreams();
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
// note that original deposits don't have actionable urls
OriginalDeposit deposit = new OriginalDeposit(this.urlManager.getBitstreamUrl(bundleBitstream.getBitstream()));
deposit.setMediaType(bundleBitstream.getBitstream().getFormat(context).getMIMEType());
OriginalDeposit deposit = new OriginalDeposit(
this.urlManager.getBitstreamUrl(
bundleBitstream.getBitstream()));
deposit.setMediaType(bundleBitstream.getBitstream()
.getFormat(context).getMIMEType());
originalDeposits.add(deposit);
}
}
@@ -120,7 +131,8 @@ public abstract class GenericStatementDisseminator implements SwordStatementDiss
return states;
}
protected List<ResourcePart> getResourceParts(Context context, Item item, List<String> includeBundles)
protected List<ResourcePart> getResourceParts(Context context, Item item,
List<String> includeBundles)
throws DSpaceSwordException
{
try
@@ -135,11 +147,16 @@ public abstract class GenericStatementDisseminator implements SwordStatementDiss
{
if (bundleName.equals(bundle.getName()))
{
List<BundleBitstream> bundleBitstreams = bundle.getBitstreams();
for (BundleBitstream bundleBitstream : bundleBitstreams) {
List<BundleBitstream> bundleBitstreams = bundle
.getBitstreams();
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
// note that individual bitstreams have actionable urls
ResourcePart part = new ResourcePart(this.urlManager.getActionableBitstreamUrl(bundleBitstream.getBitstream()));
part.setMediaType(bundleBitstream.getBitstream().getFormat(context).getMIMEType());
ResourcePart part = new ResourcePart(this.urlManager
.getActionableBitstreamUrl(
bundleBitstream.getBitstream()));
part.setMediaType(bundleBitstream.getBitstream()
.getFormat(context).getMIMEType());
resources.add(part);
}
}
@@ -161,7 +178,8 @@ public abstract class GenericStatementDisseminator implements SwordStatementDiss
private List<String> getIncludeBundles()
{
String cfg = ConfigurationManager.getProperty("swordv2-server", "statement.bundles");
String cfg = ConfigurationManager
.getProperty("swordv2-server", "statement.bundles");
if (cfg == null || "".equals(cfg))
{
cfg = "ORIGINAL, SWORD";
@@ -181,7 +199,8 @@ public abstract class GenericStatementDisseminator implements SwordStatementDiss
private String getOriginalDepositsBundle()
{
String swordBundle = ConfigurationManager.getProperty("swordv2-server", "bundle.name");
String swordBundle = ConfigurationManager
.getProperty("swordv2-server", "bundle.name");
if (swordBundle == null)
{
swordBundle = "SWORD";

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -27,12 +27,17 @@ import java.io.InputStream;
import java.sql.SQLException;
import java.util.*;
public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaResourceManager
public class MediaResourceManagerDSpace extends DSpaceSwordAPI
implements MediaResourceManager
{
private static Logger log = Logger.getLogger(MediaResourceManagerDSpace.class);
private static Logger log = Logger
.getLogger(MediaResourceManagerDSpace.class);
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory
.getInstance().getAuthorizeService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
private VerboseDescription verboseDescription = new VerboseDescription();
@@ -41,7 +46,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
try
{
return authorizeService.authorizeActionBoolean(context, bitstream, Constants.READ);
return authorizeService
.authorizeActionBoolean(context, bitstream, Constants.READ);
}
catch (SQLException e)
{
@@ -54,7 +60,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
try
{
return authorizeService.authorizeActionBoolean(context, item, Constants.READ);
return authorizeService
.authorizeActionBoolean(context, item, Constants.READ);
}
catch (SQLException e)
{
@@ -62,13 +69,15 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
}
private MediaResource getBitstreamResource(Context context, Bitstream bitstream)
private MediaResource getBitstreamResource(Context context,
Bitstream bitstream)
throws SwordServerException, SwordAuthException
{
try
{
InputStream stream = bitstreamService.retrieve(context, bitstream);
MediaResource mr = new MediaResource(stream, bitstream.getFormat(context).getMIMEType(), null, true);
MediaResource mr = new MediaResource(stream,
bitstream.getFormat(context).getMIMEType(), null, true);
mr.setContentMD5(bitstream.getChecksum());
mr.setLastModified(this.getLastModified(context, bitstream));
return mr;
@@ -76,13 +85,15 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
catch (IOException | SQLException e)
{
throw new SwordServerException(e);
} catch (AuthorizeException e)
}
catch (AuthorizeException e)
{
throw new SwordAuthException(e);
}
}
private MediaResource getItemResource(Context context, Item item, SwordUrlManager urlManager, String uri, Map<String, String> accept)
private MediaResource getItemResource(Context context, Item item,
SwordUrlManager urlManager, String uri, Map<String, String> accept)
throws SwordError, DSpaceSwordException, SwordServerException
{
boolean feedRequest = urlManager.isFeedRequest(context, uri);
@@ -94,16 +105,19 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
if (!feedRequest)
{
String acceptContentType = this.getHeader(accept, "Accept", null);
String acceptPackaging = this.getHeader(accept, "Accept-Packaging", UriRegistry.PACKAGE_SIMPLE_ZIP);
String acceptPackaging = this.getHeader(accept, "Accept-Packaging",
UriRegistry.PACKAGE_SIMPLE_ZIP);
// we know that only one Accept-Packaging value is allowed, so we don't need
// to do any further work on it.
// we extract from the Accept header the ordered list of content types
TreeMap<Float, List<String>> analysed = this.analyseAccept(acceptContentType);
TreeMap<Float, List<String>> analysed = this
.analyseAccept(acceptContentType);
// the meat of this is done by the package disseminator
disseminator = SwordDisseminatorFactory.getContentInstance(analysed, acceptPackaging);
disseminator = SwordDisseminatorFactory
.getContentInstance(analysed, acceptPackaging);
}
else
{
@@ -113,16 +127,20 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
List<String> list = new ArrayList<String>();
list.add("application/atom+xml");
analysed.put((float) 1.0, list);
disseminator = SwordDisseminatorFactory.getContentInstance(analysed, null);
disseminator = SwordDisseminatorFactory
.getContentInstance(analysed, null);
}
// Note that at this stage, if we don't have a desiredContentType, it will
// be null, and the disseminator is free to choose the format
InputStream stream = disseminator.disseminate(context, item);
return new MediaResource(stream, disseminator.getContentType(), disseminator.getPackaging());
return new MediaResource(stream, disseminator.getContentType(),
disseminator.getPackaging());
}
public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> accept, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public MediaResource getMediaResourceRepresentation(String uri,
Map<String, String> accept, AuthCredentials authCredentials,
SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// all the bits we need to make this method function
@@ -149,7 +167,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
// find out, now we know what we're being asked for, whether this is allowed
WorkflowManagerFactory.getInstance().retrieveBitstream(ctx, bitstream);
WorkflowManagerFactory.getInstance()
.retrieveBitstream(ctx, bitstream);
// we can do this in principle, but now find out whether the bitstream is accessible without credentials
boolean accessible = this.isAccessible(ctx, bitstream);
@@ -212,7 +231,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
// if we get to here we are either allowed to access the bitstream without credentials,
// or we have been authenticated
MediaResource mr = this.getItemResource(ctx, item, urlManager, uri, accept);
MediaResource mr = this
.getItemResource(ctx, item, urlManager, uri, accept);
// sc.abort();
ctx.abort();
return mr;
@@ -221,7 +241,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
catch (SQLException | DSpaceSwordException e)
{
throw new SwordServerException(e);
} finally
}
finally
{
// if there is a sword context, abort it (this will abort the inner dspace context as well)
if (sc != null)
@@ -263,14 +284,16 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
return lm;
}
public DepositReceipt replaceMediaResource(String emUri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt replaceMediaResource(String emUri, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
Date start = new Date();
// store up the verbose description, which we can then give back at the end if necessary
this.verboseDescription.append("Initialising verbose replace of media resource");
this.verboseDescription
.append("Initialising verbose replace of media resource");
SwordContext sc = null;
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
@@ -305,7 +328,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
List<BundleBitstream> bundleBitstreams = bitstream.getBundles();
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
List<Item> bundleItems = bundleBitstream.getBundle().getItems();
List<Item> bundleItems = bundleBitstream.getBundle()
.getItems();
for (Item item : bundleItems)
{
this.checkAuth(sc, item);
@@ -314,16 +338,20 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
DepositResult result = null;
try
{
result = this.replaceBitstream(sc, items, bitstream, deposit, authCredentials, config);
result = this
.replaceBitstream(sc, items, bitstream, deposit,
authCredentials, config);
}
catch (DSpaceSwordException | SwordError e)
{
@@ -331,18 +359,21 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
try
{
this.storePackageAsFile(deposit, authCredentials, config);
this.storePackageAsFile(deposit, authCredentials,
config);
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
log.warn("Unable to store SWORD package as file: " +
e);
}
}
throw e;
}
// now we've produced a deposit, we need to decide on its workflow state
wfm.resolveState(context, deposit, null, this.verboseDescription, false);
wfm.resolveState(context, deposit, null,
this.verboseDescription, false);
ReceiptGenerator genny = new ReceiptGenerator();
receipt = genny.createFileReceipt(context, result, config);
@@ -372,21 +403,28 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "replace_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot replace the given item with this context");
log.info(LogManager
.getHeader(context, "replace_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot replace the given item with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
try
{
this.replaceContent(sc, item, deposit, authCredentials, config);
this.replaceContent(sc, item, deposit, authCredentials,
config);
}
catch (DSpaceSwordException | SwordError e)
{
@@ -394,27 +432,33 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
try
{
this.storePackageAsFile(deposit, authCredentials, config);
this.storePackageAsFile(deposit, authCredentials,
config);
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
log.warn("Unable to store SWORD package as file: " +
e);
}
}
throw e;
}
// now we've produced a deposit, we need to decide on its workflow state
wfm.resolveState(context, deposit, null, this.verboseDescription, false);
wfm.resolveState(context, deposit, null,
this.verboseDescription, false);
ReceiptGenerator genny = new ReceiptGenerator();
receipt = genny.createMediaResourceReceipt(context, item, config);
receipt = genny
.createMediaResourceReceipt(context, item, config);
}
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for deposit processing: " + delta + " ms");
this.verboseDescription
.append("Total time for deposit processing: " + delta +
" ms");
// receipt.setVerboseDescription(this.verboseDescription.toString());
// if something hasn't killed it already (allowed), then complete the transaction
@@ -426,7 +470,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
catch (SQLException e)
{
@@ -442,14 +487,16 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
}
public void deleteMediaResource(String emUri, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public void deleteMediaResource(String emUri,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
Date start = new Date();
// store up the verbose description, which we can then give back at the end if necessary
this.verboseDescription.append("Initialising verbose delete of media resource");
this.verboseDescription
.append("Initialising verbose delete of media resource");
SwordContext sc = null;
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
@@ -484,7 +531,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
List<Item> items = new ArrayList<>();
for (BundleBitstream bundleBitstream : bitstream.getBundles())
{
List<Item> bundleItems = bundleBitstream.getBundle().getItems();
List<Item> bundleItems = bundleBitstream.getBundle()
.getItems();
for (Item item : bundleItems)
{
this.checkAuth(sc, item);
@@ -493,13 +541,16 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
this.removeBitstream(sc, bitstream, items, authCredentials, config);
this.removeBitstream(sc, bitstream, items, authCredentials,
config);
}
else
{
@@ -524,16 +575,22 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "replace_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot replace the given item with this context");
log.info(LogManager
.getHeader(context, "replace_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot replace the given item with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
// do the business of removal
@@ -541,7 +598,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
// now we've produced a deposit, we need to decide on its workflow state
wfm.resolveState(context, null, null, this.verboseDescription, false);
wfm.resolveState(context, null, null, this.verboseDescription,
false);
//ReceiptGenerator genny = new ReceiptGenerator();
//DepositReceipt receipt = genny.createReceipt(context, result, config);
@@ -549,7 +607,9 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for deposit processing: " + delta + " ms");
this.verboseDescription
.append("Total time for deposit processing: " + delta +
" ms");
// receipt.setVerboseDescription(this.verboseDescription.toString());
// if something hasn't killed it already (allowed), then complete the transaction
@@ -561,7 +621,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
catch (SQLException e)
{
@@ -577,14 +638,16 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
}
public DepositReceipt addResource(String emUri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public DepositReceipt addResource(String emUri, Deposit deposit,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordError, SwordServerException, SwordAuthException
{
// start the timer
Date start = new Date();
// store up the verbose description, which we can then give back at the end if necessary
this.verboseDescription.append("Initialising verbose add to media resource");
this.verboseDescription
.append("Initialising verbose add to media resource");
SwordContext sc = null;
SwordConfigurationDSpace config = (SwordConfigurationDSpace) swordConfig;
@@ -622,26 +685,35 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "replace_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot replace the given item with this context");
log.info(LogManager
.getHeader(context, "replace_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot replace the given item with this context");
}
// make a note of the authentication in the verbose string
this.verboseDescription.append("Authenticated user: " + sc.getAuthenticated().getEmail());
this.verboseDescription.append("Authenticated user: " +
sc.getAuthenticated().getEmail());
if (sc.getOnBehalfOf() != null)
{
this.verboseDescription.append("Depositing on behalf of: " + sc.getOnBehalfOf().getEmail());
this.verboseDescription.append("Depositing on behalf of: " +
sc.getOnBehalfOf().getEmail());
}
DepositResult result;
try
{
result = this.addContent(sc, item, deposit, authCredentials, config);
result = this
.addContent(sc, item, deposit, authCredentials, config);
if (deposit.isMultipart())
{
ContainerManagerDSpace cm = new ContainerManagerDSpace();
result = cm.doAddMetadata(sc, item, deposit, authCredentials, config, result);
result = cm
.doAddMetadata(sc, item, deposit, authCredentials,
config, result);
}
}
catch (DSpaceSwordException | SwordError e)
@@ -650,13 +722,15 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
try
{
this.storePackageAsFile(deposit, authCredentials, config);
this.storePackageAsFile(deposit, authCredentials,
config);
if (deposit.isMultipart())
{
this.storeEntryAsFile(deposit, authCredentials, config);
this.storeEntryAsFile(deposit, authCredentials,
config);
}
}
catch(IOException e2)
catch (IOException e2)
{
log.warn("Unable to store SWORD package as file: " + e);
}
@@ -665,7 +739,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
// now we've produced a deposit, we need to decide on its workflow state
wfm.resolveState(context, deposit, null, this.verboseDescription, false);
wfm.resolveState(context, deposit, null, this.verboseDescription,
false);
ReceiptGenerator genny = new ReceiptGenerator();
@@ -687,7 +762,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
Date finish = new Date();
long delta = finish.getTime() - start.getTime();
this.verboseDescription.append("Total time for add processing: " + delta + " ms");
this.verboseDescription
.append("Total time for add processing: " + delta + " ms");
this.addVerboseDescription(receipt, this.verboseDescription);
// if something hasn't killed it already (allowed), then complete the transaction
@@ -698,7 +774,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
catch (DSpaceSwordException e)
{
log.error("caught exception:", e);
throw new SwordServerException("There was a problem depositing the item", e);
throw new SwordServerException(
"There was a problem depositing the item", e);
}
finally
{
@@ -710,7 +787,9 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
}
private void removeContent(SwordContext swordContext, Item item, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
private void removeContent(SwordContext swordContext, Item item,
AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordAuthException
{
try
@@ -738,7 +817,9 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
}
private void removeBitstream(SwordContext swordContext, Bitstream bitstream, List<Item> items, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
private void removeBitstream(SwordContext swordContext, Bitstream bitstream,
List<Item> items, AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordAuthException
{
try
@@ -760,19 +841,25 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
}
private void replaceContent(SwordContext swordContext, Item item, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
private void replaceContent(SwordContext swordContext, Item item,
Deposit deposit, AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// is the content acceptable? If not, this will throw an error
this.isAcceptable(swordConfig, context, deposit, item);
// Obtain the relevant ingester from the factory
SwordContentIngester si = SwordIngesterFactory.getContentInstance(context, deposit, null);
this.verboseDescription.append("Loaded ingester: " + si.getClass().getName());
SwordContentIngester si = SwordIngesterFactory
.getContentInstance(context, deposit, null);
this.verboseDescription
.append("Loaded ingester: " + si.getClass().getName());
try
{
@@ -791,15 +878,21 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
// do the deposit
DepositResult result = si.ingest(context, deposit, item, this.verboseDescription);
DepositResult result = si
.ingest(context, deposit, item, this.verboseDescription);
this.verboseDescription.append("Replace completed successfully");
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
}
private DepositResult replaceBitstream(SwordContext swordContext, List<Item> items, Bitstream bitstream, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
private DepositResult replaceBitstream(SwordContext swordContext,
List<Item> items, Bitstream bitstream, Deposit deposit,
AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// FIXME: this is basically not possible with the existing DSpace API.
@@ -810,7 +903,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// is the content acceptable to the items? If not, this will throw an error
for (Item item : items)
@@ -819,13 +913,16 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
// Obtain the relevant ingester from the factory
SwordContentIngester si = SwordIngesterFactory.getContentInstance(context, deposit, null);
this.verboseDescription.append("Loaded ingester: " + si.getClass().getName());
SwordContentIngester si = SwordIngesterFactory
.getContentInstance(context, deposit, null);
this.verboseDescription
.append("Loaded ingester: " + si.getClass().getName());
try
{
// first we delete the original bitstream
this.removeBitstream(swordContext, bitstream, items, authCredentials, swordConfig);
this.removeBitstream(swordContext, bitstream, items,
authCredentials, swordConfig);
DepositResult result = null;
boolean first = true;
@@ -834,7 +931,8 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
if (first)
{
// just do this to the first item
result = this.addContent(swordContext, item, deposit, authCredentials, swordConfig);
result = this.addContent(swordContext, item, deposit,
authCredentials, swordConfig);
}
else
{
@@ -842,12 +940,15 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
List<Bundle> bundles = item.getBundles();
if (!bundles.isEmpty())
{
bundleService.addBitstream(context, bundles.get(0), result.getOriginalDeposit());
bundleService.addBitstream(context, bundles.get(0),
result.getOriginalDeposit());
}
else
{
Bundle bundle = bundleService.create(context, item, Constants.CONTENT_BUNDLE_NAME);
bundleService.addBitstream(context, bundle, result.getOriginalDeposit());
Bundle bundle = bundleService.create(context, item,
Constants.CONTENT_BUNDLE_NAME);
bundleService.addBitstream(context, bundle,
result.getOriginalDeposit());
}
}
@@ -868,31 +969,40 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
}
}
private DepositResult addContent(SwordContext swordContext, Item item, Deposit deposit, AuthCredentials authCredentials, SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
private DepositResult addContent(SwordContext swordContext, Item item,
Deposit deposit, AuthCredentials authCredentials,
SwordConfigurationDSpace swordConfig)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
// get the things out of the service that we need
Context context = swordContext.getContext();
SwordUrlManager urlManager = swordConfig.getUrlManager(swordContext.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(swordContext.getContext(), swordConfig);
// is the content acceptable? If not, this will throw an error
this.isAcceptable(swordConfig, context, deposit, item);
// Obtain the relevant ingester from the factory
SwordContentIngester si = SwordIngesterFactory.getContentInstance(context, deposit, null);
this.verboseDescription.append("Loaded ingester: " + si.getClass().getName());
SwordContentIngester si = SwordIngesterFactory
.getContentInstance(context, deposit, null);
this.verboseDescription
.append("Loaded ingester: " + si.getClass().getName());
// do the deposit
DepositResult result = si.ingest(context, deposit, item, this.verboseDescription);
DepositResult result = si
.ingest(context, deposit, item, this.verboseDescription);
this.verboseDescription.append("Add completed successfully");
// store the originals (this code deals with the possibility that that's not required)
this.storeOriginals(swordConfig, context, this.verboseDescription, deposit, result);
this.storeOriginals(swordConfig, context, this.verboseDescription,
deposit, result);
return result;
}
private Item getDSpaceTarget(Context context, String editMediaUrl, SwordConfigurationDSpace config)
private Item getDSpaceTarget(Context context, String editMediaUrl,
SwordConfigurationDSpace config)
throws DSpaceSwordException, SwordError
{
SwordUrlManager urlManager = config.getUrlManager(context, config);
@@ -900,8 +1010,12 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
// get the target collection
Item item = urlManager.getItem(context, editMediaUrl);
this.verboseDescription.append("Performing replace using edit-media URL: " + editMediaUrl);
this.verboseDescription.append("Location resolves to item with handle: " + item.getHandle());
this.verboseDescription
.append("Performing replace using edit-media URL: " +
editMediaUrl);
this.verboseDescription
.append("Location resolves to item with handle: " +
item.getHandle());
return item;
}
@@ -919,9 +1033,13 @@ public class MediaResourceManagerDSpace extends DSpaceSwordAPI implements MediaR
{
oboEmail = sc.getOnBehalfOf().getEmail();
}
log.info(LogManager.getHeader(context, "replace_failed_authorisation", "user=" +
sc.getAuthenticated().getEmail() + ",on_behalf_of=" + oboEmail));
throw new SwordAuthException("Cannot replace the given item with this context");
log.info(LogManager
.getHeader(context, "replace_failed_authorisation",
"user=" +
sc.getAuthenticated().getEmail() +
",on_behalf_of=" + oboEmail));
throw new SwordAuthException(
"Cannot replace the given item with this context");
}
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -14,11 +14,14 @@ import org.swordapp.server.Statement;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
public class OreStatementDisseminator extends GenericStatementDisseminator implements SwordStatementDisseminator
public class OreStatementDisseminator extends GenericStatementDisseminator
implements SwordStatementDisseminator
{
public Statement disseminate(Context context, Item item) throws DSpaceSwordException, SwordError, SwordServerException
public Statement disseminate(Context context, Item item)
throws DSpaceSwordException, SwordError, SwordServerException
{
SwordUrlManager urlManager = new SwordUrlManager(new SwordConfigurationDSpace(), context);
SwordUrlManager urlManager = new SwordUrlManager(
new SwordConfigurationDSpace(), context);
String aggUrl = urlManager.getAggregationUrl(item);
String remUrl = urlManager.getOreStatementUri(item);
Statement s = new OREStatement(remUrl, aggUrl);

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -38,21 +38,25 @@ public class ReceiptGenerator
/** logger */
private static Logger log = Logger.getLogger(ReceiptGenerator.class);
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected DepositReceipt createFileReceipt(Context context, DepositResult result, SwordConfigurationDSpace config)
protected DepositReceipt createFileReceipt(Context context,
DepositResult result, SwordConfigurationDSpace config)
throws DSpaceSwordException, SwordError, SwordServerException
{
SwordUrlManager urlManager = config.getUrlManager(context, config);
DepositReceipt receipt = new DepositReceipt();
receipt.setLocation(new IRI(urlManager.getActionableBitstreamUrl(result.getOriginalDeposit())));
receipt.setLocation(new IRI(urlManager
.getActionableBitstreamUrl(result.getOriginalDeposit())));
receipt.setEmpty(true);
return receipt;
}
protected DepositReceipt createMediaResourceReceipt(Context context, Item item, SwordConfigurationDSpace config)
protected DepositReceipt createMediaResourceReceipt(Context context,
Item item, SwordConfigurationDSpace config)
throws DSpaceSwordException, SwordError, SwordServerException
{
SwordUrlManager urlManager = config.getUrlManager(context, config);
@@ -61,7 +65,8 @@ public class ReceiptGenerator
return receipt;
}
protected DepositReceipt createReceipt(Context context, DepositResult result, SwordConfigurationDSpace config)
protected DepositReceipt createReceipt(Context context,
DepositResult result, SwordConfigurationDSpace config)
throws DSpaceSwordException, SwordError, SwordServerException
{
return this.createReceipt(context, result, config, false);
@@ -72,20 +77,26 @@ public class ReceiptGenerator
*
* @throws DSpaceSwordException
*/
protected DepositReceipt createReceipt(Context context, DepositResult result, SwordConfigurationDSpace config, boolean mediaResourceLocation)
protected DepositReceipt createReceipt(Context context,
DepositResult result, SwordConfigurationDSpace config,
boolean mediaResourceLocation)
throws DSpaceSwordException, SwordError, SwordServerException
{
SwordUrlManager urlManager = config.getUrlManager(context, config);
DepositReceipt receipt = new DepositReceipt();
receipt.setAtomStatementURI(urlManager.getAtomStatementUri(result.getItem()));
receipt.setOREStatementURI(urlManager.getOreStatementUri(result.getItem()));
receipt.setAtomStatementURI(
urlManager.getAtomStatementUri(result.getItem()));
receipt.setOREStatementURI(
urlManager.getOreStatementUri(result.getItem()));
receipt.setEditIRI(urlManager.getEditIRI(result.getItem()));
receipt.setSplashUri(urlManager.getSplashUrl(result.getItem()));
receipt.setSwordEditIRI(urlManager.getEditIRI(result.getItem()));
receipt.setTreatment(result.getTreatment());
receipt.setContent(urlManager.getContentUrl(result.getItem()), "application/zip");
receipt.addEditMediaIRI(urlManager.getContentUrl(result.getItem()), "application/zip");
receipt.setContent(urlManager.getContentUrl(result.getItem()),
"application/zip");
receipt.addEditMediaIRI(urlManager.getContentUrl(result.getItem()),
"application/zip");
receipt.setMediaFeedIRI(urlManager.getMediaFeedUrl(result.getItem()));
receipt.setLastModified(result.getItem().getLastModified());
@@ -104,15 +115,20 @@ public class ReceiptGenerator
if (od != null)
{
// note here that we don't provide an actionable url
receipt.setOriginalDeposit(urlManager.getActionableBitstreamUrl(od), od.getFormat(context).getMIMEType());
receipt.setOriginalDeposit(
urlManager.getActionableBitstreamUrl(od),
od.getFormat(context).getMIMEType());
}
Map<String, String> derived = new HashMap<String, String>();
List<Bitstream> drs = result.getDerivedResources();
if (drs != null) {
for (Bitstream bs : result.getDerivedResources()) {
if (drs != null)
{
for (Bitstream bs : result.getDerivedResources())
{
// here we provide actionable urls for the parts of the resource
derived.put(urlManager.getActionableBitstreamUrl(bs), bs.getFormat(context).getMIMEType());
derived.put(urlManager.getActionableBitstreamUrl(bs),
bs.getFormat(context).getMIMEType());
}
}
receipt.setDerivedResources(derived);
@@ -129,18 +145,21 @@ public class ReceiptGenerator
this.addPublishDate(result, receipt);
// add the item's metadata
SwordEntryDisseminator disseminator = SwordDisseminatorFactory.getEntryInstance();
SwordEntryDisseminator disseminator = SwordDisseminatorFactory
.getEntryInstance();
disseminator.disseminate(context, result.getItem(), receipt);
StringBuilder rightsString = new StringBuilder();
List<Bundle> bundles = result.getItem().getBundles();
for (Bundle bundle : bundles) {
for (Bundle bundle : bundles)
{
if (!Constants.LICENSE_BUNDLE_NAME.equals(bundle.getName()))
{
continue;
}
List<BundleBitstream> bss = bundle.getBitstreams();
for (BundleBitstream bs : bss) {
for (BundleBitstream bs : bss)
{
String url = urlManager.getBitstreamUrl(bs.getBitstream());
rightsString.append(url).append(" ");
}
@@ -161,7 +180,8 @@ public class ReceiptGenerator
*
* @throws DSpaceSwordException
*/
protected DepositReceipt createReceipt(Context context, Item item, SwordConfigurationDSpace config)
protected DepositReceipt createReceipt(Context context, Item item,
SwordConfigurationDSpace config)
throws DSpaceSwordException, SwordError, SwordServerException
{
SwordUrlManager urlManager = config.getUrlManager(context, config);
@@ -174,7 +194,8 @@ public class ReceiptGenerator
receipt.setSplashUri(urlManager.getSplashUrl(item));
receipt.setSwordEditIRI(urlManager.getEditIRI(item));
receipt.setContent(urlManager.getContentUrl(item), "application/zip");
receipt.addEditMediaIRI(urlManager.getContentUrl(item), "application/zip");
receipt.addEditMediaIRI(urlManager.getContentUrl(item),
"application/zip");
receipt.setMediaFeedIRI(urlManager.getMediaFeedUrl(item));
receipt.setLastModified(item.getLastModified());
@@ -185,18 +206,21 @@ public class ReceiptGenerator
this.addPublishDate(item, receipt);
// add the item's metadata
SwordEntryDisseminator disseminator = SwordDisseminatorFactory.getEntryInstance();
SwordEntryDisseminator disseminator = SwordDisseminatorFactory
.getEntryInstance();
disseminator.disseminate(context, item, receipt);
StringBuilder rightsString = new StringBuilder();
List<Bundle> bundles = item.getBundles();
for (Bundle bundle : bundles) {
for (Bundle bundle : bundles)
{
if (!Constants.LICENSE_BUNDLE_NAME.equals(bundle.getName()))
{
continue;
}
List<BundleBitstream> bss = bundle.getBitstreams();
for (BundleBitstream bs : bss) {
for (BundleBitstream bs : bss)
{
String url = urlManager.getBitstreamUrl(bs.getBitstream());
rightsString.append(url).append(" ");
}
@@ -219,22 +243,30 @@ public class ReceiptGenerator
*/
protected void addCategories(DepositResult result, DepositReceipt receipt)
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(result.getItem(), "dc.subject.*");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(result.getItem(), "dc.subject.*");
if (dcv != null)
{
for (MetadataValue aDcv : dcv) {
receipt.getWrappedEntry().addCategory(UriRegistry.DC_NAMESPACE, aDcv.getValue(), aDcv.getValue());
for (MetadataValue aDcv : dcv)
{
receipt.getWrappedEntry()
.addCategory(UriRegistry.DC_NAMESPACE, aDcv.getValue(),
aDcv.getValue());
}
}
}
protected void addCategories(Item item, DepositReceipt receipt)
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, "dc.subject.*");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.subject.*");
if (dcv != null)
{
for (MetadataValue aDcv : dcv) {
receipt.getWrappedEntry().addCategory(UriRegistry.DC_NAMESPACE, aDcv.getValue(), aDcv.getValue());
for (MetadataValue aDcv : dcv)
{
receipt.getWrappedEntry()
.addCategory(UriRegistry.DC_NAMESPACE, aDcv.getValue(),
aDcv.getValue());
}
}
}
@@ -245,7 +277,9 @@ public class ReceiptGenerator
*/
protected void addPublishDate(DepositResult result, DepositReceipt receipt)
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(result.getItem(), "dc.date.issued");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(result.getItem(),
"dc.date.issued");
if (dcv != null && !dcv.isEmpty())
{
try
@@ -264,7 +298,8 @@ public class ReceiptGenerator
protected void addPublishDate(Item item, DepositReceipt receipt)
{
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, "dc.date.issued");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, "dc.date.issued");
if (dcv != null && dcv.size() == 1)
{
try
@@ -285,10 +320,13 @@ public class ReceiptGenerator
* Add the date that this item was last updated
*
*/
protected void addLastUpdatedDate(DepositResult result, DepositReceipt receipt)
protected void addLastUpdatedDate(DepositResult result,
DepositReceipt receipt)
{
String config = ConfigurationManager.getProperty("swordv2-server", "updated.field");
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(result.getItem(), config);
String config = ConfigurationManager
.getProperty("swordv2-server", "updated.field");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(result.getItem(), config);
if (dcv != null && dcv.size() == 1)
{
try
@@ -307,8 +345,10 @@ public class ReceiptGenerator
protected void addLastUpdatedDate(Item item, DepositReceipt receipt)
{
String config = ConfigurationManager.getProperty("swordv2-server", "updated.field");
List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, config);
String config = ConfigurationManager
.getProperty("swordv2-server", "updated.field");
List<MetadataValue> dcv = itemService
.getMetadataByMetadataString(item, config);
if (dcv != null && dcv.size() == 1)
{
try

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -31,11 +31,14 @@ import java.util.List;
public class ServiceDocumentManagerDSpace implements ServiceDocumentManager
{
/** logger */
private static Logger log = Logger.getLogger(ServiceDocumentManagerDSpace.class);
private static Logger log = Logger
.getLogger(ServiceDocumentManagerDSpace.class);
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CommunityService communityService = ContentServiceFactory
.getInstance().getCommunityService();
public ServiceDocument getServiceDocument(String sdUri, AuthCredentials authCredentials, SwordConfiguration config)
public ServiceDocument getServiceDocument(String sdUri,
AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException, SwordAuthException
{
SwordContext sc = null;
@@ -53,20 +56,29 @@ public class ServiceDocumentManagerDSpace implements ServiceDocumentManager
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_do_service_document", ""));
log.debug(LogManager
.getHeader(context, "sword_do_service_document", ""));
}
// log the request
String un = authCredentials.getUsername() != null ? authCredentials.getUsername() : "NONE";
String obo = authCredentials.getOnBehalfOf() != null ? authCredentials.getOnBehalfOf() : "NONE";
log.info(LogManager.getHeader(context, "sword_service_document_request", "username=" + un + ",on_behalf_of=" + obo));
String un = authCredentials.getUsername() != null ?
authCredentials.getUsername() :
"NONE";
String obo = authCredentials.getOnBehalfOf() != null ?
authCredentials.getOnBehalfOf() :
"NONE";
log.info(LogManager
.getHeader(context, "sword_service_document_request",
"username=" + un + ",on_behalf_of=" + obo));
return this.getServiceDocument(sc, sdUri, (SwordConfigurationDSpace) config);
return this.getServiceDocument(sc, sdUri,
(SwordConfigurationDSpace) config);
}
catch (DSpaceSwordException e)
{
log.error("caught exception: ", e);
throw new SwordServerException("The DSpace SWORD interface experienced an error", e);
throw new SwordServerException(
"The DSpace SWORD interface experienced an error", e);
}
finally
{
@@ -78,21 +90,25 @@ public class ServiceDocumentManagerDSpace implements ServiceDocumentManager
}
}
public ServiceDocument getServiceDocument(SwordContext context, String url, SwordConfigurationDSpace swordConfig)
public ServiceDocument getServiceDocument(SwordContext context, String url,
SwordConfigurationDSpace swordConfig)
throws SwordError, SwordServerException, DSpaceSwordException
{
// first check that the sword context have
// been set
if (context == null)
{
throw new DSpaceSwordException("The Sword Context is null; please set it before calling getServiceDocument");
throw new DSpaceSwordException(
"The Sword Context is null; please set it before calling getServiceDocument");
}
// ensure that this method is allowed
WorkflowManagerFactory.getInstance().retrieveServiceDoc(context.getContext());
WorkflowManagerFactory.getInstance()
.retrieveServiceDoc(context.getContext());
// get the URL manager
SwordUrlManager urlManager = swordConfig.getUrlManager(context.getContext(), swordConfig);
SwordUrlManager urlManager = swordConfig
.getUrlManager(context.getContext(), swordConfig);
// we'll need the authenticator
SwordAuthenticator swordAuth = new SwordAuthenticator();
@@ -117,23 +133,30 @@ public class ServiceDocumentManagerDSpace implements ServiceDocumentManager
workspace.setTitle(ws);
// next thing to do is determine whether the default is communities or collections
boolean swordCommunities = ConfigurationManager.getBooleanProperty("swordv2-server", "expose-communities");
boolean swordCommunities = ConfigurationManager
.getBooleanProperty("swordv2-server", "expose-communities");
if (swordCommunities)
{
List<Community> comms = swordAuth.getAllowedCommunities(context);
List<Community> comms = swordAuth
.getAllowedCommunities(context);
for (Community comm : comms)
{
SwordCollection scol = comGen.buildCollection(context.getContext(), comm, swordConfig);
SwordCollection scol = comGen
.buildCollection(context.getContext(), comm,
swordConfig);
workspace.addCollection(scol);
}
}
else
{
List<Collection> cols = swordAuth.getAllowedCollections(context);
List<Collection> cols = swordAuth
.getAllowedCollections(context);
for (Collection col : cols)
{
SwordCollection scol = colGen.buildCollection(context.getContext(), col, swordConfig);
SwordCollection scol = colGen
.buildCollection(context.getContext(), col,
swordConfig);
workspace.addCollection(scol);
}
}
@@ -155,17 +178,23 @@ public class ServiceDocumentManagerDSpace implements ServiceDocumentManager
SwordWorkspace workspace = new SwordWorkspace();
workspace.setTitle(communityService.getName(community));
List<Collection> collections = swordAuth.getAllowedCollections(context, community);
List<Collection> collections = swordAuth
.getAllowedCollections(context, community);
for (Collection collection : collections)
{
SwordCollection scol = colGen.buildCollection(context.getContext(), collection, swordConfig);
SwordCollection scol = colGen
.buildCollection(context.getContext(), collection,
swordConfig);
workspace.addCollection(scol);
}
List<Community> communities = swordAuth.getCommunities(context, community);
List<Community> communities = swordAuth
.getCommunities(context, community);
for (Community comm : communities)
{
SwordCollection scol = comGen.buildCollection(context.getContext(), comm, swordConfig);
SwordCollection scol = comGen
.buildCollection(context.getContext(), comm,
swordConfig);
workspace.addCollection(scol);
}
@@ -176,5 +205,4 @@ public class ServiceDocumentManagerDSpace implements ServiceDocumentManager
return service;
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -15,11 +15,15 @@ import org.swordapp.server.SwordServerException;
import java.util.Map;
public class SimpleDCEntryDisseminator extends AbstractSimpleDC implements SwordEntryDisseminator
public class SimpleDCEntryDisseminator extends AbstractSimpleDC
implements SwordEntryDisseminator
{
public SimpleDCEntryDisseminator() { }
public SimpleDCEntryDisseminator()
{
}
public DepositReceipt disseminate(Context context, Item item, DepositReceipt receipt)
public DepositReceipt disseminate(Context context, Item item,
DepositReceipt receipt)
throws DSpaceSwordException, SwordError, SwordServerException
{
SimpleDCMetadata md = this.getMetadata(item);

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -23,40 +23,56 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntryIngester
public class SimpleDCEntryIngester extends AbstractSimpleDC
implements SwordEntryIngester
{
private static final Logger log = Logger.getLogger(SimpleDCEntryIngester.class);
private static final Logger log = Logger
.getLogger(SimpleDCEntryIngester.class);
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory
.getInstance().getWorkspaceItemService();
public SimpleDCEntryIngester()
{
this.loadMetadataMaps();
}
public DepositResult ingest(Context context, Deposit deposit, DSpaceObject dso, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingest(Context context, Deposit deposit,
DSpaceObject dso, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
return this.ingest(context, deposit, dso, verboseDescription, null, false);
return this
.ingest(context, deposit, dso, verboseDescription, null, false);
}
public DepositResult ingest(Context context, Deposit deposit, DSpaceObject dso, VerboseDescription verboseDescription, DepositResult result, boolean replace)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingest(Context context, Deposit deposit,
DSpaceObject dso, VerboseDescription verboseDescription,
DepositResult result, boolean replace)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
if (dso instanceof Collection)
{
return this.ingestToCollection(context, deposit, (Collection) dso, verboseDescription, result);
return this.ingestToCollection(context, deposit, (Collection) dso,
verboseDescription, result);
}
else if (dso instanceof Item)
{
return this.ingestToItem(context, deposit, (Item) dso, verboseDescription, result, replace);
return this.ingestToItem(context, deposit, (Item) dso,
verboseDescription, result, replace);
}
return null;
}
public DepositResult ingestToItem(Context context, Deposit deposit, Item item, VerboseDescription verboseDescription, DepositResult result, boolean replace)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingestToItem(Context context, Deposit deposit,
Item item, VerboseDescription verboseDescription,
DepositResult result, boolean replace)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
try
{
@@ -103,21 +119,30 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
private void removeMetadata(Context context, Item item)
throws DSpaceSwordException
{
String raw = ConfigurationManager.getProperty("swordv2-server", "metadata.replaceable");
String raw = ConfigurationManager
.getProperty("swordv2-server", "metadata.replaceable");
String[] parts = raw.split(",");
for (String part : parts)
{
MetadataValueInfo info = this.makeMetadataValueInfo(part.trim(), null);
try {
itemService.clearMetadata(context, item, info.schema, info.element, info.qualifier, Item.ANY);
} catch (SQLException e) {
MetadataValueInfo info = this
.makeMetadataValueInfo(part.trim(), null);
try
{
itemService
.clearMetadata(context, item, info.schema, info.element,
info.qualifier, Item.ANY);
}
catch (SQLException e)
{
log.error("Caught exception trying to remove metadata", e);
throw new DSpaceSwordException(e);
}
}
}
private void addUniqueMetadata(Context context, MetadataValueInfo info, Item item) throws SQLException {
private void addUniqueMetadata(Context context, MetadataValueInfo info,
Item item) throws SQLException
{
String qual = info.qualifier;
if (info.qualifier == null)
{
@@ -129,7 +154,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
{
lang = Item.ANY;
}
List<MetadataValue> existing = itemService.getMetadata(item, info.schema, info.element, qual, lang);
List<MetadataValue> existing = itemService
.getMetadata(item, info.schema, info.element, qual, lang);
for (MetadataValue dcValue : existing)
{
// FIXME: probably we want to be slightly more careful about qualifiers and languages
@@ -142,7 +168,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
}
// if we get to here, go on and add the metadata
itemService.addMetadata(context, item, info.schema, info.element, info.qualifier, info.language, info.value);
itemService.addMetadata(context, item, info.schema, info.element,
info.qualifier, info.language, info.value);
}
private void addMetadataToItem(Context context, Deposit deposit, Item item)
@@ -159,10 +186,14 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
String titleField = this.dcMap.get("title");
if (titleField != null)
{
MetadataValueInfo info = this.makeMetadataValueInfo(titleField, title);
try {
MetadataValueInfo info = this
.makeMetadataValueInfo(titleField, title);
try
{
this.addUniqueMetadata(context, info, item);
} catch (SQLException e) {
}
catch (SQLException e)
{
log.error("Caught exception trying to add title", e);
throw new DSpaceSwordException(e);
}
@@ -173,10 +204,14 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
String abstractField = this.dcMap.get("abstract");
if (abstractField != null)
{
MetadataValueInfo info = this.makeMetadataValueInfo(abstractField, summary);
try {
MetadataValueInfo info = this
.makeMetadataValueInfo(abstractField, summary);
try
{
this.addUniqueMetadata(context, info, item);
} catch (SQLException e) {
}
catch (SQLException e)
{
log.error("Caught exception trying to set abstract", e);
throw new DSpaceSwordException(e);
}
@@ -198,9 +233,12 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
for (String value : dc.get(term))
{
info.value = value;
try {
try
{
this.addUniqueMetadata(context, info, item);
} catch (SQLException e) {
}
catch (SQLException e)
{
log.error("Caught exception trying to add metadata", e);
throw new DSpaceSwordException(e);
}
@@ -208,8 +246,11 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
}
}
public DepositResult ingestToCollection(Context context, Deposit deposit, Collection collection, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingestToCollection(Context context, Deposit deposit,
Collection collection, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
try
{
@@ -251,7 +292,9 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
context.restoreAuthSystemState();
verboseDescription.append("Ingest successful");
verboseDescription.append("Item created with internal identifier: " + item.getID());
verboseDescription
.append("Item created with internal identifier: " +
item.getID());
result.setItem(item);
result.setTreatment(this.getTreatment());
@@ -297,26 +340,35 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
* @param item
* @throws DSpaceSwordException
*/
protected void setUpdatedDate(Context context, Item item, VerboseDescription verboseDescription)
protected void setUpdatedDate(Context context, Item item,
VerboseDescription verboseDescription)
throws DSpaceSwordException
{
String field = ConfigurationManager.getProperty("swordv2-server", "updated.field");
String field = ConfigurationManager
.getProperty("swordv2-server", "updated.field");
if (field == null || "".equals(field))
{
throw new DSpaceSwordException("No configuration, or configuration is invalid for: sword.updated.field");
throw new DSpaceSwordException(
"No configuration, or configuration is invalid for: sword.updated.field");
}
MetadataValueInfo info = this.makeMetadataValueInfo(field, null);
try {
itemService.clearMetadata(context, item, info.schema, info.element, info.qualifier, Item.ANY);
try
{
itemService.clearMetadata(context, item, info.schema, info.element,
info.qualifier, Item.ANY);
DCDate date = new DCDate(new Date());
itemService.addMetadata(context, item, info.schema, info.element, info.qualifier, null, date.toString());
} catch (SQLException e) {
itemService.addMetadata(context, item, info.schema, info.element,
info.qualifier, null, date.toString());
}
catch (SQLException e)
{
log.error("Exception caught trying to set updated date", e);
throw new DSpaceSwordException(e);
}
verboseDescription.append("Updated date added to response from item metadata where available");
verboseDescription
.append("Updated date added to response from item metadata where available");
}
/**
@@ -331,7 +383,8 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
* @param slugVal
* @throws DSpaceSwordException
*/
protected void setSlug(Context context, Item item, String slugVal, VerboseDescription verboseDescription)
protected void setSlug(Context context, Item item, String slugVal,
VerboseDescription verboseDescription)
throws DSpaceSwordException
{
// if there isn't a slug value, don't set it
@@ -340,17 +393,24 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
return;
}
String field = ConfigurationManager.getProperty("swordv2-server", "slug.field");
String field = ConfigurationManager
.getProperty("swordv2-server", "slug.field");
if (field == null || "".equals(field))
{
throw new DSpaceSwordException("No configuration, or configuration is invalid for: sword.slug.field");
throw new DSpaceSwordException(
"No configuration, or configuration is invalid for: sword.slug.field");
}
MetadataValueInfo info = this.makeMetadataValueInfo(field, null);
try {
itemService.clearMetadata(context, item, info.schema, info.element, info.qualifier, Item.ANY);
itemService.addMetadata(context, item, info.schema, info.element, info.qualifier, null, slugVal);
} catch (SQLException e) {
try
{
itemService.clearMetadata(context, item, info.schema, info.element,
info.qualifier, Item.ANY);
itemService.addMetadata(context, item, info.schema, info.element,
info.qualifier, null, slugVal);
}
catch (SQLException e)
{
log.error("Caught exception trying to set slug", e);
throw new DSpaceSwordException(e);
}
@@ -370,11 +430,16 @@ public class SimpleDCEntryIngester extends AbstractSimpleDC implements SwordEntr
return "A metadata only item has been created";
}
private class MetadataValueInfo {
private class MetadataValueInfo
{
private String schema;
private String element;
private String qualifier;
private String language;
private String value;
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
@@ -14,6 +14,7 @@ import java.util.Map;
public class SimpleDCMetadata
{
private Map<String, String> dublinCore = new HashMap<String, String>();
private Map<String, String> atom = new HashMap<String, String>();
public void addDublinCore(String element, String value)

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -35,7 +35,8 @@ import java.util.zip.ZipOutputStream;
public class SimpleZipContentDisseminator implements SwordContentDisseminator
{
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
public InputStream disseminate(Context context, Item item)
throws DSpaceSwordException, SwordError, SwordServerException
@@ -43,8 +44,11 @@ public class SimpleZipContentDisseminator implements SwordContentDisseminator
try
{
// first write everything to a temp file
String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString() + ".zip";
String tempDir = ConfigurationManager
.getProperty("upload.temp.dir");
String fn =
tempDir + File.separator + "SWORD." + item.getID() + "." +
UUID.randomUUID().toString() + ".zip";
OutputStream outStream = new FileOutputStream(new File(fn));
ZipOutputStream zip = new ZipOutputStream(outStream);
@@ -54,11 +58,13 @@ public class SimpleZipContentDisseminator implements SwordContentDisseminator
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
{
List<BundleBitstream> bss = bundle.getBitstreams();
for (BundleBitstream bundleBitstream : bss) {
for (BundleBitstream bundleBitstream : bss)
{
Bitstream bitstream = bundleBitstream.getBitstream();
ZipEntry ze = new ZipEntry(bitstream.getName());
zip.putNextEntry(ze);
InputStream is = bitstreamService.retrieve(context, bitstream);
InputStream is = bitstreamService
.retrieve(context, bitstream);
Utils.copy(is, zip);
zip.closeEntry();
is.close();

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -36,13 +36,24 @@ import java.util.zip.ZipFile;
public class SimpleZipContentIngester extends AbstractSwordContentIngester
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
public DepositResult ingestToCollection(Context context, Deposit deposit, Collection collection, VerboseDescription verboseDescription, DepositResult result)
protected BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory
.getInstance().getWorkspaceItemService();
public DepositResult ingestToCollection(Context context, Deposit deposit,
Collection collection, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException
{
try
@@ -71,7 +82,8 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester
// get the original bundle
List<Bundle> bundles = item.getBundles();
Bundle original = null;
for (Bundle bundle : bundles) {
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
{
original = bundle;
@@ -80,16 +92,21 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester
}
if (original == null)
{
original = bundleService.create(context, item, Constants.CONTENT_BUNDLE_NAME);
original = bundleService
.create(context, item, Constants.CONTENT_BUNDLE_NAME);
}
// unzip the file into the bundle
List<Bitstream> derivedResources = this.unzipToBundle(context, depositFile, original);
List<Bitstream> derivedResources = this
.unzipToBundle(context, depositFile, original);
// now we have an item in the workspace, and we need to consider adding some metadata to it,
// but since the zip file didn't contain anything, what do we do?
itemService.addMetadata(context, item, "dc", "title", null, null, "Untitled: " + deposit.getFilename());
itemService.addMetadata(context, item, "dc", "description", null, null, "Zip file deposted by SWORD without accompanying metadata");
itemService.addMetadata(context, item, "dc", "title", null, null,
"Untitled: " + deposit.getFilename());
itemService
.addMetadata(context, item, "dc", "description", null, null,
"Zip file deposted by SWORD without accompanying metadata");
// update the item metadata to inclue the current time as
// the updated date
@@ -108,7 +125,9 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester
context.restoreAuthSystemState();
verboseDescription.append("Ingest successful");
verboseDescription.append("Item created with internal identifier: " + item.getID());
verboseDescription
.append("Item created with internal identifier: " +
item.getID());
result.setItem(item);
result.setTreatment(this.getTreatment());
@@ -126,7 +145,8 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester
}
}
private List<Bitstream> unzipToBundle(Context context, File depositFile, Bundle target)
private List<Bitstream> unzipToBundle(Context context, File depositFile,
Bundle target)
throws DSpaceSwordException, SwordError, SwordAuthException
{
try
@@ -141,7 +161,8 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester
ZipEntry entry = (ZipEntry) zenum.nextElement();
InputStream stream = zip.getInputStream(entry);
Bitstream bs = bitstreamService.create(context, target, stream);
BitstreamFormat format = this.getFormat(context, entry.getName());
BitstreamFormat format = this
.getFormat(context, entry.getName());
bs.setFormat(context, format);
bs.setName(context, entry.getName());
bitstreamService.update(context, bs);
@@ -152,18 +173,22 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester
}
catch (ZipException e)
{
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "unable to unzip provided package", e);
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST,
"unable to unzip provided package", e);
}
catch (IOException | SQLException e)
{
throw new DSpaceSwordException(e);
} catch (AuthorizeException e)
}
catch (AuthorizeException e)
{
throw new SwordAuthException(e);
}
}
public DepositResult ingestToItem(Context context, Deposit deposit, Item item, VerboseDescription verboseDescription, DepositResult result)
public DepositResult ingestToItem(Context context, Deposit deposit,
Item item, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException
{
try
@@ -190,11 +215,13 @@ public class SimpleZipContentIngester extends AbstractSwordContentIngester
}
if (original == null)
{
original = bundleService.create(context, item, Constants.CONTENT_BUNDLE_NAME);
original = bundleService
.create(context, item, Constants.CONTENT_BUNDLE_NAME);
}
// we are now free to go and unpack the new zip into the original bundle
List<Bitstream> derivedResources = this.unzipToBundle(context, depositFile, original);
List<Bitstream> derivedResources = this
.unzipToBundle(context, depositFile, original);
// update the item metadata to inclue the current time as
// the updated date

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -31,13 +31,16 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class StatementManagerDSpace extends DSpaceSwordAPI implements StatementManager
public class StatementManagerDSpace extends DSpaceSwordAPI
implements StatementManager
{
private static Logger log = Logger.getLogger(StatementManagerDSpace.class);
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory
.getInstance().getAuthorizeService();
public Statement getStatement(String stateIRI, Map<String, String> accept, AuthCredentials authCredentials, SwordConfiguration swordConfig)
public Statement getStatement(String stateIRI, Map<String, String> accept,
AuthCredentials authCredentials, SwordConfiguration swordConfig)
throws SwordServerException, SwordError, SwordAuthException
{
SwordContext sc = null;
@@ -51,13 +54,19 @@ public class StatementManagerDSpace extends DSpaceSwordAPI implements StatementM
if (log.isDebugEnabled())
{
log.debug(LogManager.getHeader(context, "sword_get_statement", ""));
log.debug(LogManager
.getHeader(context, "sword_get_statement", ""));
}
// log the request
String un = authCredentials.getUsername() != null ? authCredentials.getUsername() : "NONE";
String obo = authCredentials.getOnBehalfOf() != null ? authCredentials.getOnBehalfOf() : "NONE";
log.info(LogManager.getHeader(context, "sword_get_statement", "username=" + un + ",on_behalf_of=" + obo));
String un = authCredentials.getUsername() != null ?
authCredentials.getUsername() :
"NONE";
String obo = authCredentials.getOnBehalfOf() != null ?
authCredentials.getOnBehalfOf() :
"NONE";
log.info(LogManager.getHeader(context, "sword_get_statement",
"username=" + un + ",on_behalf_of=" + obo));
// first thing is to figure out what we're being asked to work on
SwordUrlManager urlManager = config.getUrlManager(context, config);
@@ -71,7 +80,8 @@ public class StatementManagerDSpace extends DSpaceSwordAPI implements StatementM
authorizeService.authorizeAction(context, item, Constants.READ);
// find out, now we know what we're being asked for, whether this is allowed
WorkflowManagerFactory.getInstance().retrieveStatement(context, item);
WorkflowManagerFactory.getInstance()
.retrieveStatement(context, item);
String suffix = urlManager.getTypeSuffix(context, stateIRI);
SwordStatementDisseminator disseminator = null;
@@ -82,18 +92,22 @@ public class StatementManagerDSpace extends DSpaceSwordAPI implements StatementM
List<String> list = new ArrayList<>();
list.add(suffix);
analysed.put((float) 1.0, list);
disseminator = SwordDisseminatorFactory.getStatementInstance(analysed);
disseminator = SwordDisseminatorFactory
.getStatementInstance(analysed);
}
else
{
// we rely on the content negotiation to do the work
String acceptContentType = this.getHeader(accept, "Accept", null);
String acceptContentType = this
.getHeader(accept, "Accept", null);
// we extract from the Accept header the ordered list of content types
TreeMap<Float, List<String>> analysed = this.analyseAccept(acceptContentType);
TreeMap<Float, List<String>> analysed = this
.analyseAccept(acceptContentType);
// the meat of this is done by the package disseminator
disseminator = SwordDisseminatorFactory.getStatementInstance(analysed);
disseminator = SwordDisseminatorFactory
.getStatementInstance(analysed);
}
return disseminator.disseminate(context, item);
@@ -105,7 +119,8 @@ public class StatementManagerDSpace extends DSpaceSwordAPI implements StatementM
catch (SQLException | DSpaceSwordException e)
{
throw new SwordServerException(e);
} finally
}
finally
{
if (sc != null)
{

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -51,12 +51,23 @@ public class SwordAuthenticator
/** logger */
private static Logger log = Logger.getLogger(SwordAuthenticator.class);
protected AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService();
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected AuthenticationService authenticationService = AuthenticateServiceFactory
.getInstance().getAuthenticationService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory
.getInstance().getAuthorizeService();
protected EPersonService ePersonService = EPersonServiceFactory
.getInstance().getEPersonService();
protected CommunityService communityService = ContentServiceFactory
.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
/**
* Does the given username and password authenticate for the
@@ -69,7 +80,8 @@ public class SwordAuthenticator
*/
public boolean authenticates(Context context, String un, String pw)
{
int auth = authenticationService.authenticate(context, un, pw, null, null);
int auth = authenticationService
.authenticate(context, un, pw, null, null);
return auth == AuthenticationMethod.SUCCESS;
}
@@ -149,15 +161,19 @@ public class SwordAuthenticator
}
// first find out if we support on-behalf-of deposit
boolean mediated = ConfigurationManager.getBooleanProperty("swordv2-server", "on-behalf-of.enable");
boolean mediated = ConfigurationManager
.getBooleanProperty("swordv2-server", "on-behalf-of.enable");
if (!mediated && obo != null)
{
// user is trying to do a mediated deposit on a repository which does not support it
log.error("Attempted mediated deposit on service not configured to do so");
throw new SwordError(UriRegistry.ERROR_MEDIATION_NOT_ALLOWED, "Mediated deposit to this service is not permitted");
log.error(
"Attempted mediated deposit on service not configured to do so");
throw new SwordError(UriRegistry.ERROR_MEDIATION_NOT_ALLOWED,
"Mediated deposit to this service is not permitted");
}
log.info(LogManager.getHeader(context, "sword_authenticate", "username=" + un + ",on_behalf_of=" + obo));
log.info(LogManager.getHeader(context, "sword_authenticate",
"username=" + un + ",on_behalf_of=" + obo));
try
{
@@ -175,11 +191,14 @@ public class SwordAuthenticator
authenticated = true;
sc.setAuthenticated(ep);
// Set any special groups - invoke the authentication mgr.
List<Group> specialGroups = authenticationService.getSpecialGroups(context, null);
List<Group> specialGroups = authenticationService
.getSpecialGroups(context, null);
for (Group specialGroup : specialGroups) {
for (Group specialGroup : specialGroups)
{
context.setSpecialGroup(specialGroup.getID());
log.debug("Adding Special Group id=" + specialGroup.getID());
log.debug("Adding Special Group id=" +
specialGroup.getID());
}
sc.setAuthenticatorContext(context);
@@ -204,18 +223,23 @@ public class SwordAuthenticator
Context oboContext = this.constructContext();
oboContext.setCurrentUser(epObo);
// Set any special groups - invoke the authentication mgr.
List<Group> specialGroups = authenticationService.getSpecialGroups(oboContext, null);
List<Group> specialGroups = authenticationService
.getSpecialGroups(oboContext, null);
for (Group specialGroup : specialGroups) {
for (Group specialGroup : specialGroups)
{
oboContext.setSpecialGroup(specialGroup.getID());
log.debug("Adding Special Group id=" + specialGroup.getID());
log.debug("Adding Special Group id=" +
specialGroup.getID());
}
sc.setContext(oboContext);
}
else
{
authenticated = false;
throw new SwordError(UriRegistry.ERROR_TARGET_OWNER_UNKNOWN, "unable to identify on-behalf-of user: " + obo);
throw new SwordError(
UriRegistry.ERROR_TARGET_OWNER_UNKNOWN,
"unable to identify on-behalf-of user: " + obo);
}
}
}
@@ -225,15 +249,21 @@ public class SwordAuthenticator
// decide what kind of error to throw
if (ep != null)
{
log.info(LogManager.getHeader(context, "sword_unable_to_set_user", "username=" + un));
throw new SwordAuthException("Unable to authenticate with the supplied credentials");
log.info(LogManager
.getHeader(context, "sword_unable_to_set_user",
"username=" + un));
throw new SwordAuthException(
"Unable to authenticate with the supplied credentials");
}
else
{
// FIXME: this shouldn't ever happen now, but may as well leave it in just in case
// there's a bug elsewhere
log.info(LogManager.getHeader(context, "sword_unable_to_set_on_behalf_of", "username=" + un + ",on_behalf_of=" + obo));
throw new SwordAuthException("Unable to authenticate the onBehalfOf account");
log.info(LogManager.getHeader(context,
"sword_unable_to_set_on_behalf_of",
"username=" + un + ",on_behalf_of=" + obo));
throw new SwordAuthException(
"Unable to authenticate the onBehalfOf account");
}
}
@@ -242,7 +272,9 @@ public class SwordAuthenticator
catch (SQLException e)
{
log.error("caught exception: ", e);
throw new DSpaceSwordException("There was a problem accessing the repository user database", e);
throw new DSpaceSwordException(
"There was a problem accessing the repository user database",
e);
}
}
@@ -256,7 +288,8 @@ public class SwordAuthenticator
* @return true if yes, false if not
* @throws DSpaceSwordException
*/
public boolean canSubmit(SwordContext swordContext, DSpaceObject dso, VerboseDescription msg)
public boolean canSubmit(SwordContext swordContext, DSpaceObject dso,
VerboseDescription msg)
throws DSpaceSwordException, SwordError
{
// determine if we can submit
@@ -291,7 +324,8 @@ public class SwordAuthenticator
EPerson authenticated = swordContext.getAuthenticated();
if (authenticated != null)
{
return authorizeService.isAdmin(swordContext.getAuthenticatorContext());
return authorizeService
.isAdmin(swordContext.getAuthenticatorContext());
}
return false;
}
@@ -319,7 +353,8 @@ public class SwordAuthenticator
{
if (onBehalfOf != null)
{
return authorizeService.isAdmin(swordContext.getOnBehalfOfContext());
return authorizeService
.isAdmin(swordContext.getOnBehalfOfContext());
}
return false;
}
@@ -378,8 +413,10 @@ public class SwordAuthenticator
List<Group> groups = group.getMemberGroups();
// is the user in the current group
for (EPerson ep : eps) {
if (eperson.getID().equals(ep.getID())) {
for (EPerson ep : eps)
{
if (eperson.getID().equals(ep.getID()))
{
return true;
}
}
@@ -387,8 +424,10 @@ public class SwordAuthenticator
// is the eperson in the sub-groups (recurse)
if (groups != null && !groups.isEmpty())
{
for (Group group1 : groups) {
if (isInGroup(group1, eperson)) {
for (Group group1 : groups)
{
if (isInGroup(group1, eperson))
{
return true;
}
}
@@ -454,14 +493,18 @@ public class SwordAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), comm, Constants.READ);
authAllowed = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), comm,
Constants.READ);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), comm, Constants.READ);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), comm,
Constants.READ);
}
// final check to see if we are allowed to READ
@@ -501,7 +544,8 @@ public class SwordAuthenticator
* @return the array of allowed collections
* @throws DSpaceSwordException
*/
public List<Community> getCommunities(SwordContext swordContext, Community community)
public List<Community> getCommunities(SwordContext swordContext,
Community community)
throws DSpaceSwordException
{
// a community is allowed if the following conditions are met
@@ -534,14 +578,18 @@ public class SwordAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), comm, Constants.READ);
authAllowed = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), comm,
Constants.READ);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), comm, Constants.READ);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), comm,
Constants.READ);
}
// final check to see if we are allowed to READ
@@ -574,7 +622,8 @@ public class SwordAuthenticator
* @return the array of allowed collections
* @throws DSpaceSwordException
*/
public List<org.dspace.content.Collection> getAllowedCollections(SwordContext swordContext)
public List<org.dspace.content.Collection> getAllowedCollections(
SwordContext swordContext)
throws DSpaceSwordException
{
return this.getAllowedCollections(swordContext, null);
@@ -599,7 +648,8 @@ public class SwordAuthenticator
* @return the array of allowed collections
* @throws DSpaceSwordException
*/
public List<org.dspace.content.Collection> getAllowedCollections(SwordContext swordContext, Community community)
public List<org.dspace.content.Collection> getAllowedCollections(
SwordContext swordContext, Community community)
throws DSpaceSwordException
{
// a collection is allowed if the following conditions are met
@@ -619,7 +669,8 @@ public class SwordAuthenticator
Context authContext = swordContext.getAuthenticatorContext();
// short cut by obtaining the collections to which the authenticated user can submit
List<Collection> cols = collectionService.findAuthorized(authContext, community, Constants.ADD);
List<Collection> cols = collectionService
.findAuthorized(authContext, community, Constants.ADD);
List<org.dspace.content.Collection> allowed = new ArrayList<>();
// now find out if the obo user is allowed to submit to any of these collections
@@ -637,7 +688,9 @@ public class SwordAuthenticator
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), col, Constants.ADD);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), col,
Constants.ADD);
}
// final check to see if we are allowed to READ
@@ -675,7 +728,8 @@ public class SwordAuthenticator
* @return the array of allowed collections
* @throws DSpaceSwordException
*/
public List<Item> getAllowedItems(SwordContext swordContext, org.dspace.content.Collection collection)
public List<Item> getAllowedItems(SwordContext swordContext,
org.dspace.content.Collection collection)
throws DSpaceSwordException
{
// an item is allowed if the following conditions are met
@@ -692,7 +746,8 @@ public class SwordAuthenticator
try
{
List<Item> allowed = new ArrayList<>();
Iterator<Item> ii = itemService.findByCollection(swordContext.getContext(), collection);
Iterator<Item> ii = itemService
.findByCollection(swordContext.getContext(), collection);
while (ii.hasNext())
{
@@ -714,20 +769,27 @@ public class SwordAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
boolean write = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), item, Constants.WRITE);
boolean write = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), item,
Constants.WRITE);
boolean add = false;
if (bundles.isEmpty())
{
add = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), item, Constants.ADD);
add = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), item,
Constants.ADD);
}
else
{
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
if (Constants.CONTENT_BUNDLE_NAME
.equals(bundle.getName()))
{
add = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), bundle, Constants.ADD);
add = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(),
bundle, Constants.ADD);
if (!add)
{
break;
@@ -743,20 +805,27 @@ public class SwordAuthenticator
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
boolean write = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), item, Constants.WRITE);
boolean write = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), item,
Constants.WRITE);
boolean add = false;
if (bundles.isEmpty())
{
add = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), item, Constants.ADD);
add = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), item,
Constants.ADD);
}
else
{
for (Bundle bundle : bundles)
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
if (Constants.CONTENT_BUNDLE_NAME
.equals(bundle.getName()))
{
add = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), bundle, Constants.ADD);
add = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(),
bundle, Constants.ADD);
if (!add)
{
break;
@@ -802,7 +871,8 @@ public class SwordAuthenticator
* @param collection
* @throws DSpaceSwordException
*/
public boolean canSubmitTo(SwordContext swordContext, org.dspace.content.Collection collection)
public boolean canSubmitTo(SwordContext swordContext,
org.dspace.content.Collection collection)
throws DSpaceSwordException
{
// a user can submit to a collection in the following conditions:
@@ -831,14 +901,18 @@ public class SwordAuthenticator
// so we do not need to check that separately
if (!authAllowed)
{
authAllowed = authorizeService.authorizeActionBoolean(swordContext.getAuthenticatorContext(), collection, Constants.ADD);
authAllowed = authorizeService.authorizeActionBoolean(
swordContext.getAuthenticatorContext(), collection,
Constants.ADD);
}
// if we have not already determined that the obo user is ok to submit, look up the READ policy on the
// community. THis will include determining if the user is an administrator.
if (!oboAllowed)
{
oboAllowed = authorizeService.authorizeActionBoolean(swordContext.getOnBehalfOfContext(), collection, Constants.ADD);
oboAllowed = authorizeService.authorizeActionBoolean(
swordContext.getOnBehalfOfContext(), collection,
Constants.ADD);
}
// final check to see if we are allowed to READ
@@ -872,7 +946,8 @@ public class SwordAuthenticator
if (isObo)
{
// we need to find out if the authenticated user is permitted to mediate
if (!this.allowedToMediate(swordContext.getAuthenticatorContext()))
if (!this.allowedToMediate(
swordContext.getAuthenticatorContext()))
{
return false;
}
@@ -885,13 +960,17 @@ public class SwordAuthenticator
// we now need to check whether the selected context that we are authorising
// has the appropriate permissions
boolean write = authorizeService.authorizeActionBoolean(allowContext, item, Constants.WRITE);
boolean write = authorizeService
.authorizeActionBoolean(allowContext, item,
Constants.WRITE);
List<Bundle> bundles = item.getBundles();
boolean add = false;
if (bundles.isEmpty())
{
add = authorizeService.authorizeActionBoolean(allowContext, item, Constants.ADD);
add = authorizeService
.authorizeActionBoolean(allowContext, item,
Constants.ADD);
}
else
{
@@ -899,7 +978,9 @@ public class SwordAuthenticator
{
if (Constants.CONTENT_BUNDLE_NAME.equals(bundle.getName()))
{
add = authorizeService.authorizeActionBoolean(allowContext, bundle, Constants.ADD);
add = authorizeService
.authorizeActionBoolean(allowContext, bundle,
Constants.ADD);
if (!add)
{
break;
@@ -921,7 +1002,8 @@ public class SwordAuthenticator
private boolean allowedToMediate(Context context)
{
// get the configuration
String mediatorCfg = ConfigurationManager.getProperty("swordv2-server", "on-behalf-of.update.mediators");
String mediatorCfg = ConfigurationManager
.getProperty("swordv2-server", "on-behalf-of.update.mediators");
if (mediatorCfg == null)
{
// if there's no explicit list of mediators, then anyone can mediate
@@ -967,9 +1049,11 @@ public class SwordAuthenticator
public boolean canSubmitTo(SwordContext context, DSpaceObject dso)
throws DSpaceSwordException
{
if (dso instanceof Collection) {
if (dso instanceof Collection)
{
return this.canSubmitTo(context, (Collection) dso);
} else
}
else
return dso instanceof Item && this.canSubmitTo(context, (Item) dso);
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -30,9 +30,11 @@ import java.util.Set;
public class SwordConfigurationDSpace implements SwordConfiguration
{
/** logger */
public static final Logger log = Logger.getLogger(SwordConfigurationDSpace.class);
public static final Logger log = Logger
.getLogger(SwordConfigurationDSpace.class);
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory
.getInstance().getBitstreamFormatService();
/** whether we can be verbose */
private boolean verbose = true;
@@ -69,33 +71,41 @@ public class SwordConfigurationDSpace implements SwordConfiguration
public SwordConfigurationDSpace()
{
// set the max upload size
int mus = ConfigurationManager.getIntProperty("swordv2-server", "max-upload-size");
int mus = ConfigurationManager
.getIntProperty("swordv2-server", "max-upload-size");
if (mus > 0)
{
this.maxUploadSize = mus;
}
// set the mediation value
this.mediated = ConfigurationManager.getBooleanProperty("swordv2-server", "on-behalf-of.enable");
this.mediated = ConfigurationManager
.getBooleanProperty("swordv2-server", "on-behalf-of.enable");
// find out if we keep the original as bitstream
this.keepOriginal = ConfigurationManager.getBooleanProperty("swordv2-server", "keep-original-package");
this.keepOriginal = ConfigurationManager
.getBooleanProperty("swordv2-server", "keep-original-package");
// get the sword bundle
String bundle = ConfigurationManager.getProperty("swordv2-server", "bundle.name");
String bundle = ConfigurationManager
.getProperty("swordv2-server", "bundle.name");
if (bundle != null && "".equals(bundle))
{
this.swordBundle = bundle;
}
// find out if we keep the package as a file in specified directory
this.keepPackageOnFailedIngest = ConfigurationManager.getBooleanProperty("swordv2-server", "keep-package-on-fail", false);
this.keepPackageOnFailedIngest = ConfigurationManager
.getBooleanProperty("swordv2-server", "keep-package-on-fail",
false);
// get directory path and name
this.failedPackageDir = ConfigurationManager.getProperty("swordv2-server", "failed-package.dir");
this.failedPackageDir = ConfigurationManager
.getProperty("swordv2-server", "failed-package.dir");
// Get the accepted formats
String acceptsProperty = ConfigurationManager.getProperty("swordv2-server", "accepts");
String acceptsProperty = ConfigurationManager
.getProperty("swordv2-server", "accepts");
swordaccepts = new ArrayList<String>();
if (acceptsProperty == null)
{
@@ -107,10 +117,14 @@ public class SwordConfigurationDSpace implements SwordConfiguration
}
// find out if community deposit is allowed
this.allowCommunityDeposit = ConfigurationManager.getBooleanProperty("swordv2-server", "allow-community-deposit");
this.allowCommunityDeposit = ConfigurationManager
.getBooleanProperty("swordv2-server",
"allow-community-deposit");
// find out if we keep the package as a file in specified directory
this.entryFirst = ConfigurationManager.getBooleanProperty("swordv2-server", "multipart.entry-first", false);
this.entryFirst = ConfigurationManager
.getBooleanProperty("swordv2-server", "multipart.entry-first",
false);
}
@@ -118,7 +132,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration
// Utilities
///////////////////////////////////////////////////////////////////////////////////
public String getStringProperty(String module, String propName, String defaultValue, String[] allowedValues)
public String getStringProperty(String module, String propName,
String defaultValue, String[] allowedValues)
{
String cfg;
if (module == null)
@@ -155,7 +170,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration
return defaultValue;
}
public String getStringProperty(String module, String propName, String defaultValue)
public String getStringProperty(String module, String propName,
String defaultValue)
{
return this.getStringProperty(module, propName, defaultValue, null);
}
@@ -164,8 +180,6 @@ public class SwordConfigurationDSpace implements SwordConfiguration
// Required by the SwordConfiguration interface
//////////////////////////////////////////////////////////////////////////////////
public boolean returnDepositReceipt()
{
return true;
@@ -173,7 +187,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration
public boolean returnStackTraceInError()
{
return ConfigurationManager.getBooleanProperty("swordv2-server", "verbose-description.error.enable");
return ConfigurationManager.getBooleanProperty("swordv2-server",
"verbose-description.error.enable");
}
public boolean returnErrorBody()
@@ -183,12 +198,14 @@ public class SwordConfigurationDSpace implements SwordConfiguration
public String generator()
{
return this.getStringProperty("swordv2-server", "generator.url", DSpaceUriRegistry.DSPACE_SWORD_NS);
return this.getStringProperty("swordv2-server", "generator.url",
DSpaceUriRegistry.DSPACE_SWORD_NS);
}
public String generatorVersion()
{
return this.getStringProperty("swordv2-server", "generator.version", "2.0");
return this.getStringProperty("swordv2-server", "generator.version",
"2.0");
}
public String administratorEmail()
@@ -198,7 +215,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration
public String getAuthType()
{
return this.getStringProperty("swordv2-server", "auth-type", "Basic", new String[] { "Basic", "None" } );
return this.getStringProperty("swordv2-server", "auth-type", "Basic",
new String[] { "Basic", "None" });
}
public boolean storeAndCheckBinary()
@@ -213,19 +231,22 @@ public class SwordConfigurationDSpace implements SwordConfiguration
public String getAlternateUrl()
{
return ConfigurationManager.getProperty("swordv2-server", "error.alternate.url");
return ConfigurationManager
.getProperty("swordv2-server", "error.alternate.url");
}
public String getAlternateUrlContentType()
{
return ConfigurationManager.getProperty("swordv2-server", "error.alternate.content-type");
return ConfigurationManager
.getProperty("swordv2-server", "error.alternate.content-type");
}
///////////////////////////////////////////////////////////////////////////////////
// Required by DSpace-side implementation
///////////////////////////////////////////////////////////////////////////////////
public SwordUrlManager getUrlManager(Context context, SwordConfigurationDSpace config)
public SwordUrlManager getUrlManager(Context context,
SwordConfigurationDSpace config)
{
return new SwordUrlManager(config, context);
}
@@ -259,7 +280,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration
boolean disseminable = true;
try
{
SwordContentDisseminator disseminator = SwordDisseminatorFactory.getContentInstance(null, value);
SwordContentDisseminator disseminator = SwordDisseminatorFactory
.getContentInstance(null, value);
}
catch (SwordError e)
{
@@ -434,8 +456,10 @@ public class SwordConfigurationDSpace implements SwordConfiguration
{
// items will take any of the bitstream formats registered, plus
// any swordaccepts mimetypes
List<BitstreamFormat> bfs = bitstreamFormatService.findNonInternal(context);
for (BitstreamFormat bf : bfs) {
List<BitstreamFormat> bfs = bitstreamFormatService
.findNonInternal(context);
for (BitstreamFormat bf : bfs)
{
accepts.add(bf.getMIMEType());
}
for (String format : swordaccepts)
@@ -622,7 +646,8 @@ public class SwordConfigurationDSpace implements SwordConfiguration
* @param dso
* @throws DSpaceSwordException
*/
public boolean isAcceptableContentType(Context context, String type, DSpaceObject dso)
public boolean isAcceptableContentType(Context context, String type,
DSpaceObject dso)
throws DSpaceSwordException
{
List<String> accepts = this.getAccepts(context, dso);
@@ -671,12 +696,14 @@ public class SwordConfigurationDSpace implements SwordConfiguration
public String getStateUri(String state)
{
return ConfigurationManager.getProperty("swordv2-server", "state." + state + ".uri");
return ConfigurationManager
.getProperty("swordv2-server", "state." + state + ".uri");
}
public String getStateDescription(String state)
{
return ConfigurationManager.getProperty("swordv2-server", "state." + state + ".description");
return ConfigurationManager.getProperty("swordv2-server",
"state." + state + ".description");
}
public boolean allowUnauthenticatedMediaAccess()

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -32,9 +32,13 @@ public interface SwordContentIngester
* @return the result of the deposit
* @throws DSpaceSwordException
*/
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException;
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target,
VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException;
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException;
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target,
VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -17,7 +17,8 @@ import java.util.Map;
public class SwordDisseminatorFactory
{
public static SwordContentDisseminator getContentInstance(Map<Float, List<String>> accept, String acceptPackaging)
public static SwordContentDisseminator getContentInstance(
Map<Float, List<String>> accept, String acceptPackaging)
throws DSpaceSwordException, SwordError
{
try
@@ -31,9 +32,13 @@ public class SwordDisseminatorFactory
{
for (String format : accept.get(q))
{
format = format.replace(";", "_"); // clean up the string for the plugin manager
format = format.replace("=", "_"); // clean up the string for the plugin manager
disseminator = (SwordContentDisseminator) PluginManager.getNamedPlugin("swordv2-server", SwordContentDisseminator.class, format);
format = format.replace(";",
"_"); // clean up the string for the plugin manager
format = format.replace("=",
"_"); // clean up the string for the plugin manager
disseminator = (SwordContentDisseminator) PluginManager
.getNamedPlugin("swordv2-server",
SwordContentDisseminator.class, format);
if (disseminator == null)
{
continue;
@@ -42,7 +47,8 @@ public class SwordDisseminatorFactory
{
// if we find a disseminator which says it does this format, then find out if it
// will do the packaging
if (!disseminator.disseminatesPackage(acceptPackaging))
if (!disseminator
.disseminatesPackage(acceptPackaging))
{
disseminator = null;
continue;
@@ -62,9 +68,14 @@ public class SwordDisseminatorFactory
{
if (acceptPackaging != null)
{
acceptPackaging = acceptPackaging.replace(";", "_"); // clean up the string for the plugin manager
acceptPackaging = acceptPackaging.replace("=", "_"); // clean up the string for the plugin manager
disseminator = (SwordContentDisseminator) PluginManager.getNamedPlugin("swordv2-server", SwordContentDisseminator.class, acceptPackaging);
acceptPackaging = acceptPackaging.replace(";",
"_"); // clean up the string for the plugin manager
acceptPackaging = acceptPackaging.replace("=",
"_"); // clean up the string for the plugin manager
disseminator = (SwordContentDisseminator) PluginManager
.getNamedPlugin("swordv2-server",
SwordContentDisseminator.class,
acceptPackaging);
if (disseminator != null)
{
if (accept != null)
@@ -73,7 +84,8 @@ public class SwordDisseminatorFactory
{
for (String format : accept.get(q))
{
if (!disseminator.disseminatesContentType(format))
if (!disseminator
.disseminatesContentType(format))
{
disseminator = null;
}
@@ -90,7 +102,8 @@ public class SwordDisseminatorFactory
if (disseminator == null)
{
throw new SwordError(UriRegistry.ERROR_CONTENT, 406, "No plugin can disseminate the requested formats");
throw new SwordError(UriRegistry.ERROR_CONTENT, 406,
"No plugin can disseminate the requested formats");
}
disseminator.setPackaging(acceptPackaging);
@@ -102,7 +115,8 @@ public class SwordDisseminatorFactory
}
}
public static SwordStatementDisseminator getStatementInstance(Map<Float, List<String>> accept)
public static SwordStatementDisseminator getStatementInstance(
Map<Float, List<String>> accept)
throws DSpaceSwordException, SwordError
{
SwordStatementDisseminator disseminator = null;
@@ -114,9 +128,13 @@ public class SwordDisseminatorFactory
{
for (String format : accept.get(q))
{
format = format.replace(";", "_"); // clean up the string for the plugin manager
format = format.replace("=", "_"); // clean up the string for the plugin manager
disseminator = (SwordStatementDisseminator) PluginManager.getNamedPlugin("swordv2-server", SwordStatementDisseminator.class, format);
format = format.replace(";",
"_"); // clean up the string for the plugin manager
format = format.replace("=",
"_"); // clean up the string for the plugin manager
disseminator = (SwordStatementDisseminator) PluginManager
.getNamedPlugin("swordv2-server",
SwordStatementDisseminator.class, format);
if (disseminator != null)
{
break;
@@ -127,7 +145,8 @@ public class SwordDisseminatorFactory
if (disseminator == null)
{
throw new SwordError(UriRegistry.ERROR_CONTENT, 406, "No plugin can disseminate the requested formats");
throw new SwordError(UriRegistry.ERROR_CONTENT, 406,
"No plugin can disseminate the requested formats");
}
return disseminator;
@@ -136,10 +155,13 @@ public class SwordDisseminatorFactory
public static SwordEntryDisseminator getEntryInstance()
throws DSpaceSwordException, SwordError
{
SwordEntryDisseminator disseminator = (SwordEntryDisseminator) PluginManager.getSinglePlugin("swordv2-server", SwordEntryDisseminator.class);
SwordEntryDisseminator disseminator = (SwordEntryDisseminator) PluginManager
.getSinglePlugin("swordv2-server",
SwordEntryDisseminator.class);
if (disseminator == null)
{
throw new SwordError(DSpaceUriRegistry.REPOSITORY_ERROR, "No disseminator configured for handling sword entry documents");
throw new SwordError(DSpaceUriRegistry.REPOSITORY_ERROR,
"No disseminator configured for handling sword entry documents");
}
return disseminator;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -15,6 +15,7 @@ import org.swordapp.server.SwordServerException;
public interface SwordEntryDisseminator
{
public DepositReceipt disseminate(Context context, Item item, DepositReceipt receipt)
public DepositReceipt disseminate(Context context, Item item,
DepositReceipt receipt)
throws DSpaceSwordException, SwordError, SwordServerException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -16,9 +16,14 @@ import org.swordapp.server.SwordServerException;
public interface SwordEntryIngester
{
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException;
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target,
VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException;
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target, VerboseDescription verboseDescription, DepositResult result, boolean replace)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException;
DepositResult ingest(Context context, Deposit deposit, DSpaceObject target,
VerboseDescription verboseDescription, DepositResult result,
boolean replace)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -15,7 +15,6 @@ import org.swordapp.server.Deposit;
import org.swordapp.server.SwordError;
import org.swordapp.server.UriRegistry;
/**
* Factory class which will mint objects conforming to the
* SWORDIngester interface.
@@ -39,13 +38,16 @@ public class SwordIngesterFactory
* @param deposit
* @throws DSpaceSwordException
*/
public static SwordContentIngester getContentInstance(Context context, Deposit deposit, DSpaceObject dso)
public static SwordContentIngester getContentInstance(Context context,
Deposit deposit, DSpaceObject dso)
throws DSpaceSwordException, SwordError
{
SwordContentIngester ingester = null;
// first look to see if there's an intester for the content type
ingester = (SwordContentIngester) PluginManager.getNamedPlugin("swordv2-server", SwordContentIngester.class, deposit.getMimeType());
ingester = (SwordContentIngester) PluginManager
.getNamedPlugin("swordv2-server", SwordContentIngester.class,
deposit.getMimeType());
if (ingester != null)
{
return ingester;
@@ -53,21 +55,27 @@ public class SwordIngesterFactory
// if no ingester, then
// look to see if there's an ingester for the package format
ingester = (SwordContentIngester) PluginManager.getNamedPlugin("swordv2-server", SwordContentIngester.class, deposit.getPackaging());
ingester = (SwordContentIngester) PluginManager
.getNamedPlugin("swordv2-server", SwordContentIngester.class,
deposit.getPackaging());
if (ingester == null)
{
throw new SwordError(UriRegistry.ERROR_CONTENT, "No ingester configured for this package type");
throw new SwordError(UriRegistry.ERROR_CONTENT,
"No ingester configured for this package type");
}
return ingester;
}
public static SwordEntryIngester getEntryInstance(Context context, Deposit deposit, DSpaceObject dso)
public static SwordEntryIngester getEntryInstance(Context context,
Deposit deposit, DSpaceObject dso)
throws DSpaceSwordException, SwordError
{
SwordEntryIngester ingester = (SwordEntryIngester) PluginManager.getSinglePlugin("swordv2-server", SwordEntryIngester.class);
SwordEntryIngester ingester = (SwordEntryIngester) PluginManager
.getSinglePlugin("swordv2-server", SwordEntryIngester.class);
if (ingester == null)
{
throw new SwordError(UriRegistry.ERROR_CONTENT, "No ingester configured for handling sword entry documents");
throw new SwordError(UriRegistry.ERROR_CONTENT,
"No ingester configured for handling sword entry documents");
}
return ingester;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -37,22 +37,35 @@ import org.swordapp.server.SwordServerException;
public class SwordMETSContentIngester extends AbstractSwordContentIngester
{
/** Log4j logger */
public static final Logger log = Logger.getLogger(SwordMETSContentIngester.class);
public static final Logger log = Logger
.getLogger(SwordMETSContentIngester.class);
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory
.getInstance().getWorkspaceItemService();
public DepositResult ingest(Context context, Deposit deposit, DSpaceObject dso, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
protected CollectionService collectionService = ContentServiceFactory
.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService();
public DepositResult ingest(Context context, Deposit deposit,
DSpaceObject dso, VerboseDescription verboseDescription)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
return this.ingest(context, deposit, dso, verboseDescription, null);
}
@Override
public DepositResult ingestToCollection(Context context, Deposit deposit, Collection collection, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingestToCollection(Context context, Deposit deposit,
Collection collection, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
try
{
@@ -61,7 +74,8 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
if (result != null)
{
Item item = result.getItem();
return this.ingestToItem(context, deposit, item, verboseDescription, result);
return this.ingestToItem(context, deposit, item,
verboseDescription, result);
}
// otherwise, go on and do a create ...
@@ -71,29 +85,34 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
// us finer control over the workflow state of the item, whereas asking
// the ingester to /create/ this item causes it to be injected into the workflow,
// irrespective of the In-Progress header provided by the depositor
WorkspaceItem wsi = workspaceItemService.create(context, collection, true);
WorkspaceItem wsi = workspaceItemService
.create(context, collection, true);
Item item = wsi.getItem();
// need to add a licence file, otherwise the METS replace function raises a NullPointerException
String licence = collectionService.getLicense(collection);
if (PackageUtils.findDepositLicense(context, item) == null)
{
PackageUtils.addDepositLicense(context, licence, item, collection);
PackageUtils
.addDepositLicense(context, licence, item, collection);
}
// get deposited file as InputStream
File depositFile = deposit.getFile();
// load the plugin manager for the required configuration
String cfg = ConfigurationManager.getProperty("sword-server", "mets-ingester.package-ingester");
String cfg = ConfigurationManager.getProperty("sword-server",
"mets-ingester.package-ingester");
if (cfg == null || "".equals(cfg))
{
cfg = "METS"; // default to METS
}
verboseDescription.append("Using package manifest format: " + cfg);
PackageIngester pi = (PackageIngester) PluginManager.getNamedPlugin(PackageIngester.class, cfg);
verboseDescription.append("Loaded package ingester: " + pi.getClass().getName());
PackageIngester pi = (PackageIngester) PluginManager
.getNamedPlugin(PackageIngester.class, cfg);
verboseDescription.append("Loaded package ingester: " +
pi.getClass().getName());
// Initialize parameters to packager
PackageParameters params = new PackageParameters();
@@ -102,26 +121,35 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
params.setWorkflowEnabled(true);
// Should restore mode be enabled, i.e. keep existing handle?
if (ConfigurationManager.getBooleanProperty("sword-server", "restore-mode.enable",false))
if (ConfigurationManager
.getBooleanProperty("sword-server", "restore-mode.enable",
false))
{
params.setRestoreModeEnabled(true);
}
// Whether or not to use the collection template
params.setUseCollectionTemplate(ConfigurationManager.getBooleanProperty("mets.default.ingest.useCollectionTemplate", false));
params.setUseCollectionTemplate(ConfigurationManager
.getBooleanProperty(
"mets.default.ingest.useCollectionTemplate",
false));
// ingest the item from the temp file
DSpaceObject ingestedObject = pi.replace(context, item, depositFile, params);
DSpaceObject ingestedObject = pi
.replace(context, item, depositFile, params);
if (ingestedObject == null)
{
verboseDescription.append("Failed to ingest the package; throwing exception");
throw new SwordError(DSpaceUriRegistry.UNPACKAGE_FAIL, "METS package ingester failed to unpack package");
verboseDescription
.append("Failed to ingest the package; throwing exception");
throw new SwordError(DSpaceUriRegistry.UNPACKAGE_FAIL,
"METS package ingester failed to unpack package");
}
// Verify we have an Item as a result
if (!(ingestedObject instanceof Item))
{
throw new DSpaceSwordException("DSpace Ingester returned wrong object type -- not an Item result.");
throw new DSpaceSwordException(
"DSpace Ingester returned wrong object type -- not an Item result.");
}
else
{
@@ -138,7 +166,8 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
// DSpace ignores the slug value as suggested identifier, but
// it does store it in the metadata
this.setSlug(context, installedItem, deposit.getSlug(), verboseDescription);
this.setSlug(context, installedItem, deposit.getSlug(),
verboseDescription);
// in order to write these changes, we need to bypass the
// authorisation briefly, because although the user may be
@@ -153,14 +182,19 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
String handle = handleService.findHandle(context, installedItem);
verboseDescription.append("Ingest successful");
verboseDescription.append("Item created with internal identifier: " + installedItem.getID());
verboseDescription
.append("Item created with internal identifier: " +
installedItem.getID());
if (handle != null)
{
verboseDescription.append("Item created with external identifier: " + handle);
verboseDescription
.append("Item created with external identifier: " +
handle);
}
else
{
verboseDescription.append("No external identifier available at this stage (item in workflow)");
verboseDescription
.append("No external identifier available at this stage (item in workflow)");
}
DepositResult dr = new DepositResult();
@@ -182,8 +216,11 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
}
@Override
public DepositResult ingestToItem(Context context, Deposit deposit, Item item, VerboseDescription verboseDescription, DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException, SwordServerException
public DepositResult ingestToItem(Context context, Deposit deposit,
Item item, VerboseDescription verboseDescription,
DepositResult result)
throws DSpaceSwordException, SwordError, SwordAuthException,
SwordServerException
{
if (result == null)
{
@@ -196,15 +233,18 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
File depositFile = deposit.getFile();
// load the plugin manager for the required configuration
String cfg = ConfigurationManager.getProperty("sword-server", "mets-ingester.package-ingester");
String cfg = ConfigurationManager.getProperty("sword-server",
"mets-ingester.package-ingester");
if (cfg == null || "".equals(cfg))
{
cfg = "METS"; // default to METS
}
verboseDescription.append("Using package manifest format: " + cfg);
PackageIngester pi = (PackageIngester) PluginManager.getNamedPlugin(PackageIngester.class, cfg);
verboseDescription.append("Loaded package ingester: " + pi.getClass().getName());
PackageIngester pi = (PackageIngester) PluginManager
.getNamedPlugin(PackageIngester.class, cfg);
verboseDescription.append("Loaded package ingester: " +
pi.getClass().getName());
// Initialize parameters to packager
PackageParameters params = new PackageParameters();
@@ -213,26 +253,35 @@ public class SwordMETSContentIngester extends AbstractSwordContentIngester
params.setWorkflowEnabled(true);
// Should restore mode be enabled, i.e. keep existing handle?
if (ConfigurationManager.getBooleanProperty("sword-server", "restore-mode.enable",false))
if (ConfigurationManager
.getBooleanProperty("sword-server", "restore-mode.enable",
false))
{
params.setRestoreModeEnabled(true);
}
// Whether or not to use the collection template
params.setUseCollectionTemplate(ConfigurationManager.getBooleanProperty("mets.default.ingest.useCollectionTemplate", false));
params.setUseCollectionTemplate(ConfigurationManager
.getBooleanProperty(
"mets.default.ingest.useCollectionTemplate",
false));
// ingest the item from the temp file
DSpaceObject ingestedObject = pi.replace(context, item, depositFile, params);
DSpaceObject ingestedObject = pi
.replace(context, item, depositFile, params);
if (ingestedObject == null)
{
verboseDescription.append("Failed to replace the package; throwing exception");
throw new SwordError(DSpaceUriRegistry.UNPACKAGE_FAIL, "METS package ingester failed to unpack package");
verboseDescription
.append("Failed to replace the package; throwing exception");
throw new SwordError(DSpaceUriRegistry.UNPACKAGE_FAIL,
"METS package ingester failed to unpack package");
}
// Verify we have an Item as a result
if (!(ingestedObject instanceof Item))
{
throw new DSpaceSwordException("DSpace Ingester returned wrong object type -- not an Item result.");
throw new DSpaceSwordException(
"DSpace Ingester returned wrong object type -- not an Item result.");
}
// get reference to item so that we can report on it

View File

@@ -2,12 +2,11 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Item;
@@ -39,7 +38,8 @@ public class SwordMETSPackageIngester extends DSpaceMETSIngester
throws PackageValidationException,
AuthorizeException, SQLException, IOException
{
if (PackageUtils.findDepositLicense(context, item) == null && license != null)
if (PackageUtils.findDepositLicense(context, item) == null &&
license != null)
{
PackageUtils.addDepositLicense(context, license, item, collection);
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -32,9 +32,14 @@ import java.util.List;
*/
public class SwordUrlManager
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
protected HandleService handleService = HandleServiceFactory.getInstance()
.getHandleService();
/** the sword configuration */
private SwordConfigurationDSpace config;
@@ -88,22 +93,26 @@ public class SwordUrlManager
String sUrl = ConfigurationManager.getProperty("swordv2-server", "url");
if (sUrl == null || "".equals(sUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
String dspaceUrl = ConfigurationManager
.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSwordException("Unable to construct service document urls, due to missing/invalid " +
throw new DSpaceSwordException(
"Unable to construct service document urls, due to missing/invalid " +
"config in sword2.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
sUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/swordv2").toString();
sUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(),
"/swordv2").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSwordException("Unable to construct service document urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
throw new DSpaceSwordException(
"Unable to construct service document urls, due to invalid dspace.baseUrl " +
e.getMessage(), e);
}
}
return sUrl;
@@ -133,7 +142,8 @@ public class SwordUrlManager
}
else
{
throw new SwordError(DSpaceUriRegistry.BAD_URL, "The item URL is invalid");
throw new SwordError(DSpaceUriRegistry.BAD_URL,
"The item URL is invalid");
}
String iid = location.substring(cBaseUrl.length());
@@ -154,7 +164,8 @@ public class SwordUrlManager
catch (SQLException e)
{
// log.error("Caught exception:", e);
throw new DSpaceSwordException("There was a problem resolving the item", e);
throw new DSpaceSwordException(
"There was a problem resolving the item", e);
}
}
@@ -193,7 +204,8 @@ public class SwordUrlManager
String baseUrl = this.getBaseCollectionUrl();
if (baseUrl.length() == location.length())
{
throw new SwordError(DSpaceUriRegistry.BAD_URL, "The deposit URL is incomplete");
throw new SwordError(DSpaceUriRegistry.BAD_URL,
"The deposit URL is incomplete");
}
String handle = location.substring(baseUrl.length());
if (handle.startsWith("/"))
@@ -202,7 +214,8 @@ public class SwordUrlManager
}
if ("".equals(handle))
{
throw new SwordError(DSpaceUriRegistry.BAD_URL, "The deposit URL is incomplete");
throw new SwordError(DSpaceUriRegistry.BAD_URL,
"The deposit URL is incomplete");
}
DSpaceObject dso = handleService.resolveToObject(context, handle);
@@ -213,7 +226,8 @@ public class SwordUrlManager
if (!(dso instanceof Collection))
{
throw new SwordError(DSpaceUriRegistry.BAD_URL, "The deposit URL does not resolve to a valid collection");
throw new SwordError(DSpaceUriRegistry.BAD_URL,
"The deposit URL does not resolve to a valid collection");
}
return (Collection) dso;
@@ -221,7 +235,8 @@ public class SwordUrlManager
catch (SQLException e)
{
// log.error("Caught exception:", e);
throw new DSpaceSwordException("There was a problem resolving the collection", e);
throw new DSpaceSwordException(
"There was a problem resolving the collection", e);
}
}
@@ -306,7 +321,8 @@ public class SwordUrlManager
else
{
throw new SwordError(DSpaceUriRegistry.BAD_URL,
"Unable to recognise URL as a valid service document: " + url);
"Unable to recognise URL as a valid service document: " +
url);
}
}
catch (SQLException e)
@@ -323,25 +339,30 @@ public class SwordUrlManager
public String getBaseServiceDocumentUrl()
throws DSpaceSwordException
{
String sdUrl = ConfigurationManager.getProperty("swordv2-server", "servicedocument.url");
String sdUrl = ConfigurationManager
.getProperty("swordv2-server", "servicedocument.url");
if (sdUrl == null || "".equals(sdUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
String dspaceUrl = ConfigurationManager
.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSwordException("Unable to construct service document urls, due to missing/invalid " +
throw new DSpaceSwordException(
"Unable to construct service document urls, due to missing/invalid " +
"config in swordv2-server.cfg servicedocument.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
sdUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/swordv2/servicedocument").toString();
sdUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(),
"/swordv2/servicedocument").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSwordException("Unable to construct service document urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
throw new DSpaceSwordException(
"Unable to construct service document urls, due to invalid dspace.baseUrl " +
e.getMessage(), e);
}
}
return sdUrl;
@@ -366,28 +387,32 @@ public class SwordUrlManager
public String getBaseCollectionUrl()
throws DSpaceSwordException
{
String depositUrl = ConfigurationManager.getProperty("swordv2-server", "collection.url");
String depositUrl = ConfigurationManager
.getProperty("swordv2-server", "collection.url");
if (depositUrl == null || "".equals(depositUrl))
{
String dspaceUrl = ConfigurationManager.getProperty("dspace.baseUrl");
String dspaceUrl = ConfigurationManager
.getProperty("dspace.baseUrl");
if (dspaceUrl == null || "".equals(dspaceUrl))
{
throw new DSpaceSwordException("Unable to construct deposit urls, due to missing/invalid config in " +
throw new DSpaceSwordException(
"Unable to construct deposit urls, due to missing/invalid config in " +
"swordv2-server.cfg deposit.url and/or dspace.baseUrl");
}
try
{
URL url = new URL(dspaceUrl);
depositUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/swordv2/collection").toString();
depositUrl = new URL(url.getProtocol(), url.getHost(),
url.getPort(), "/swordv2/collection").toString();
}
catch (MalformedURLException e)
{
throw new DSpaceSwordException("Unable to construct deposit urls, due to invalid dspace.baseUrl " +
e.getMessage(),e);
throw new DSpaceSwordException(
"Unable to construct deposit urls, due to invalid dspace.baseUrl " +
e.getMessage(), e);
}
}
return depositUrl;
}
@@ -424,7 +449,8 @@ public class SwordUrlManager
}
else
{
throw new DSpaceSwordException("Encountered orphaned bitstream");
throw new DSpaceSwordException(
"Encountered orphaned bitstream");
}
List<Item> items = parent.getItems();
@@ -443,11 +469,13 @@ public class SwordUrlManager
if (handle != null && !"".equals(handle))
{
bsLink = bsLink + "/bitstream/" + handle + "/" + bitstream.getSequenceID() + "/" + bitstream.getName();
bsLink = bsLink + "/bitstream/" + handle + "/" +
bitstream.getSequenceID() + "/" + bitstream.getName();
}
else
{
bsLink = bsLink + "/retrieve/" + bitstream.getID() + "/" + bitstream.getName();
bsLink = bsLink + "/retrieve/" + bitstream.getID() + "/" +
bitstream.getName();
}
return bsLink;
@@ -461,7 +489,8 @@ public class SwordUrlManager
public String getActionableBitstreamUrl(Bitstream bitstream)
throws DSpaceSwordException
{
return this.getSwordBaseUrl() + "/edit-media/bitstream/" + bitstream.getID() + "/" + bitstream.getName();
return this.getSwordBaseUrl() + "/edit-media/bitstream/" +
bitstream.getID() + "/" + bitstream.getName();
}
public boolean isActionableBitstreamUrl(Context context, String url)
@@ -478,7 +507,8 @@ public class SwordUrlManager
String emBaseUrl = baseUrl + "/edit-media/bitstream/";
if (!location.startsWith(emBaseUrl))
{
throw new SwordError(DSpaceUriRegistry.BAD_URL, "The bitstream URL is invalid");
throw new SwordError(DSpaceUriRegistry.BAD_URL,
"The bitstream URL is invalid");
}
String bitstreamParts = location.substring(emBaseUrl.length());
@@ -488,13 +518,15 @@ public class SwordUrlManager
String bid = bitstreamParts.substring(0, firstSlash);
String fn = bitstreamParts.substring(firstSlash + 1);
Bitstream bitstream = bitstreamService.findByIdOrLegacyId(context, bid);
Bitstream bitstream = bitstreamService
.findByIdOrLegacyId(context, bid);
return bitstream;
}
catch (SQLException e)
{
// log.error("Caught exception:", e);
throw new DSpaceSwordException("There was a problem resolving the collection", e);
throw new DSpaceSwordException(
"There was a problem resolving the collection", e);
}
}
@@ -532,10 +564,12 @@ public class SwordUrlManager
// special identifier
if (wft.isItemInWorkspace(context, item))
{
String urlTemplate = ConfigurationManager.getProperty("swordv2-server", "workspace.url-template");
String urlTemplate = ConfigurationManager
.getProperty("swordv2-server", "workspace.url-template");
if (urlTemplate != null)
{
return urlTemplate.replace("#wsid#", Integer.toString(wft.getWorkspaceItem(context, item).getID()));
return urlTemplate.replace("#wsid#", Integer.toString(
wft.getWorkspaceItem(context, item).getID()));
}
}
// otherwise, it may be in the workflow, in which case there is
@@ -563,6 +597,7 @@ public class SwordUrlManager
public IRI getMediaFeedUrl(Item item)
throws DSpaceSwordException
{
return new IRI(this.getSwordBaseUrl() + "/edit-media/" + item.getID() + ".atom");
return new IRI(this.getSwordBaseUrl() + "/edit-media/" + item.getID() +
".atom");
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -28,14 +28,20 @@ import java.util.List;
public class VersionManager
{
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected ItemService itemService = ContentServiceFactory.getInstance()
.getItemService();
protected BundleService bundleService = ContentServiceFactory.getInstance()
.getBundleService();
protected BitstreamService bitstreamService = ContentServiceFactory
.getInstance().getBitstreamService();
public void removeBundle(Context context, Item item, String name)
throws SQLException, AuthorizeException, IOException
{
boolean keep = ConfigurationManager.getBooleanProperty("swordv2-server", "versions.keep");
boolean keep = ConfigurationManager
.getBooleanProperty("swordv2-server", "versions.keep");
Iterator<Bundle> bundles = item.getBundles().iterator();
while (bundles.hasNext())
{
@@ -51,11 +57,13 @@ public class VersionManager
public void removeBundle(Context context, Item item, Bundle source)
throws SQLException, AuthorizeException, IOException
{
boolean keep = ConfigurationManager.getBooleanProperty("swordv2-server", "versions.keep");
boolean keep = ConfigurationManager
.getBooleanProperty("swordv2-server", "versions.keep");
this.removeBundle(context, item, source, keep);
}
public void removeBundle(Context context, Item item, Bundle source, boolean archive)
public void removeBundle(Context context, Item item, Bundle source,
boolean archive)
throws SQLException, AuthorizeException, IOException
{
// archive the bundle contents if desired
@@ -65,12 +73,14 @@ public class VersionManager
}
// remove all the bitstreams from the bundle
Iterator<BundleBitstream> bundleBitstreams = source.getBitstreams().iterator();
Iterator<BundleBitstream> bundleBitstreams = source.getBitstreams()
.iterator();
while (bundleBitstreams.hasNext())
{
BundleBitstream bundleBitstream = bundleBitstreams.next();
bundleBitstreams.remove();
bundleService.removeBitstream(context, source, bundleBitstream.getBitstream());
bundleService.removeBitstream(context, source,
bundleBitstream.getBitstream());
}
// delete the bundle itself
@@ -80,11 +90,13 @@ public class VersionManager
public void removeBitstream(Context context, Item item, Bitstream bitstream)
throws SQLException, AuthorizeException, IOException
{
boolean keep = ConfigurationManager.getBooleanProperty("swordv2-server", "versions.keep");
boolean keep = ConfigurationManager
.getBooleanProperty("swordv2-server", "versions.keep");
this.removeBitstream(context, item, bitstream, keep);
}
public void removeBitstream(Context context, Item item, Bitstream bitstream, boolean keep)
public void removeBitstream(Context context, Item item, Bitstream bitstream,
boolean keep)
throws SQLException, AuthorizeException, IOException
{
Bundle exempt = null;
@@ -93,14 +105,18 @@ public class VersionManager
exempt = this.archiveBitstream(context, item, bitstream);
}
Iterator<BundleBitstream> bundleBitstreams = bitstream.getBundles().iterator();
Iterator<BundleBitstream> bundleBitstreams = bitstream.getBundles()
.iterator();
while (bundleBitstreams.hasNext())
{
BundleBitstream bundleBitstream = bundleBitstreams.next();
if (exempt != null && bundleBitstream.getBundle().getID() != exempt.getID())
if (exempt != null &&
bundleBitstream.getBundle().getID() != exempt.getID())
{
bundleBitstreams.remove();
bundleService.removeBitstream(context, bundleBitstream.getBundle(), bitstream);
bundleService
.removeBitstream(context, bundleBitstream.getBundle(),
bitstream);
}
}
@@ -117,10 +133,12 @@ public class VersionManager
bitstreamService.update(context, bitstream);
}
private Bundle archiveBitstream(Context context, Item item, Bitstream bitstream)
private Bundle archiveBitstream(Context context, Item item,
Bitstream bitstream)
throws SQLException, AuthorizeException, IOException
{
String swordBundle = ConfigurationManager.getProperty("swordv2-server", "bundle.deleted");
String swordBundle = ConfigurationManager
.getProperty("swordv2-server", "bundle.deleted");
if (swordBundle == null)
{
swordBundle = "DELETED";
@@ -128,8 +146,10 @@ public class VersionManager
List<Bundle> bundles = item.getBundles();
Bundle archive = null;
for (Bundle bundle : bundles) {
if (swordBundle.equals(bundle.getName())) {
for (Bundle bundle : bundles)
{
if (swordBundle.equals(bundle.getName()))
{
archive = bundle;
break;
}
@@ -142,7 +162,8 @@ public class VersionManager
return archive;
}
private void archiveBitstream(Context context, Bundle target, Bitstream bitstream)
private void archiveBitstream(Context context, Bundle target,
Bitstream bitstream)
throws SQLException, AuthorizeException, IOException
{
bundleService.addBitstream(context, target, bitstream);
@@ -160,7 +181,8 @@ public class VersionManager
List<BundleBitstream> bundleBitstreams = source.getBitstreams();
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
bundleService.addBitstream(context, old, bundleBitstream.getBitstream());
bundleService
.addBitstream(context, old, bundleBitstream.getBitstream());
}
}
@@ -169,8 +191,10 @@ public class VersionManager
{
String nName = name + "." + Integer.toString(number);
List<Bundle> bundles = item.getBundles();
for (Bundle bundle : bundles) {
if (nName.equals(bundle.getName())) {
for (Bundle bundle : bundles)
{
if (nName.equals(bundle.getName()))
{
return this.getNumberedName(item, name, number + 1);
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -16,43 +16,61 @@ import org.swordapp.server.SwordError;
public interface WorkflowManager
{
public void retrieveServiceDoc(Context context) throws SwordError, DSpaceSwordException;
public void retrieveServiceDoc(Context context)
throws SwordError, DSpaceSwordException;
public void listCollectionContents(Context context, Collection collection) throws SwordError, DSpaceSwordException;
public void listCollectionContents(Context context, Collection collection)
throws SwordError, DSpaceSwordException;
public void createResource(Context context, Collection collection) throws SwordError, DSpaceSwordException;
public void createResource(Context context, Collection collection)
throws SwordError, DSpaceSwordException;
public void retrieveContent(Context context, Item item) throws SwordError, DSpaceSwordException;
public void retrieveContent(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void retrieveBitstream(Context context, Bitstream bitstream) throws SwordError, DSpaceSwordException;
public void retrieveBitstream(Context context, Bitstream bitstream)
throws SwordError, DSpaceSwordException;
public void replaceResourceContent(Context context, Item item) throws SwordError, DSpaceSwordException;
public void replaceResourceContent(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void replaceBitstream(Context context, Bitstream bitstream) throws SwordError, DSpaceSwordException;
public void replaceBitstream(Context context, Bitstream bitstream)
throws SwordError, DSpaceSwordException;
public void replaceMetadata(Context context, Item item) throws SwordError, DSpaceSwordException;
public void replaceMetadata(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void replaceMetadataAndMediaResource(Context context, Item item) throws SwordError, DSpaceSwordException;
public void replaceMetadataAndMediaResource(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void deleteMediaResource(Context context, Item item) throws SwordError, DSpaceSwordException;
public void deleteMediaResource(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void deleteBitstream(Context context, Bitstream bitstream) throws SwordError, DSpaceSwordException;
public void deleteBitstream(Context context, Bitstream bitstream)
throws SwordError, DSpaceSwordException;
public void addResourceContent(Context context, Item item) throws SwordError, DSpaceSwordException;
public void addResourceContent(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void addMetadata(Context context, Item item) throws SwordError, DSpaceSwordException;
public void addMetadata(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void deleteItem(Context context, Item item) throws SwordError, DSpaceSwordException;
public void deleteItem(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void retrieveStatement(Context context, Item item) throws SwordError, DSpaceSwordException;
public void retrieveStatement(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void modifyState(Context context, Item item) throws SwordError, DSpaceSwordException;
public void modifyState(Context context, Item item)
throws SwordError, DSpaceSwordException;
public void resolveState(Context context, Deposit deposit, DepositResult result, VerboseDescription verboseDescription)
public void resolveState(Context context, Deposit deposit,
DepositResult result, VerboseDescription verboseDescription)
throws DSpaceSwordException;
public void resolveState(Context context, Deposit deposit, DepositResult result, VerboseDescription verboseDescription, boolean containerOperation)
public void resolveState(Context context, Deposit deposit,
DepositResult result, VerboseDescription verboseDescription,
boolean containerOperation)
throws DSpaceSwordException;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -30,12 +30,14 @@ public class WorkflowManagerDefault implements WorkflowManager
// do nothing - operation allowed
}
public void listCollectionContents(Context context, Collection collection) throws SwordError
public void listCollectionContents(Context context, Collection collection)
throws SwordError
{
// do nothing - operation allowed
}
public void createResource(Context context, Collection collection) throws SwordError
public void createResource(Context context, Collection collection)
throws SwordError
{
// do nothing - operation allowed
}
@@ -45,27 +47,34 @@ public class WorkflowManagerDefault implements WorkflowManager
// do nothing - operation allowed
}
public void retrieveBitstream(Context context, Bitstream bitstream) throws SwordError, DSpaceSwordException
public void retrieveBitstream(Context context, Bitstream bitstream)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void replaceResourceContent(Context context, Item item) throws SwordError, DSpaceSwordException
public void replaceResourceContent(Context context, Item item)
throws SwordError, DSpaceSwordException
{
WorkflowTools wft = new WorkflowTools();
if (item.isArchived() || item.isWithdrawn())
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been archived, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been archived, and can no longer be modified");
}
if (wft.isItemInWorkflow(context, item))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been injected into the review workflow, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been injected into the review workflow, and can no longer be modified");
}
}
public void replaceMetadata(Context context, Item item) throws SwordError, DSpaceSwordException
public void replaceMetadata(Context context, Item item)
throws SwordError, DSpaceSwordException
{
boolean allowUpdate = ConfigurationManager.getBooleanProperty("swordv2-server", "workflowmanagerdefault.always-update-metadata");
boolean allowUpdate = ConfigurationManager
.getBooleanProperty("swordv2-server",
"workflowmanagerdefault.always-update-metadata");
if (allowUpdate)
{
// all updates are allowed
@@ -76,34 +85,41 @@ public class WorkflowManagerDefault implements WorkflowManager
WorkflowTools wft = new WorkflowTools();
if (item.isArchived() || item.isWithdrawn())
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been archived, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been archived, and can no longer be modified");
}
if (wft.isItemInWorkflow(context, item))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been injected into the review workflow, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been injected into the review workflow, and can no longer be modified");
}
}
public void replaceMetadataAndMediaResource(Context context, Item item) throws SwordError, DSpaceSwordException
public void replaceMetadataAndMediaResource(Context context, Item item)
throws SwordError, DSpaceSwordException
{
this.replaceResourceContent(context, item);
this.replaceMetadata(context, item);
}
public void deleteMediaResource(Context context, Item item) throws SwordError, DSpaceSwordException
public void deleteMediaResource(Context context, Item item)
throws SwordError, DSpaceSwordException
{
WorkflowTools wft = new WorkflowTools();
if (item.isArchived() || item.isWithdrawn())
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been archived, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been archived, and can no longer be modified");
}
if (wft.isItemInWorkflow(context, item))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been injected into the review workflow, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been injected into the review workflow, and can no longer be modified");
}
}
public void deleteBitstream(Context context, Bitstream bitstream) throws SwordError, DSpaceSwordException
public void deleteBitstream(Context context, Bitstream bitstream)
throws SwordError, DSpaceSwordException
{
// this is equivalent to asking whether the media resource in the item can be deleted
try
@@ -112,9 +128,11 @@ public class WorkflowManagerDefault implements WorkflowManager
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
// is the bitstream in the ORIGINAL bundle? If not, it can't be worked on
if (!Constants.CONTENT_BUNDLE_NAME.equals(bundleBitstream.getBundle().getName()))
if (!Constants.CONTENT_BUNDLE_NAME
.equals(bundleBitstream.getBundle().getName()))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The file is not in a bundle which can be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The file is not in a bundle which can be modified");
}
List<Item> items = bundleBitstream.getBundle().getItems();
@@ -136,10 +154,13 @@ public class WorkflowManagerDefault implements WorkflowManager
// File replace with DSpace actually violates the RESTful environment, so it is
// turned off by default, and strongly advised against. Nonetheless, it is used
// by some DepositMO aware extensions, so must be supported (as shown below)
boolean fileReplace = ConfigurationManager.getBooleanProperty("swordv2-server", "workflowmanagerdefault.file-replace.enable");
boolean fileReplace = ConfigurationManager
.getBooleanProperty("swordv2-server",
"workflowmanagerdefault.file-replace.enable");
if (!fileReplace)
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "DSpace does not support file replace; you should DELETE the original file and PUT the new one");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"DSpace does not support file replace; you should DELETE the original file and PUT the new one");
}
// this is equivalent to asking whether the media resource in the item can be deleted
@@ -149,9 +170,11 @@ public class WorkflowManagerDefault implements WorkflowManager
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
// is the bitstream in the ORIGINAL bundle? If not, it can't be worked on
if (!Constants.CONTENT_BUNDLE_NAME.equals(bundleBitstream.getBundle().getName()))
if (!Constants.CONTENT_BUNDLE_NAME
.equals(bundleBitstream.getBundle().getName()))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The file is not in a bundle which can be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The file is not in a bundle which can be modified");
}
for (Item item : bundleBitstream.getBundle().getItems())
@@ -166,22 +189,28 @@ public class WorkflowManagerDefault implements WorkflowManager
}
}
public void addResourceContent(Context context, Item item) throws SwordError, DSpaceSwordException
public void addResourceContent(Context context, Item item)
throws SwordError, DSpaceSwordException
{
WorkflowTools wft = new WorkflowTools();
if (item.isArchived() || item.isWithdrawn())
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been archived, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been archived, and can no longer be modified");
}
if (wft.isItemInWorkflow(context, item))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been injected into the review workflow, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been injected into the review workflow, and can no longer be modified");
}
}
public void addMetadata(Context context, Item item) throws SwordError, DSpaceSwordException
public void addMetadata(Context context, Item item)
throws SwordError, DSpaceSwordException
{
boolean allowUpdate = ConfigurationManager.getBooleanProperty("swordv2-server", "workflowmanagerdefault.always-update-metadata");
boolean allowUpdate = ConfigurationManager
.getBooleanProperty("swordv2-server",
"workflowmanagerdefault.always-update-metadata");
if (allowUpdate)
{
// all updates are allowed
@@ -192,52 +221,64 @@ public class WorkflowManagerDefault implements WorkflowManager
WorkflowTools wft = new WorkflowTools();
if (item.isArchived() || item.isWithdrawn())
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been archived, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been archived, and can no longer be modified");
}
if (wft.isItemInWorkflow(context, item))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been injected into the review workflow, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been injected into the review workflow, and can no longer be modified");
}
}
public void deleteItem(Context context, Item item) throws SwordError, DSpaceSwordException
public void deleteItem(Context context, Item item)
throws SwordError, DSpaceSwordException
{
WorkflowTools wft = new WorkflowTools();
if (item.isArchived() || item.isWithdrawn())
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been archived, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been archived, and can no longer be modified");
}
if (wft.isItemInWorkflow(context, item))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been injected into the review workflow, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been injected into the review workflow, and can no longer be modified");
}
}
public void retrieveStatement(Context context, Item item) throws SwordError, DSpaceSwordException
public void retrieveStatement(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void modifyState(Context context, Item item) throws SwordError, DSpaceSwordException
public void modifyState(Context context, Item item)
throws SwordError, DSpaceSwordException
{
WorkflowTools wft = new WorkflowTools();
if (item.isArchived() || item.isWithdrawn())
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been archived, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been archived, and can no longer be modified");
}
if (wft.isItemInWorkflow(context, item))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The item has already been injected into the review workflow, and can no longer be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The item has already been injected into the review workflow, and can no longer be modified");
}
}
public void resolveState(Context context, Deposit deposit, DepositResult result, VerboseDescription verboseDescription)
public void resolveState(Context context, Deposit deposit,
DepositResult result, VerboseDescription verboseDescription)
throws DSpaceSwordException
{
this.resolveState(context, deposit, result, verboseDescription, true);
}
public void resolveState(Context context, Deposit deposit, DepositResult result, VerboseDescription verboseDescription, boolean containerOperation)
public void resolveState(Context context, Deposit deposit,
DepositResult result, VerboseDescription verboseDescription,
boolean containerOperation)
throws DSpaceSwordException
{
// the containerOperation flag tells us whether this method was called by an operation which happened on the
@@ -269,25 +310,29 @@ public class WorkflowManagerDefault implements WorkflowManager
if (!deposit.isInProgress() && inarch)
{
verboseDescription.append("The deposit is finished, and the item is already in the archive");
verboseDescription
.append("The deposit is finished, and the item is already in the archive");
// throw new DSpaceSwordException("Invalid workflow state");
}
if (!deposit.isInProgress() && inws)
{
verboseDescription.append("The deposit is finished: moving it from the workspace to the workflow");
verboseDescription
.append("The deposit is finished: moving it from the workspace to the workflow");
wft.startWorkflow(context, item);
}
if (deposit.isInProgress() && inarch)
{
verboseDescription.append("The deposit is not finished, and the item is already in the archive");
verboseDescription
.append("The deposit is not finished, and the item is already in the archive");
// throw new DSpaceSwordException("Invalid workflow state");
}
if (deposit.isInProgress() && inwf)
{
verboseDescription.append("The deposit is in progress, but is in the workflow; returning to the workspace");
verboseDescription
.append("The deposit is in progress, but is in the workflow; returning to the workspace");
wft.stopWorkflow(context, item);
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -15,10 +15,12 @@ public class WorkflowManagerFactory
public static WorkflowManager getInstance()
throws DSpaceSwordException, SwordError
{
WorkflowManager manager = (WorkflowManager) PluginManager.getSinglePlugin("swordv2-server", WorkflowManager.class);
WorkflowManager manager = (WorkflowManager) PluginManager
.getSinglePlugin("swordv2-server", WorkflowManager.class);
if (manager == null)
{
throw new SwordError(DSpaceUriRegistry.REPOSITORY_ERROR, "No workflow manager configured");
throw new SwordError(DSpaceUriRegistry.REPOSITORY_ERROR,
"No workflow manager configured");
}
return manager;
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -29,12 +29,14 @@ public class WorkflowManagerUnrestricted implements WorkflowManager
// do nothing - operation allowed
}
public void listCollectionContents(Context context, Collection collection) throws SwordError
public void listCollectionContents(Context context, Collection collection)
throws SwordError
{
// do nothing - operation allowed
}
public void createResource(Context context, Collection collection) throws SwordError
public void createResource(Context context, Collection collection)
throws SwordError
{
// do nothing - operation allowed
}
@@ -44,32 +46,38 @@ public class WorkflowManagerUnrestricted implements WorkflowManager
// do nothing - operation allowed
}
public void retrieveBitstream(Context context, Bitstream bitstream) throws SwordError, DSpaceSwordException
public void retrieveBitstream(Context context, Bitstream bitstream)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void replaceResourceContent(Context context, Item item) throws SwordError, DSpaceSwordException
public void replaceResourceContent(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void replaceMetadata(Context context, Item item) throws SwordError, DSpaceSwordException
public void replaceMetadata(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void replaceMetadataAndMediaResource(Context context, Item item) throws SwordError, DSpaceSwordException
public void replaceMetadataAndMediaResource(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void deleteMediaResource(Context context, Item item) throws SwordError, DSpaceSwordException
public void deleteMediaResource(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void deleteBitstream(Context context, Bitstream bitstream) throws SwordError, DSpaceSwordException
public void deleteBitstream(Context context, Bitstream bitstream)
throws SwordError, DSpaceSwordException
{
// this is equivalent to asking whether the media resource in the item can be deleted
try
@@ -78,9 +86,11 @@ public class WorkflowManagerUnrestricted implements WorkflowManager
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
// is the bitstream in the ORIGINAL bundle? If not, it can't be worked on
if (!Constants.CONTENT_BUNDLE_NAME.equals(bundleBitstream.getBundle().getName()))
if (!Constants.CONTENT_BUNDLE_NAME
.equals(bundleBitstream.getBundle().getName()))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The file is not in a bundle which can be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The file is not in a bundle which can be modified");
}
List<Item> items = bundleBitstream.getBundle().getItems();
@@ -106,9 +116,11 @@ public class WorkflowManagerUnrestricted implements WorkflowManager
for (BundleBitstream bundleBitstream : bundleBitstreams)
{
// is the bitstream in the ORIGINAL bundle? If not, it can't be worked on
if (!Constants.CONTENT_BUNDLE_NAME.equals(bundleBitstream.getBundle().getName()))
if (!Constants.CONTENT_BUNDLE_NAME
.equals(bundleBitstream.getBundle().getName()))
{
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED, "The file is not in a bundle which can be modified");
throw new SwordError(UriRegistry.ERROR_METHOD_NOT_ALLOWED,
"The file is not in a bundle which can be modified");
}
List<Item> items = bundleBitstream.getBundle().getItems();
@@ -124,38 +136,46 @@ public class WorkflowManagerUnrestricted implements WorkflowManager
}
}
public void addResourceContent(Context context, Item item) throws SwordError, DSpaceSwordException
public void addResourceContent(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void addMetadata(Context context, Item item) throws SwordError, DSpaceSwordException
public void addMetadata(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void deleteItem(Context context, Item item) throws SwordError, DSpaceSwordException
public void deleteItem(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void retrieveStatement(Context context, Item item) throws SwordError, DSpaceSwordException
public void retrieveStatement(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void modifyState(Context context, Item item) throws SwordError, DSpaceSwordException
public void modifyState(Context context, Item item)
throws SwordError, DSpaceSwordException
{
// do nothing - operation allowed
}
public void resolveState(Context context, Deposit deposit, DepositResult result, VerboseDescription verboseDescription)
public void resolveState(Context context, Deposit deposit,
DepositResult result, VerboseDescription verboseDescription)
throws DSpaceSwordException
{
this.resolveState(context, deposit, result, verboseDescription, true);
}
public void resolveState(Context context, Deposit deposit, DepositResult result, VerboseDescription verboseDescription, boolean containerOperation)
public void resolveState(Context context, Deposit deposit,
DepositResult result, VerboseDescription verboseDescription,
boolean containerOperation)
throws DSpaceSwordException
{
// the containerOperation flag tells us whether this method was called by an operation which happened on the
@@ -187,25 +207,29 @@ public class WorkflowManagerUnrestricted implements WorkflowManager
if (!deposit.isInProgress() && inarch)
{
verboseDescription.append("The deposit is finished, and the item is already in the archive");
verboseDescription
.append("The deposit is finished, and the item is already in the archive");
// throw new DSpaceSwordException("Invalid workflow state");
}
if (!deposit.isInProgress() && inws)
{
verboseDescription.append("The deposit is finished: moving it from the workspace to the workflow");
verboseDescription
.append("The deposit is finished: moving it from the workspace to the workflow");
wft.startWorkflow(context, item);
}
if (deposit.isInProgress() && inarch)
{
verboseDescription.append("The deposit is not finished, and the item is already in the archive");
verboseDescription
.append("The deposit is not finished, and the item is already in the archive");
// throw new DSpaceSwordException("Invalid workflow state");
}
if (deposit.isInProgress() && inwf)
{
verboseDescription.append("The deposit is in progress, but is in the workflow; returning to the workspace");
verboseDescription
.append("The deposit is in progress, but is in the workflow; returning to the workspace");
wft.stopWorkflow(context, item);
}
}

View File

@@ -2,7 +2,7 @@
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* <p>
* http://www.dspace.org/license/
*/
package org.dspace.sword2;
@@ -30,13 +30,20 @@ import java.sql.SQLException;
public class WorkflowTools
{
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory
.getInstance().getWorkspaceItemService();
protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowItemService();
protected BasicWorkflowService basicWorkflowService = BasicWorkflowServiceFactory.getInstance().getBasicWorkflowService();
protected BasicWorkflowItemService basicWorkflowItemService = BasicWorkflowServiceFactory
.getInstance().getBasicWorkflowItemService();
protected XmlWorkflowItemService xmlWorkflowItemService = XmlWorkflowServiceFactory.getInstance().getXmlWorkflowItemService();
protected XmlWorkflowService xmlWorkflowService = XmlWorkflowServiceFactory.getInstance().getXmlWorkflowService();
protected BasicWorkflowService basicWorkflowService = BasicWorkflowServiceFactory
.getInstance().getBasicWorkflowService();
protected XmlWorkflowItemService xmlWorkflowItemService = XmlWorkflowServiceFactory
.getInstance().getXmlWorkflowItemService();
protected XmlWorkflowService xmlWorkflowService = XmlWorkflowServiceFactory
.getInstance().getXmlWorkflowService();
/**
* Is the given item in the DSpace workflow?
@@ -53,10 +60,16 @@ public class WorkflowTools
{
try
{
if(ConfigurationManager.getProperty("workflow","workflow.framework").equals("xmlworkflow")){
if (ConfigurationManager
.getProperty("workflow", "workflow.framework")
.equals("xmlworkflow"))
{
return xmlWorkflowItemService.findByItem(context, item) != null;
}else{
return basicWorkflowItemService.findByItem(context, item) != null;
}
else
{
return basicWorkflowItemService.findByItem(context, item) !=
null;
}
}
catch (SQLException e)
@@ -103,9 +116,14 @@ public class WorkflowTools
{
try
{
if(ConfigurationManager.getProperty("workflow","workflow.framework").equals("xmlworkflow")){
if (ConfigurationManager
.getProperty("workflow", "workflow.framework")
.equals("xmlworkflow"))
{
return xmlWorkflowItemService.findByItem(context, item);
}else{
}
else
{
return basicWorkflowItemService.findByItem(context, item);
}
}
@@ -153,17 +171,29 @@ public class WorkflowTools
WorkspaceItem wsi = this.getWorkspaceItem(context, item);
// kick off the workflow
boolean notify = ConfigurationManager.getBooleanProperty("swordv2-server", "workflow.notify");
if (ConfigurationManager.getProperty("workflow", "workflow.framework").equals("xmlworkflow")) {
if (notify) {
boolean notify = ConfigurationManager
.getBooleanProperty("swordv2-server", "workflow.notify");
if (ConfigurationManager
.getProperty("workflow", "workflow.framework")
.equals("xmlworkflow"))
{
if (notify)
{
xmlWorkflowService.start(context, wsi);
} else {
}
else
{
xmlWorkflowService.startWithoutNotify(context, wsi);
}
} else {
if (notify) {
}
else
{
if (notify)
{
basicWorkflowService.start(context, wsi);
} else {
}
else
{
basicWorkflowService.startWithoutNotify(context, wsi);
}
}
@@ -191,11 +221,15 @@ public class WorkflowTools
// abort the workflow
if (wfi != null)
{
if(wfi instanceof BasicWorkflowItem)
if (wfi instanceof BasicWorkflowItem)
{
basicWorkflowService.abort(context, (BasicWorkflowItem) wfi, context.getCurrentUser());
}else{
xmlWorkflowService.abort(context, (XmlWorkflowItem) wfi, context.getCurrentUser());
basicWorkflowService.abort(context, (BasicWorkflowItem) wfi,
context.getCurrentUser());
}
else
{
xmlWorkflowService.abort(context, (XmlWorkflowItem) wfi,
context.getCurrentUser());
}
}
}