Merge pull request #1026 from LongsightGroup/DS-2701-rest

[DS-2701] REST API
Merging, still a few issues remaining but I will create a separate pull request for these.
This commit is contained in:
Kevin Van de Velde
2015-09-18 12:21:39 +02:00
17 changed files with 607 additions and 627 deletions

View File

@@ -1115,6 +1115,16 @@ public class ItemServiceImpl extends DSpaceObjectServiceImpl<Item> implements It
return itemDAO.countItems(context, collection, true, false);
}
@Override
public int countItems(Context context, Community community) throws SQLException {
List<Collection> collections = communityService.getAllCollections(context, community);
int itemCount = 0;
for(Collection collection : collections) {
itemCount += countItems(context, collection);
}
return itemCount;
}
@Override
protected void getAuthoritiesAndConfidences(String fieldKey, Collection collection, List<String> values, List<String> authorities, List<Integer> confidences, int i) {
Choices c = choiceAuthorityService.getBestMatch(fieldKey, values.get(i), collection, null);

View File

@@ -449,4 +449,11 @@ public interface ItemService extends DSpaceObjectService<Item>, DSpaceObjectLega
*/
public Iterator<Item> findByLastModifiedSince(Context context, Date last)
throws SQLException;
/**
* counts items in the given community
*
* @return total items
*/
public int countItems(Context context, Community community) throws SQLException;
}

View File

@@ -13,6 +13,7 @@ import java.net.URLConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
@@ -34,16 +35,21 @@ import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.authorize.service.ResourcePolicyService;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.eperson.Group;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.BundleService;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.GroupService;
import org.dspace.rest.common.Bitstream;
import org.dspace.rest.common.ResourcePolicy;
import org.dspace.rest.exceptions.ContextException;
import org.dspace.storage.bitstore.BitstreamStorageServiceImpl;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
import org.dspace.storage.bitstore.factory.StorageServiceFactory;
import org.dspace.storage.bitstore.service.BitstreamStorageService;
import org.dspace.usage.UsageEvent;
/**
@@ -54,6 +60,13 @@ import org.dspace.usage.UsageEvent;
@Path("/bitstreams")
public class BitstreamResource extends Resource
{
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected BitstreamStorageService bitstreamStorageService = StorageServiceFactory.getInstance().getBitstreamStorageService();
protected ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService();
protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
private static Logger log = Logger.getLogger(BitstreamResource.class);
@@ -85,7 +98,7 @@ public class BitstreamResource extends Resource
@GET
@Path("/{bitstream_id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Bitstream getBitstream(@PathParam("bitstream_id") Integer bitstreamId, @QueryParam("expand") String expand,
public Bitstream getBitstream(@PathParam("bitstream_id") String bitstreamId, @QueryParam("expand") String expand,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -103,7 +116,7 @@ public class BitstreamResource extends Resource
writeStats(dspaceBitstream, UsageEvent.Action.VIEW, user_ip, user_agent, xforwardedfor, headers,
request, context);
bitstream = new Bitstream(dspaceBitstream, expand);
bitstream = new Bitstream(dspaceBitstream, expand, context);
context.complete();
log.trace("Bitsream(id=" + bitstreamId + ") was successfully read.");
@@ -141,7 +154,7 @@ public class BitstreamResource extends Resource
@GET
@Path("/{bitstream_id}/policy")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ResourcePolicy[] getBitstreamPolicies(@PathParam("bitstream_id") Integer bitstreamId, @Context HttpHeaders headers)
public ResourcePolicy[] getBitstreamPolicies(@PathParam("bitstream_id") String bitstreamId, @Context HttpHeaders headers)
{
log.info("Reading bitstream(id=" + bitstreamId + ") policies.");
@@ -152,9 +165,9 @@ public class BitstreamResource extends Resource
{
context = createContext(getUser(headers));
org.dspace.content.Bitstream dspaceBitstream = findBitstream(context, bitstreamId, org.dspace.core.Constants.READ);
AuthorizeManager.getPolicies(context, dspaceBitstream);
policies = new Bitstream(dspaceBitstream,"policies").getPolicies();
List<org.dspace.authorize.ResourcePolicy> resourcePolicies = authorizeService.getPolicies(context, dspaceBitstream);
//TODO why isn't the above used...
policies = new Bitstream(dspaceBitstream,"policies", context).getPolicies();
context.complete();
log.trace("Policies for bitstream(id=" + bitstreamId + ") was successfully read.");
@@ -213,25 +226,25 @@ public class BitstreamResource extends Resource
try
{
context = createContext(getUser(headers));
org.dspace.content.Bitstream[] dspaceBitstreams = org.dspace.content.Bitstream.findAll(context);
List<org.dspace.content.Bitstream> dspaceBitstreams = bitstreamService.findAll(context);
if (!((limit != null) && (limit >= 0) && (offset != null) && (offset >= 0)))
{
log.warn("Pagging was badly set.");
log.warn("Paging was badly set.");
limit = 100;
offset = 0;
}
// TODO If bitstream doesn't exist, throws exception.
for (int i = offset; (i < (offset + limit)) && (i < dspaceBitstreams.length); i++)
for (int i = offset; (i < (offset + limit)) && (i < dspaceBitstreams.size()); i++)
{
if (AuthorizeServiceImpl.authorizeActionBoolean(context, dspaceBitstreams[i], org.dspace.core.Constants.READ))
if (authorizeService.authorizeActionBoolean(context, dspaceBitstreams.get(i), org.dspace.core.Constants.READ))
{
if (dspaceBitstreams[i].getParentObject() != null)
if (bitstreamService.getParentObject(context, dspaceBitstreams.get(i)) != null)
{ // To eliminate bitstreams which cause exception, because of
// reading under administrator permissions
bitstreams.add(new Bitstream(dspaceBitstreams[i], expand));
writeStats(dspaceBitstreams[i], UsageEvent.Action.VIEW, user_ip, user_agent,
bitstreams.add(new Bitstream(dspaceBitstreams.get(i), expand, context));
writeStats(dspaceBitstreams.get(i), UsageEvent.Action.VIEW, user_ip, user_agent,
xforwardedfor, headers, request, context);
}
}
@@ -281,7 +294,7 @@ public class BitstreamResource extends Resource
*/
@GET
@Path("/{bitstream_id}/retrieve")
public javax.ws.rs.core.Response getBitstreamData(@PathParam("bitstream_id") Integer bitstreamId,
public javax.ws.rs.core.Response getBitstreamData(@PathParam("bitstream_id") String bitstreamId,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -301,8 +314,8 @@ public class BitstreamResource extends Resource
request, context);
log.trace("Bitsream(id=" + bitstreamId + ") data was successfully read.");
inputStream = dspaceBitstream.retrieve();
type = dspaceBitstream.getFormat().getMIMEType();
inputStream = bitstreamService.retrieve(context, dspaceBitstream);
type = dspaceBitstream.getFormat(context).getMIMEType();
context.complete();
}
@@ -351,7 +364,7 @@ public class BitstreamResource extends Resource
@POST
@Path("/{bitstream_id}/policy")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public javax.ws.rs.core.Response addBitstreamPolicy(@PathParam("bitstream_id") Integer bitstreamId, ResourcePolicy policy,
public javax.ws.rs.core.Response addBitstreamPolicy(@PathParam("bitstream_id") String bitstreamId, ResourcePolicy policy,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -422,7 +435,7 @@ public class BitstreamResource extends Resource
@PUT
@Path("/{bitstream_id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateBitstream(@PathParam("bitstream_id") Integer bitstreamId, Bitstream bitstream,
public Response updateBitstream(@PathParam("bitstream_id") String bitstreamId, Bitstream bitstream,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -440,30 +453,33 @@ public class BitstreamResource extends Resource
headers, request, context);
log.trace("Updating bitstream metadata.");
dspaceBitstream.setDescription(bitstream.getDescription());
dspaceBitstream.setDescription(context, bitstream.getDescription());
if (getMimeType(bitstream.getName()) == null)
{
dspaceBitstream.setFormat(BitstreamFormat.findUnknown(context));
BitstreamFormat unknownFormat = bitstreamFormatService.findUnknown(context);
bitstreamService.setFormat(context, dspaceBitstream, unknownFormat);
}
else
{
dspaceBitstream.setFormat(BitstreamFormat.findByMIMEType(context, getMimeType(bitstream.getName())));
BitstreamFormat guessedFormat = bitstreamFormatService.findByMIMEType(context, getMimeType(bitstream.getName()));
bitstreamService.setFormat(context, dspaceBitstream, guessedFormat);
}
dspaceBitstream.setName(bitstream.getName());
dspaceBitstream.setName(context, bitstream.getName());
Integer sequenceId = bitstream.getSequenceId();
if (sequenceId != null && sequenceId.intValue() != -1)
{
dspaceBitstream.setSequenceID(sequenceId);
}
dspaceBitstream.update();
bitstreamService.update(context, dspaceBitstream);
if (bitstream.getPolicies() != null)
{
log.trace("Updating bitstream policies.");
// Remove all old bitstream policies.
AuthorizeManager.removeAllPolicies(context,dspaceBitstream);
authorizeService.removeAllPolicies(context,dspaceBitstream);
// Add all new bitstream policies
for (ResourcePolicy policy : bitstream.getPolicies()) {
@@ -524,7 +540,7 @@ public class BitstreamResource extends Resource
// TODO Change to better logic, without editing database.
@PUT
@Path("/{bitstream_id}/data")
public Response updateBitstreamData(@PathParam("bitstream_id") Integer bitstreamId, InputStream is,
public Response updateBitstreamData(@PathParam("bitstream_id") String bitstreamId, InputStream is,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -542,24 +558,9 @@ public class BitstreamResource extends Resource
headers, request, context);
log.trace("Creating new bitstream.");
int newBitstreamId = BitstreamStorageServiceImpl.store(context, is);
log.trace("Looking for table rows of bitstreams.");
TableRow originalBitstreamRow = DatabaseManager.find(context, "Bitstream", bitstreamId);
TableRow bitstream = DatabaseManager.find(context, "Bitstream", newBitstreamId);
log.trace("Changing new internal id with old internal id.");
String internal_id = originalBitstreamRow.getStringColumn("internal_id");
Long size_bytes = originalBitstreamRow.getLongColumn("size_bytes");
originalBitstreamRow.setColumn("internal_id", bitstream.getStringColumn("internal_id"));
originalBitstreamRow.setColumn("size_bytes", bitstream.getLongColumn("size_bytes"));
bitstream.setColumn("internal_id", internal_id);
bitstream.setColumn("size_bytes", size_bytes);
DatabaseManager.update(context, originalBitstreamRow);
BitstreamStorageServiceImpl.delete(context, newBitstreamId);
context.complete();
UUID newBitstreamId = bitstreamStorageService.store(context, dspaceBitstream, is);
log.trace("Bitstream data stored: " + newBitstreamId);
}
catch (SQLException e)
@@ -609,7 +610,7 @@ public class BitstreamResource extends Resource
*/
@DELETE
@Path("/{bitstream_id}")
public Response deleteBitstream(@PathParam("bitstream_id") Integer bitstreamId, @QueryParam("userIP") String user_ip,
public Response deleteBitstream(@PathParam("bitstream_id") String bitstreamId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -626,13 +627,7 @@ public class BitstreamResource extends Resource
headers, request, context);
log.trace("Deleting bitstream from all bundles.");
for (org.dspace.content.Bundle bundle : dspaceBitstream.getBundles())
{
org.dspace.content.Bundle.find(context, bundle.getID()).removeBitstream(dspaceBitstream);
}
context.complete();
bitstreamService.delete(context, dspaceBitstream);
}
catch (SQLException e)
{
@@ -675,7 +670,7 @@ public class BitstreamResource extends Resource
*/
@DELETE
@Path("/{bitstream_id}/policy/{policy_id}")
public javax.ws.rs.core.Response deleteBitstreamPolicy(@PathParam("bitstream_id") Integer bitstreamId,
public javax.ws.rs.core.Response deleteBitstreamPolicy(@PathParam("bitstream_id") String bitstreamId,
@PathParam("policy_id") Integer policyId, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -691,25 +686,17 @@ public class BitstreamResource extends Resource
writeStats(dspaceBitstream, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor, headers,
request, context);
// Check if resource policy exists in bitstream.
boolean found = false;
List<org.dspace.authorize.ResourcePolicy> policies = AuthorizeManager.getPolicies(context, dspaceBitstream);
for(org.dspace.authorize.ResourcePolicy policy : policies) {
if(policy.getID() == policyId) {
found = true;
break;
}
}
org.dspace.authorize.ResourcePolicy resourcePolicy = resourcePolicyService.find(context, policyId);
if(resourcePolicy.getdSpaceObject().getID() == dspaceBitstream.getID() && authorizeService.authorizeActionBoolean(context, dspaceBitstream, org.dspace.core.Constants.REMOVE)) {
if(found) {
removePolicyFromBitstream(context, policyId, bitstreamId);
} else {
context.abort();
throw new WebApplicationException(Response.Status.NOT_FOUND);
try {
resourcePolicyService.delete(context, resourcePolicy);
} catch (AuthorizeException e) {
processException("Someting went wrong while deleting policy(id=" + policyId + ") to bitstream(id=" + bitstreamId
+ "), AuthorizeException! Message: " + e, context);
}
context.complete();
log.trace("Policy for bitstream(id=" + bitstreamId + ") was successfully removed.");
}
}
catch (SQLException e)
@@ -751,30 +738,16 @@ public class BitstreamResource extends Resource
* @throws AuthorizeException
*/
private void addPolicyToBitstream(org.dspace.core.Context context, ResourcePolicy policy, org.dspace.content.Bitstream dspaceBitstream) throws SQLException, AuthorizeException {
org.dspace.authorize.ResourcePolicy dspacePolicy = org.dspace.authorize.ResourcePolicy.create(context);
org.dspace.authorize.ResourcePolicy dspacePolicy = resourcePolicyService.create(context);
dspacePolicy.setAction(policy.getActionInt());
dspacePolicy.setGroup(Group.find(context, policy.getGroupId()));
dspacePolicy.setResourceID(dspaceBitstream.getID());
dspacePolicy.setResource(dspaceBitstream);
dspacePolicy.setResourceType(org.dspace.core.Constants.BITSTREAM);
dspacePolicy.setGroup(groupService.findByIdOrLegacyId(context, policy.getGroupId()));
dspacePolicy.setdSpaceObject(dspaceBitstream);
dspacePolicy.setStartDate(policy.getStartDate());
dspacePolicy.setEndDate(policy.getEndDate());
dspacePolicy.setRpDescription(policy.getRpDescription());
dspacePolicy.setRpName(policy.getRpName());
dspacePolicy.update();
dspaceBitstream.updateLastModified();
}
/**
* Remove policy from bitstream. But only if resourceID of policy is same as bitstream id.
* @param context Context to delete policy.
* @param policyID Id of resource policy, which will be deleted.
* @param bitstreamID Id of bitstream.
* @throws SQLException
*/
private void removePolicyFromBitstream(org.dspace.core.Context context, int policyID, int bitstreamID) throws SQLException {
DatabaseManager.updateQuery(context, "DELETE FROM resourcepolicy WHERE POLICY_ID = ? AND RESOURCE_ID = ?", policyID,bitstreamID);
resourcePolicyService.update(context, dspacePolicy);
}
/**
@@ -793,21 +766,21 @@ public class BitstreamResource extends Resource
* Is thrown when item with passed id is not exists and if user
* has no permission to do passed action.
*/
private org.dspace.content.Bitstream findBitstream(org.dspace.core.Context context, int id, int action)
private org.dspace.content.Bitstream findBitstream(org.dspace.core.Context context, String id, int action)
throws WebApplicationException
{
org.dspace.content.Bitstream bitstream = null;
try
{
bitstream = org.dspace.content.Bitstream.find(context, id);
bitstream = bitstreamService.findByIdOrLegacyId(context, id);
if ((bitstream == null) || (bitstream.getParentObject() == null))
if ((bitstream == null) || (bitstreamService.getParentObject(context, bitstream) == null))
{
context.abort();
log.warn("Bitstream(id=" + id + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, bitstream, action))
else if (!authorizeService.authorizeActionBoolean(context, bitstream, action))
{
context.abort();
if (context.getCurrentUser() != null)

View File

@@ -10,6 +10,7 @@ package org.dspace.rest;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
@@ -31,10 +32,15 @@ import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.browse.BrowseException;
import org.dspace.content.InstallItemServiceImpl;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.InstallItemService;
import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.Constants;
import org.dspace.rest.common.Collection;
import org.dspace.rest.common.Item;
import org.dspace.rest.common.MetadataEntry;
@@ -49,6 +55,12 @@ import org.dspace.usage.UsageEvent;
@Path("/collections")
public class CollectionsResource extends Resource
{
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected WorkspaceItemService workspaceItemService = ContentServiceFactory.getInstance().getWorkspaceItemService();
protected InstallItemService installItemService = ContentServiceFactory.getInstance().getInstallItemService();
private static Logger log = Logger.getLogger(CollectionsResource.class);
/**
@@ -84,7 +96,7 @@ public class CollectionsResource extends Resource
@GET
@Path("/{collection_id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public org.dspace.rest.common.Collection getCollection(@PathParam("collection_id") Integer collectionId,
public org.dspace.rest.common.Collection getCollection(@PathParam("collection_id") String collectionId,
@QueryParam("expand") String expand, @QueryParam("limit") @DefaultValue("100") Integer limit,
@QueryParam("offset") @DefaultValue("0") Integer offset, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@@ -175,10 +187,10 @@ public class CollectionsResource extends Resource
offset = 0;
}
org.dspace.content.Collection[] dspaceCollections = org.dspace.content.Collection.findAll(context, limit, offset);
List<org.dspace.content.Collection> dspaceCollections = collectionService.findAll(context, limit, offset);
for(org.dspace.content.Collection dspaceCollection : dspaceCollections)
{
if (AuthorizeServiceImpl.authorizeActionBoolean(context, dspaceCollection, org.dspace.core.Constants.READ))
if (authorizeService.authorizeActionBoolean(context, dspaceCollection, org.dspace.core.Constants.READ))
{
Collection collection = new org.dspace.rest.common.Collection(dspaceCollection, null, context, limit,
offset);
@@ -239,7 +251,7 @@ public class CollectionsResource extends Resource
@GET
@Path("/{collection_id}/items")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public org.dspace.rest.common.Item[] getCollectionItems(@PathParam("collection_id") Integer collectionId,
public org.dspace.rest.common.Item[] getCollectionItems(@PathParam("collection_id") String collectionId,
@QueryParam("expand") String expand, @QueryParam("limit") @DefaultValue("100") Integer limit,
@QueryParam("offset") @DefaultValue("0") Integer offset, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@@ -259,13 +271,13 @@ public class CollectionsResource extends Resource
headers, request, context);
items = new ArrayList<Item>();
org.dspace.content.ItemIterator dspaceItems = dspaceCollection.getItems();
Iterator<org.dspace.content.Item> dspaceItems = itemService.findByCollection(context, dspaceCollection);
for (int i = 0; (dspaceItems.hasNext()) && (i < (limit + offset)); i++)
{
if (i >= offset)
{
org.dspace.content.Item dspaceItem = dspaceItems.next();
if (ItemService.isItemListedForUser(context, dspaceItem))
if (itemService.isItemListedForUser(context, dspaceItem))
{
items.add(new Item(dspaceItem, expand, context));
writeStats(dspaceItem, UsageEvent.Action.VIEW, user_ip, user_agent, xforwardedfor,
@@ -320,7 +332,7 @@ public class CollectionsResource extends Resource
@POST
@Path("/{collection_id}/items")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Item addCollectionItem(@PathParam("collection_id") Integer collectionId, Item item,
public Item addCollectionItem(@PathParam("collection_id") String collectionId, Item item,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -340,8 +352,7 @@ public class CollectionsResource extends Resource
headers, request, context);
log.trace("Creating item in collection(id=" + collectionId + ").");
org.dspace.content.WorkspaceItem workspaceItem = org.dspace.content.WorkspaceItem.create(context, dspaceCollection,
false);
org.dspace.content.WorkspaceItem workspaceItem = workspaceItemService.create(context, dspaceCollection, false);
org.dspace.content.Item dspaceItem = workspaceItem.getItem();
log.trace("Adding metadata to item(id=" + dspaceItem.getID() + ").");
@@ -350,17 +361,17 @@ public class CollectionsResource extends Resource
for (MetadataEntry entry : item.getMetadata())
{
String data[] = mySplit(entry.getKey());
dspaceItem.addMetadata(data[0], data[1], data[2], entry.getLanguage(), entry.getValue());
itemService.addMetadata(context, dspaceItem, data[0], data[1], data[2], entry.getLanguage(), entry.getValue());
}
}
workspaceItem.update();
// Index item to browse.
org.dspace.browse.IndexBrowse browse = new org.dspace.browse.IndexBrowse();
browse.indexItem(dspaceItem);
log.trace("Installing item to collection(id=" + collectionId + ").");
dspaceItem = InstallItemServiceImpl.installItem(context, workspaceItem);
dspaceItem = installItemService.installItem(context, workspaceItem);
workspaceItemService.update(context, workspaceItem);
returnItem = new Item(dspaceItem, "", context);
@@ -376,10 +387,6 @@ public class CollectionsResource extends Resource
processException("Could not add item into collection(id=" + collectionId + "), AuthorizeException. Message: " + e,
context);
}
catch (IOException e)
{
processException("Could not add item into collection(id=" + collectionId + "), IOException. Message: " + e, context);
}
catch (BrowseException e)
{
processException("Could not add item into browse index, BrowseException. Message: " + e, context);
@@ -421,7 +428,7 @@ public class CollectionsResource extends Resource
@PUT
@Path("/{collection_id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateCollection(@PathParam("collection_id") Integer collectionId,
public Response updateCollection(@PathParam("collection_id") String collectionId,
org.dspace.rest.common.Collection collection, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
@@ -439,14 +446,15 @@ public class CollectionsResource extends Resource
writeStats(dspaceCollection, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor,
headers, request, context);
dspaceCollection.setMetadata("name", collection.getName());
dspaceCollection.setLicense(collection.getLicense());
collectionService.setMetadata(context, dspaceCollection, "name", collection.getName());
collectionService.setMetadata(context, dspaceCollection, "license", collection.getLicense());
// dspaceCollection.setLogo(collection.getLogo()); // TODO Add this option.
dspaceCollection.setMetadata(org.dspace.content.Collection.COPYRIGHT_TEXT, collection.getCopyrightText());
dspaceCollection.setMetadata(org.dspace.content.Collection.INTRODUCTORY_TEXT, collection.getIntroductoryText());
dspaceCollection.setMetadata(org.dspace.content.Collection.SHORT_DESCRIPTION, collection.getShortDescription());
dspaceCollection.setMetadata(org.dspace.content.Collection.SIDEBAR_TEXT, collection.getSidebarText());
dspaceCollection.update();
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.COPYRIGHT_TEXT, collection.getCopyrightText());
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.INTRODUCTORY_TEXT, collection.getIntroductoryText());
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.SHORT_DESCRIPTION, collection.getShortDescription());
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.SIDEBAR_TEXT, collection.getSidebarText());
collectionService.update(context, dspaceCollection);
context.complete();
@@ -459,12 +467,9 @@ public class CollectionsResource extends Resource
catch (SQLException e)
{
processException("Could not update collection(id=" + collectionId + "), SQLException. Message: " + e, context);
}
catch (AuthorizeException e)
{
} catch (AuthorizeException e) {
processException("Could not update collection(id=" + collectionId + "), AuthorizeException. Message: " + e, context);
}
finally
} finally
{
processFinally(context);
}
@@ -494,7 +499,7 @@ public class CollectionsResource extends Resource
@DELETE
@Path("/{collection_id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response deleteCollection(@PathParam("collection_id") Integer collectionId, @QueryParam("userIP") String user_ip,
public Response deleteCollection(@PathParam("collection_id") String collectionId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -511,16 +516,13 @@ public class CollectionsResource extends Resource
writeStats(dspaceCollection, UsageEvent.Action.REMOVE, user_ip, user_agent, xforwardedfor,
headers, request, context);
org.dspace.content.Community community = (org.dspace.content.Community) dspaceCollection.getParentObject();
community.removeCollection(dspaceCollection);
context.complete();
collectionService.delete(context, dspaceCollection);
collectionService.update(context, dspaceCollection);
}
catch (ContextException e)
{
processException(
"Could not delete collection(id=" + collectionId + "), ContextExcpetion. Message: " + e.getMessage(), context);
"Could not delete collection(id=" + collectionId + "), ContextException. Message: " + e.getMessage(), context);
}
catch (SQLException e)
{
@@ -565,7 +567,7 @@ public class CollectionsResource extends Resource
@DELETE
@Path("/{collection_id}/items/{item_id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response deleteCollectionItem(@PathParam("collection_id") Integer collectionId, @PathParam("item_id") Integer itemId,
public Response deleteCollectionItem(@PathParam("collection_id") String collectionId, @PathParam("item_id") String itemId,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -577,32 +579,29 @@ public class CollectionsResource extends Resource
try
{
context = createContext(getUser(headers));
org.dspace.content.Collection dspaceCollection = findCollection(context, collectionId,
org.dspace.core.Constants.WRITE);
org.dspace.content.Item item = null;
org.dspace.content.ItemIterator dspaceItems = dspaceCollection.getItems();
while (dspaceItems.hasNext())
{
org.dspace.content.Item dspaceItem = dspaceItems.next();
if (dspaceItem.getID() == itemId)
{
item = dspaceItem;
}
org.dspace.content.Collection dspaceCollection = collectionService.findByIdOrLegacyId(context, collectionId);
org.dspace.content.Item item = itemService.findByIdOrLegacyId(context, itemId);
if(dspaceCollection == null) {
//throw collection not exist
log.warn("Collection(id=" + itemId + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
if (item == null)
{
context.abort();
if(item == null) {
//throw item not exist
log.warn("Item(id=" + itemId + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, item, org.dspace.core.Constants.REMOVE))
{
context.abort();
if(!authorizeService.authorizeActionBoolean(context, item, Constants.REMOVE)
|| !authorizeService.authorizeActionBoolean(context, dspaceCollection, Constants.REMOVE)) {
//throw auth
if (context.getCurrentUser() != null)
{
log.error("User(" + context.getCurrentUser().getEmail() + ") has not permission to delete item!");
log.error("User(" + context.getCurrentUser().getEmail() + ") does not have permission to delete item!");
}
else
{
@@ -611,12 +610,14 @@ public class CollectionsResource extends Resource
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
collectionService.removeItem(context, dspaceCollection, item);
collectionService.update(context, dspaceCollection);
itemService.update(context, item);
writeStats(dspaceCollection, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor,
headers, request, context);
writeStats(item, UsageEvent.Action.REMOVE, user_ip, user_agent, xforwardedfor, headers, request, context);
dspaceCollection.removeItem(item);
context.complete();
}
@@ -675,13 +676,13 @@ public class CollectionsResource extends Resource
try
{
context = createContext(getUser(headers));
org.dspace.content.Collection[] dspaceCollections;
dspaceCollections = org.dspace.content.Collection.findAll(context);
List<org.dspace.content.Collection> dspaceCollections = collectionService.findAll(context);
//TODO, this would be more efficient with a findByName query
for (org.dspace.content.Collection dspaceCollection : dspaceCollections)
{
if (AuthorizeServiceImpl.authorizeActionBoolean(context, dspaceCollection, org.dspace.core.Constants.READ))
if (authorizeService.authorizeActionBoolean(context, dspaceCollection, org.dspace.core.Constants.READ))
{
if (dspaceCollection.getName().equals(name))
{
@@ -736,13 +737,13 @@ public class CollectionsResource extends Resource
* Is thrown when item with passed id is not exists and if user
* has no permission to do passed action.
*/
private org.dspace.content.Collection findCollection(org.dspace.core.Context context, int id, int action)
private org.dspace.content.Collection findCollection(org.dspace.core.Context context, String id, int action)
throws WebApplicationException
{
org.dspace.content.Collection collection = null;
try
{
collection = org.dspace.content.Collection.find(context, id);
collection = collectionService.findByIdOrLegacyId(context, id);
if (collection == null)
{
@@ -750,7 +751,7 @@ public class CollectionsResource extends Resource
log.warn("Collection(id=" + id + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, collection, action))
else if (!authorizeService.authorizeActionBoolean(context, collection, action))
{
context.abort();
if (context.getCurrentUser() != null)

View File

@@ -7,35 +7,30 @@
*/
package org.dspace.rest;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService;
import org.dspace.eperson.EPerson;
import org.dspace.rest.common.Collection;
import org.dspace.rest.common.Community;
import org.dspace.rest.exceptions.ContextException;
import org.dspace.usage.UsageEvent;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Class which provides CRUD methods over communities.
*
@@ -45,6 +40,10 @@ import org.dspace.usage.UsageEvent;
@Path("/communities")
public class CommunitiesResource extends Resource
{
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
private static Logger log = Logger.getLogger(CommunitiesResource.class);
/**
@@ -71,7 +70,7 @@ public class CommunitiesResource extends Resource
@GET
@Path("/{community_id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Community getCommunity(@PathParam("community_id") Integer communityId, @QueryParam("expand") String expand,
public Community getCommunity(@PathParam("community_id") String communityId, @QueryParam("expand") String expand,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -151,7 +150,7 @@ public class CommunitiesResource extends Resource
{
context = createContext(getUser(headers));
org.dspace.content.Community[] dspaceCommunities = org.dspace.content.Community.findAll(context);
List<org.dspace.content.Community> dspaceCommunities = communityService.findAll(context);
communities = new ArrayList<Community>();
if (!((limit != null) && (limit >= 0) && (offset != null) && (offset >= 0)))
@@ -161,12 +160,12 @@ public class CommunitiesResource extends Resource
offset = 0;
}
for (int i = offset; (i < (offset + limit)) && i < dspaceCommunities.length; i++)
for (int i = offset; (i < (offset + limit)) && i < dspaceCommunities.size(); i++)
{
if (AuthorizeServiceImpl.authorizeActionBoolean(context, dspaceCommunities[i], org.dspace.core.Constants.READ))
if (authorizeService.authorizeActionBoolean(context, dspaceCommunities.get(i), org.dspace.core.Constants.READ))
{
Community community = new Community(dspaceCommunities[i], expand, context);
writeStats(dspaceCommunities[i], UsageEvent.Action.VIEW, user_ip, user_agent,
Community community = new Community(dspaceCommunities.get(i), expand, context);
writeStats(dspaceCommunities.get(i), UsageEvent.Action.VIEW, user_ip, user_agent,
xforwardedfor, headers, request, context);
communities.add(community);
}
@@ -233,22 +232,22 @@ public class CommunitiesResource extends Resource
{
context = createContext(getUser(headers));
org.dspace.content.Community[] dspaceCommunities = org.dspace.content.Community.findAllTop(context);
List<org.dspace.content.Community> dspaceCommunities = communityService.findAllTop(context);
communities = new ArrayList<Community>();
if (!((limit != null) && (limit >= 0) && (offset != null) && (offset >= 0)))
{
log.warn("Pagging was badly set, using default values.");
log.warn("Paging was badly set, using default values.");
limit = 100;
offset = 0;
}
for (int i = offset; (i < (offset + limit)) && i < dspaceCommunities.length; i++)
for (int i = offset; (i < (offset + limit)) && i < dspaceCommunities.size(); i++)
{
if (AuthorizeServiceImpl.authorizeActionBoolean(context, dspaceCommunities[i], org.dspace.core.Constants.READ))
if (authorizeService.authorizeActionBoolean(context, dspaceCommunities.get(i), org.dspace.core.Constants.READ))
{
Community community = new Community(dspaceCommunities[i], expand, context);
writeStats(dspaceCommunities[i], UsageEvent.Action.VIEW, user_ip, user_agent,
Community community = new Community(dspaceCommunities.get(i), expand, context);
writeStats(dspaceCommunities.get(i), UsageEvent.Action.VIEW, user_ip, user_agent,
xforwardedfor, headers, request, context);
communities.add(community);
}
@@ -300,7 +299,7 @@ public class CommunitiesResource extends Resource
@GET
@Path("/{community_id}/collections")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Collection[] getCommunityCollections(@PathParam("community_id") Integer communityId,
public Collection[] getCommunityCollections(@PathParam("community_id") String communityId,
@QueryParam("expand") String expand, @QueryParam("limit") @DefaultValue("100") Integer limit,
@QueryParam("offset") @DefaultValue("0") Integer offset, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@@ -327,13 +326,13 @@ public class CommunitiesResource extends Resource
}
collections = new ArrayList<Collection>();
org.dspace.content.Collection[] dspaceCollections = dspaceCommunity.getCollections();
for (int i = offset; (i < (offset + limit)) && (i < dspaceCollections.length); i++)
List<org.dspace.content.Collection> dspaceCollections = dspaceCommunity.getCollections();
for (int i = offset; (i < (offset + limit)) && (i < dspaceCollections.size()); i++)
{
if (AuthorizeServiceImpl.authorizeActionBoolean(context, dspaceCollections[i], org.dspace.core.Constants.READ))
if (authorizeService.authorizeActionBoolean(context, dspaceCollections.get(i), org.dspace.core.Constants.READ))
{
collections.add(new Collection(dspaceCollections[i], expand, context, 20, 0));
writeStats(dspaceCollections[i], UsageEvent.Action.VIEW, user_ip, user_agent,
collections.add(new Collection(dspaceCollections.get(i), expand, context, 20, 0));
writeStats(dspaceCollections.get(i), UsageEvent.Action.VIEW, user_ip, user_agent,
xforwardedfor, headers, request, context);
}
}
@@ -386,7 +385,7 @@ public class CommunitiesResource extends Resource
@GET
@Path("/{community_id}/communities")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Community[] getCommunityCommunities(@PathParam("community_id") Integer communityId,
public Community[] getCommunityCommunities(@PathParam("community_id") String communityId,
@QueryParam("expand") String expand, @QueryParam("limit") @DefaultValue("20") Integer limit,
@QueryParam("offset") @DefaultValue("0") Integer offset, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@@ -413,13 +412,13 @@ public class CommunitiesResource extends Resource
}
communities = new ArrayList<Community>();
org.dspace.content.Community[] dspaceCommunities = dspaceCommunity.getSubcommunities();
for (int i = offset; (i < (offset + limit)) && (i < dspaceCommunities.length); i++)
List<org.dspace.content.Community> dspaceCommunities = dspaceCommunity.getSubcommunities();
for (int i = offset; (i < (offset + limit)) && (i < dspaceCommunities.size()); i++)
{
if (AuthorizeServiceImpl.authorizeActionBoolean(context, dspaceCommunities[i], org.dspace.core.Constants.READ))
if (authorizeService.authorizeActionBoolean(context, dspaceCommunities.get(i), org.dspace.core.Constants.READ))
{
communities.add(new Community(dspaceCommunities[i], expand, context));
writeStats(dspaceCommunities[i], UsageEvent.Action.VIEW, user_ip, user_agent,
communities.add(new Community(dspaceCommunities.get(i), expand, context));
writeStats(dspaceCommunities.get(i), UsageEvent.Action.VIEW, user_ip, user_agent,
xforwardedfor, headers, request, context);
}
}
@@ -474,9 +473,9 @@ public class CommunitiesResource extends Resource
try
{
context = createContext(getUser(headers));
if (!AuthorizeServiceImpl.isAdmin(context))
EPerson eperson = getUser(headers);
context = createContext(eperson);
if (!authorizeService.isAdmin(context))
{
context.abort();
String user = "anonymous";
@@ -488,20 +487,19 @@ public class CommunitiesResource extends Resource
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
org.dspace.content.Community dspaceCommunity = org.dspace.content.Community.create(null, context);
org.dspace.content.Community dspaceCommunity = communityService.create(null, context);
writeStats(dspaceCommunity, UsageEvent.Action.CREATE, user_ip, user_agent, xforwardedfor,
headers, request, context);
dspaceCommunity.setMetadata("name", community.getName());
dspaceCommunity.setMetadata(org.dspace.content.Community.COPYRIGHT_TEXT, community.getCopyrightText());
dspaceCommunity.setMetadata(org.dspace.content.Community.INTRODUCTORY_TEXT, community.getIntroductoryText());
dspaceCommunity.setMetadata(org.dspace.content.Community.SHORT_DESCRIPTION, community.getShortDescription());
dspaceCommunity.setMetadata(org.dspace.content.Community.SIDEBAR_TEXT, community.getSidebarText());
dspaceCommunity.update();
communityService.setMetadata(context, dspaceCommunity, "name", community.getName());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.COPYRIGHT_TEXT, community.getCopyrightText());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.INTRODUCTORY_TEXT, community.getIntroductoryText());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.SHORT_DESCRIPTION, community.getShortDescription());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.SIDEBAR_TEXT, community.getSidebarText());
communityService.update(context, dspaceCommunity);
retCommunity = new Community(dspaceCommunity, "", context);
context.complete();
}
catch (SQLException e)
{
@@ -547,7 +545,7 @@ public class CommunitiesResource extends Resource
@POST
@Path("/{community_id}/collections")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Collection addCommunityCollection(@PathParam("community_id") Integer communityId, Collection collection,
public Collection addCommunityCollection(@PathParam("community_id") String communityId, Collection collection,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -560,23 +558,20 @@ public class CommunitiesResource extends Resource
try
{
context = createContext(getUser(headers));
org.dspace.content.Community dspaceCommunity = findCommunity(context, communityId, org.dspace.core.Constants.WRITE);
org.dspace.content.Community dspaceCommunity = findCommunity(context, communityId, org.dspace.core.Constants.WRITE);
writeStats(dspaceCommunity, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor,
headers, request, context);
org.dspace.content.Collection dspaceCollection = dspaceCommunity.createCollection();
dspaceCollection.setLicense(collection.getLicense());
org.dspace.content.Collection dspaceCollection = collectionService.create(context, dspaceCommunity);
collectionService.setMetadata(context, dspaceCollection, "license", collection.getLicense());
// dspaceCollection.setLogo(collection.getLogo()); // TODO Add this option.
dspaceCollection.setMetadata("name", collection.getName());
dspaceCollection.setMetadata(org.dspace.content.Collection.COPYRIGHT_TEXT, collection.getCopyrightText());
dspaceCollection.setMetadata(org.dspace.content.Collection.INTRODUCTORY_TEXT, collection.getIntroductoryText());
dspaceCollection.setMetadata(org.dspace.content.Collection.SHORT_DESCRIPTION, collection.getShortDescription());
dspaceCollection.setMetadata(org.dspace.content.Collection.SIDEBAR_TEXT, collection.getSidebarText());
dspaceCollection.setLicense(collection.getLicense());
dspaceCollection.update();
dspaceCommunity.update();
collectionService.setMetadata(context, dspaceCollection, "name", collection.getName());
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.COPYRIGHT_TEXT, collection.getCopyrightText());
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.INTRODUCTORY_TEXT, collection.getIntroductoryText());
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.SHORT_DESCRIPTION, collection.getShortDescription());
collectionService.setMetadata(context, dspaceCollection, org.dspace.content.Collection.SIDEBAR_TEXT, collection.getSidebarText());
collectionService.update(context, dspaceCollection);
communityService.update(context, dspaceCommunity);
retCollection = new Collection(dspaceCollection, "", context, 100, 0);
context.complete();
@@ -631,7 +626,7 @@ public class CommunitiesResource extends Resource
@POST
@Path("/{community_id}/communities")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Community addCommunityCommunity(@PathParam("community_id") Integer communityId, Community community,
public Community addCommunityCommunity(@PathParam("community_id") String communityId, Community community,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -650,14 +645,14 @@ public class CommunitiesResource extends Resource
writeStats(dspaceParentCommunity, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor,
headers, request, context);
org.dspace.content.Community dspaceCommunity = org.dspace.content.Community.create(dspaceParentCommunity, context);
dspaceCommunity.setMetadata("name", community.getName());
dspaceCommunity.setMetadata(org.dspace.content.Community.COPYRIGHT_TEXT, community.getCopyrightText());
dspaceCommunity.setMetadata(org.dspace.content.Community.INTRODUCTORY_TEXT, community.getIntroductoryText());
dspaceCommunity.setMetadata(org.dspace.content.Community.SHORT_DESCRIPTION, community.getShortDescription());
dspaceCommunity.setMetadata(org.dspace.content.Community.SIDEBAR_TEXT, community.getSidebarText());
dspaceCommunity.update();
dspaceParentCommunity.update();
org.dspace.content.Community dspaceCommunity = communityService.createSubcommunity(context, dspaceParentCommunity);
communityService.setMetadata(context, dspaceCommunity, "name", community.getName());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.COPYRIGHT_TEXT, community.getCopyrightText());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.INTRODUCTORY_TEXT, community.getIntroductoryText());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.SHORT_DESCRIPTION, community.getShortDescription());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.SIDEBAR_TEXT, community.getSidebarText());
communityService.update(context, dspaceCommunity);
communityService.update(context, dspaceParentCommunity);
retCommunity = new Community(dspaceCommunity, "", context);
context.complete();
@@ -711,7 +706,7 @@ public class CommunitiesResource extends Resource
@PUT
@Path("/{community_id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateCommunity(@PathParam("community_id") Integer communityId, Community community,
public Response updateCommunity(@PathParam("community_id") String communityId, Community community,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -729,13 +724,12 @@ public class CommunitiesResource extends Resource
headers, request, context);
// dspaceCommunity.setLogo(arg0); // TODO Add this option.
dspaceCommunity.setMetadata("name", community.getName());
dspaceCommunity.setMetadata(org.dspace.content.Community.COPYRIGHT_TEXT, community.getCopyrightText());
dspaceCommunity.setMetadata(org.dspace.content.Community.INTRODUCTORY_TEXT, community.getIntroductoryText());
dspaceCommunity.setMetadata(org.dspace.content.Community.SHORT_DESCRIPTION, community.getShortDescription());
dspaceCommunity.setMetadata(org.dspace.content.Community.SIDEBAR_TEXT, community.getSidebarText());
dspaceCommunity.update();
communityService.setMetadata(context, dspaceCommunity, "name", community.getName());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.COPYRIGHT_TEXT, community.getCopyrightText());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.INTRODUCTORY_TEXT, community.getIntroductoryText());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.SHORT_DESCRIPTION, community.getShortDescription());
communityService.setMetadata(context, dspaceCommunity, org.dspace.content.Community.SIDEBAR_TEXT, community.getSidebarText());
communityService.update(context, dspaceCommunity);
context.complete();
}
@@ -746,12 +740,9 @@ public class CommunitiesResource extends Resource
catch (ContextException e)
{
processException("Could not update community(id=" + communityId + "), ContextException Message:" + e, context);
}
catch (AuthorizeException e)
{
processException("Could not update community(id=" + communityId + "), AuthorizeException. Message:" + e, context);
}
finally
} catch (AuthorizeException e) {
processException("Could not update community(id=" + communityId + "), AuthorizeException Message:" + e, context);
} finally
{
processFinally(context);
}
@@ -779,7 +770,7 @@ public class CommunitiesResource extends Resource
*/
@DELETE
@Path("/{community_id}")
public Response deleteCommunity(@PathParam("community_id") Integer communityId, @QueryParam("userIP") String user_ip,
public Response deleteCommunity(@PathParam("community_id") String communityId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -795,7 +786,8 @@ public class CommunitiesResource extends Resource
writeStats(community, UsageEvent.Action.DELETE, user_ip, user_agent, xforwardedfor, headers,
request, context);
community.delete();
communityService.delete(context, community);
communityService.update(context, community);
context.complete();
}
@@ -848,8 +840,8 @@ public class CommunitiesResource extends Resource
*/
@DELETE
@Path("/{community_id}/collections/{collection_id}")
public Response deleteCommunityCollection(@PathParam("community_id") Integer communityId,
@PathParam("collection_id") Integer collectionId, @QueryParam("userIP") String user_ip,
public Response deleteCommunityCollection(@PathParam("community_id") String communityId,
@PathParam("collection_id") String collectionId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -862,15 +854,7 @@ public class CommunitiesResource extends Resource
context = createContext(getUser(headers));
org.dspace.content.Community community = findCommunity(context, communityId, org.dspace.core.Constants.WRITE);
org.dspace.content.Collection collection = null;
for (org.dspace.content.Collection dspaceCollection : community.getAllCollections())
{
if (dspaceCollection.getID() == collectionId)
{
collection = dspaceCollection;
break;
}
}
org.dspace.content.Collection collection = collectionService.findByIdOrLegacyId(context, collectionId);
if (collection == null)
{
@@ -878,7 +862,7 @@ public class CommunitiesResource extends Resource
log.warn("Collection(id=" + collectionId + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, collection, org.dspace.core.Constants.REMOVE))
else if (!authorizeService.authorizeActionBoolean(context, collection, org.dspace.core.Constants.REMOVE))
{
context.abort();
if (context.getCurrentUser() != null)
@@ -892,13 +876,15 @@ public class CommunitiesResource extends Resource
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
communityService.removeCollection(context, community, collection);
communityService.update(context, community);
collectionService.update(context, collection);
writeStats(community, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor, headers,
request, context);
writeStats(collection, UsageEvent.Action.DELETE, user_ip, user_agent, xforwardedfor, headers,
request, context);
community.removeCollection(collection);
context.complete();
}
@@ -954,8 +940,8 @@ public class CommunitiesResource extends Resource
*/
@DELETE
@Path("/{community_id}/communities/{community_id2}")
public Response deleteCommunityCommunity(@PathParam("community_id") Integer parentCommunityId,
@PathParam("community_id2") Integer subcommunityId, @QueryParam("userIP") String user_ip,
public Response deleteCommunityCommunity(@PathParam("community_id") String parentCommunityId,
@PathParam("community_id2") String subcommunityId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -969,15 +955,7 @@ public class CommunitiesResource extends Resource
org.dspace.content.Community parentCommunity = findCommunity(context, parentCommunityId,
org.dspace.core.Constants.WRITE);
org.dspace.content.Community subcommunity = null;
for (org.dspace.content.Community dspaceCommunity : parentCommunity.getSubcommunities())
{
if (dspaceCommunity.getID() == subcommunityId)
{
subcommunity = dspaceCommunity;
break;
}
}
org.dspace.content.Community subcommunity = communityService.findByIdOrLegacyId(context, subcommunityId);
if (subcommunity == null)
{
@@ -985,7 +963,7 @@ public class CommunitiesResource extends Resource
log.warn("Subcommunity(id=" + subcommunityId + ") in community(id=" + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, subcommunity, org.dspace.core.Constants.REMOVE))
else if (!authorizeService.authorizeActionBoolean(context, subcommunity, org.dspace.core.Constants.REMOVE))
{
context.abort();
if (context.getCurrentUser() != null)
@@ -999,12 +977,15 @@ public class CommunitiesResource extends Resource
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
communityService.removeSubcommunity(context, parentCommunity, subcommunity);
communityService.update(context, parentCommunity);
communityService.update(context, subcommunity);
writeStats(parentCommunity, UsageEvent.Action.UPDATE, user_ip, user_agent, xforwardedfor,
headers, request, context);
writeStats(subcommunity, UsageEvent.Action.DELETE, user_ip, user_agent, xforwardedfor, headers,
request, context);
parentCommunity.removeSubcommunity(subcommunity);
context.complete();
}
@@ -1026,7 +1007,7 @@ public class CommunitiesResource extends Resource
catch (ContextException e)
{
processException("Could not delete subcommunity(id=" + subcommunityId + ") in community(id=" + parentCommunityId
+ "), ContextExcpetion. Message:" + e.getMessage(), context);
+ "), ContextException. Message:" + e.getMessage(), context);
}
finally
{
@@ -1054,13 +1035,13 @@ public class CommunitiesResource extends Resource
* Is thrown when item with passed id is not exists and if user
* has no permission to do passed action.
*/
private org.dspace.content.Community findCommunity(org.dspace.core.Context context, int id, int action)
private org.dspace.content.Community findCommunity(org.dspace.core.Context context, String id, int action)
throws WebApplicationException
{
org.dspace.content.Community community = null;
try
{
community = org.dspace.content.Community.find(context, id);
community = communityService.findByIdOrLegacyId(context, id);
if (community == null)
{
@@ -1068,7 +1049,7 @@ public class CommunitiesResource extends Resource
log.warn("Community(id=" + id + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, community, action))
else if (!authorizeService.authorizeActionBoolean(context, community, action))
{
context.abort();
if (context.getCurrentUser() != null)

View File

@@ -8,16 +8,21 @@
package org.dspace.rest;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.DSpaceObjectService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.handle.HandleServiceImpl;
import org.dspace.handle.factory.HandleServiceFactory;
import org.dspace.handle.service.HandleService;
import org.dspace.rest.common.Collection;
import org.dspace.rest.common.Community;
import org.dspace.rest.common.DSpaceObject;
import org.dspace.rest.common.Item;
import org.dspace.rest.exceptions.ContextException;
import javax.ws.rs.*;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.sql.SQLException;
@@ -30,37 +35,43 @@ import java.sql.SQLException;
* To change this template use File | Settings | File Templates.
*/
@Path("/handle")
public class HandleResource {
public class HandleResource extends Resource {
protected HandleService handleService = HandleServiceFactory.getInstance().getHandleService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
private static Logger log = Logger.getLogger(HandleResource.class);
private static org.dspace.core.Context context;
@GET
@Path("/{prefix}/{suffix}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public org.dspace.rest.common.DSpaceObject getObject(@PathParam("prefix") String prefix, @PathParam("suffix") String suffix, @QueryParam("expand") String expand) {
public org.dspace.rest.common.DSpaceObject getObject(@PathParam("prefix") String prefix, @PathParam("suffix") String suffix, @QueryParam("expand") String expand, @javax.ws.rs.core.Context HttpHeaders headers) {
DSpaceObject dSpaceObject = new DSpaceObject();
try {
if(context == null || !context.isValid() ) {
context = new Context();
//Failed SQL is ignored as a failed SQL statement, prevent: current transaction is aborted, commands ignored until end of transaction block
context.getDBConnection().setAutoCommit(true);
}
context = createContext(getUser(headers));
org.dspace.content.DSpaceObject dso = handleService.resolveToObject(context, prefix + "/" + suffix);
org.dspace.content.DSpaceObject dso = HandleServiceImpl.resolveToObject(context, prefix + "/" + suffix);
if(dso == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
log.info("DSO Lookup by handle: [" + prefix + "] / [" + suffix + "] got result of: " + dso.getTypeText() + "_" + dso.getID());
DSpaceObjectService dSpaceObjectService = ContentServiceFactory.getInstance().getDSpaceObjectService(dso);
log.info("DSO Lookup by handle: [" + prefix + "] / [" + suffix + "] got result of: " + dSpaceObjectService.getTypeText(dso) + "_" + dso.getID());
if(AuthorizeServiceImpl.authorizeActionBoolean(context, dso, org.dspace.core.Constants.READ)) {
if(authorizeService.authorizeActionBoolean(context, dso, org.dspace.core.Constants.READ)) {
switch(dso.getType()) {
case Constants.COMMUNITY:
return new Community((org.dspace.content.Community) dso, expand, context);
dSpaceObject = new Community((org.dspace.content.Community) dso, expand, context);
return dSpaceObject;
case Constants.COLLECTION:
return new Collection((org.dspace.content.Collection) dso, expand, context, null, null);
dSpaceObject = new Collection((org.dspace.content.Collection) dso, expand, context, null, null);
return dSpaceObject;
case Constants.ITEM:
return new Item((org.dspace.content.Item) dso, expand, context);
dSpaceObject = new Item((org.dspace.content.Item) dso, expand, context);
return dSpaceObject;
default:
return new DSpaceObject(dso);
dSpaceObject = new DSpaceObject(dso);
return dSpaceObject;
}
} else {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
@@ -68,6 +79,16 @@ public class HandleResource {
} catch (SQLException e) {
log.error(e.getMessage());
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
} catch (ContextException e)
{
processException("Could not read handle(prefix=" + prefix + "), (suffix=" + suffix + ") ContextException. Message:" + e.getMessage(),
context);
} finally
{
processFinally(context);
}
//Not sure where I was missing a return..
return dSpaceObject;
}
}

View File

@@ -7,47 +7,37 @@
*/
package org.dspace.rest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.authorize.service.ResourcePolicyService;
import org.dspace.content.Bundle;
import org.dspace.content.BundleBitstream;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.*;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.GroupService;
import org.dspace.rest.common.Bitstream;
import org.dspace.rest.common.Item;
import org.dspace.rest.common.MetadataEntry;
import org.dspace.rest.exceptions.ContextException;
import org.dspace.usage.UsageEvent;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.content.BitstreamFormat;
import org.dspace.content.Bundle;
import org.dspace.content.ItemIterator;
import org.dspace.content.Metadatum;
import org.dspace.content.service.ItemService;
import org.dspace.eperson.Group;
import org.dspace.rest.common.Bitstream;
import org.dspace.rest.common.Item;
import org.dspace.rest.common.MetadataEntry;
import org.dspace.rest.exceptions.ContextException;
import org.dspace.storage.rdbms.TableRow;
import org.dspace.storage.rdbms.TableRowIterator;
import org.dspace.usage.UsageEvent;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/**
* Class which provide all CRUD methods over items.
@@ -60,6 +50,14 @@ import org.dspace.usage.UsageEvent;
@Path("/items")
public class ItemsResource extends Resource
{
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BitstreamFormatService bitstreamFormatService = ContentServiceFactory.getInstance().getBitstreamFormatService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
protected ResourcePolicyService resourcePolicyService = AuthorizeServiceFactory.getInstance().getResourcePolicyService();
protected GroupService groupService = EPersonServiceFactory.getInstance().getGroupService();
private static final Logger log = Logger.getLogger(ItemsResource.class);
@@ -90,7 +88,7 @@ public class ItemsResource extends Resource
@GET
@Path("/{item_id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Item getItem(@PathParam("item_id") Integer itemId, @QueryParam("expand") String expand,
public Item getItem(@PathParam("item_id") String itemId, @QueryParam("expand") String expand,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -164,12 +162,12 @@ public class ItemsResource extends Resource
{
context = createContext(getUser(headers));
ItemIterator dspaceItems = org.dspace.content.Item.findAllUnfiltered(context);
Iterator<org.dspace.content.Item> dspaceItems = itemService.findAllUnfiltered(context);
items = new ArrayList<Item>();
if (!((limit != null) && (limit >= 0) && (offset != null) && (offset >= 0)))
{
log.warn("Pagging was badly set, using default values.");
log.warn("Paging was badly set, using default values.");
limit = 100;
offset = 0;
}
@@ -179,7 +177,7 @@ public class ItemsResource extends Resource
org.dspace.content.Item dspaceItem = dspaceItems.next();
if (i >= offset)
{
if (ItemService.isItemListedForUser(context, dspaceItem))
if (itemService.isItemListedForUser(context, dspaceItem))
{
items.add(new Item(dspaceItem, expand, context));
writeStats(dspaceItem, UsageEvent.Action.VIEW, user_ip, user_agent, xforwardedfor,
@@ -227,7 +225,7 @@ public class ItemsResource extends Resource
@GET
@Path("/{item_id}/metadata")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public MetadataEntry[] getItemMetadata(@PathParam("item_id") Integer itemId, @QueryParam("userIP") String user_ip,
public MetadataEntry[] getItemMetadata(@PathParam("item_id") String itemId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -285,7 +283,7 @@ public class ItemsResource extends Resource
@GET
@Path("/{item_id}/bitstreams")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Bitstream[] getItemBitstreams(@PathParam("item_id") Integer itemId,
public Bitstream[] getItemBitstreams(@PathParam("item_id") String itemId,
@QueryParam("limit") @DefaultValue("20") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
@@ -357,7 +355,7 @@ public class ItemsResource extends Resource
@POST
@Path("/{item_id}/metadata")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response addItemMetadata(@PathParam("item_id") Integer itemId, List<org.dspace.rest.common.MetadataEntry> metadata,
public Response addItemMetadata(@PathParam("item_id") String itemId, List<org.dspace.rest.common.MetadataEntry> metadata,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -379,10 +377,9 @@ public class ItemsResource extends Resource
String data[] = mySplit(entry.getKey()); // Done by my split, because of java split was not function.
if ((data.length >= 2) && (data.length <= 3))
{
dspaceItem.addMetadata(data[0], data[1], data[2], entry.getLanguage(), entry.getValue());
itemService.addMetadata(context, dspaceItem, data[0], data[1], data[2], entry.getLanguage(), entry.getValue());
}
}
dspaceItem.update();
context.complete();
}
@@ -390,10 +387,6 @@ public class ItemsResource extends Resource
{
processException("Could not write metadata to item(id=" + itemId + "), SQLException. Message: " + e, context);
}
catch (AuthorizeException e)
{
processException("Could not write metadata to item(id=" + itemId + "), AuthorizeException. Message: " + e, context);
}
catch (ContextException e)
{
processException("Could not write metadata to item(id=" + itemId + "), ContextException. Message: " + e.getMessage(),
@@ -434,9 +427,9 @@ public class ItemsResource extends Resource
// TODO Add option to add bitstream by URI.(for very big files)
@POST
@Path("/{item_id}/bitstreams")
public Bitstream addItemBitstream(@PathParam("item_id") Integer itemId, InputStream inputStream,
public Bitstream addItemBitstream(@PathParam("item_id") String itemId, InputStream inputStream,
@QueryParam("name") String name, @QueryParam("description") String description,
@QueryParam("groupId") Integer groupId, @QueryParam("year") Integer year, @QueryParam("month") Integer month,
@QueryParam("groupId") String groupId, @QueryParam("year") Integer year, @QueryParam("month") Integer month,
@QueryParam("day") Integer day, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -457,57 +450,56 @@ public class ItemsResource extends Resource
log.trace("Creating bitstream in item.");
org.dspace.content.Bundle bundle = null;
org.dspace.content.Bitstream dspaceBitstream = null;
Bundle[] bundles = dspaceItem.getBundles("ORIGINAL");
if(bundles != null && bundles.length != 0)
List<Bundle> bundles = itemService.getBundles(dspaceItem, org.dspace.core.Constants.CONTENT_BUNDLE_NAME);
if(bundles != null && bundles.size() != 0)
{
bundle = bundles[0]; // There should be only one bundle ORIGINAL.
bundle = bundles.get(0); // There should be only one bundle ORIGINAL.
}
if (bundle == null)
{
log.trace("Creating bundle in item.");
dspaceBitstream = dspaceItem.createSingleBitstream(inputStream);
dspaceBitstream = itemService.createSingleBitstream(context, inputStream, dspaceItem);
}
else
{
log.trace("Getting bundle from item.");
dspaceBitstream = bundle.createBitstream(inputStream);
dspaceBitstream = bitstreamService.create(context, bundle, inputStream);
}
dspaceBitstream.setSource("DSpace Rest api");
dspaceBitstream.setSource(context, "DSpace REST API");
// Set bitstream name and description
if (name != null)
{
if (BitstreamResource.getMimeType(name) == null)
{
dspaceBitstream.setFormat(BitstreamFormat.findUnknown(context));
dspaceBitstream.setFormat(context, bitstreamFormatService.findUnknown(context));
}
else
{
dspaceBitstream.setFormat(BitstreamFormat.findByMIMEType(context, BitstreamResource.getMimeType(name)));
bitstreamService.setFormat(context, dspaceBitstream, bitstreamFormatService.findByMIMEType(context, BitstreamResource.getMimeType(name)));
}
dspaceBitstream.setName(name);
dspaceBitstream.setName(context, name);
}
if (description != null)
{
dspaceBitstream.setDescription(description);
dspaceBitstream.setDescription(context, description);
}
dspaceBitstream.update();
// Create policy for bitstream
if (groupId != null)
{
bundles = dspaceBitstream.getBundles();
List<BundleBitstream> bundleBitstreams = dspaceBitstream.getBundles();
for (Bundle dspaceBundle : bundles)
{
List<org.dspace.authorize.ResourcePolicy> bitstreamsPolicies = dspaceBundle.getBitstreamPolicies();
List<org.dspace.authorize.ResourcePolicy> bitstreamsPolicies = bundleService.getBitstreamPolicies(context, dspaceBundle);
// Remove default bitstream policies
List<org.dspace.authorize.ResourcePolicy> policiesToRemove = new ArrayList<org.dspace.authorize.ResourcePolicy>();
for (org.dspace.authorize.ResourcePolicy policy : bitstreamsPolicies)
{
if (policy.getResourceID() == dspaceBitstream.getID())
for (org.dspace.authorize.ResourcePolicy policy : bitstreamsPolicies) {
if (policy.getdSpaceObject().getID() == dspaceBitstream.getID())
{
policiesToRemove.add(policy);
}
@@ -517,12 +509,10 @@ public class ItemsResource extends Resource
bitstreamsPolicies.remove(policy);
}
org.dspace.authorize.ResourcePolicy dspacePolicy = org.dspace.authorize.ResourcePolicy.create(context);
org.dspace.authorize.ResourcePolicy dspacePolicy = resourcePolicyService.create(context);
dspacePolicy.setAction(org.dspace.core.Constants.READ);
dspacePolicy.setGroup(Group.find(context, groupId));
dspacePolicy.setResourceID(dspaceBitstream.getID());
dspacePolicy.setResource(dspaceBitstream);
dspacePolicy.setResourceType(org.dspace.core.Constants.BITSTREAM);
dspacePolicy.setGroup(groupService.findByIdOrLegacyId(context, groupId));
dspacePolicy.setdSpaceObject(dspaceBitstream);
if ((year != null) || (month != null) || (day != null))
{
Date date = new Date();
@@ -544,13 +534,14 @@ public class ItemsResource extends Resource
dspacePolicy.setStartDate(date);
}
dspacePolicy.update();
dspaceBitstream.updateLastModified();
resourcePolicyService.update(context, dspacePolicy);
bitstreamService.updateLastModified(context, dspaceBitstream);
}
}
dspaceBitstream = org.dspace.content.Bitstream.find(context, dspaceBitstream.getID());
bitstream = new Bitstream(dspaceBitstream, "");
dspaceBitstream = bitstreamService.find(context, dspaceBitstream.getID());
bitstream = new Bitstream(dspaceBitstream, "", context);
context.complete();
@@ -605,7 +596,7 @@ public class ItemsResource extends Resource
@PUT
@Path("/{item_id}/metadata")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateItemMetadata(@PathParam("item_id") Integer itemId, MetadataEntry[] metadata,
public Response updateItemMetadata(@PathParam("item_id") String itemId, MetadataEntry[] metadata,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -627,7 +618,7 @@ public class ItemsResource extends Resource
String data[] = mySplit(entry.getKey());
if ((data.length >= 2) && (data.length <= 3))
{
dspaceItem.clearMetadata(data[0], data[1], data[2], org.dspace.content.Item.ANY);
itemService.clearMetadata(context, dspaceItem, data[0], data[1], data[2], org.dspace.content.Item.ANY);
}
}
@@ -637,11 +628,10 @@ public class ItemsResource extends Resource
String data[] = mySplit(entry.getKey());
if ((data.length >= 2) && (data.length <= 3))
{
dspaceItem.addMetadata(data[0], data[1], data[2], entry.getLanguage(), entry.getValue());
itemService.addMetadata(context, dspaceItem, data[0], data[1], data[2], entry.getLanguage(), entry.getValue());
}
}
dspaceItem.update();
context.complete();
}
@@ -649,10 +639,6 @@ public class ItemsResource extends Resource
{
processException("Could not update metadata in item(id=" + itemId + "), SQLException. Message: " + e, context);
}
catch (AuthorizeException e)
{
processException("Could not update metadata in item(id=" + itemId + "), AuthorizeException. Message: " + e, context);
}
catch (ContextException e)
{
processException(
@@ -688,7 +674,7 @@ public class ItemsResource extends Resource
*/
@DELETE
@Path("/{item_id}")
public Response deleteItem(@PathParam("item_id") Integer itemId, @QueryParam("userIP") String user_ip,
public Response deleteItem(@PathParam("item_id") String itemId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -704,9 +690,8 @@ public class ItemsResource extends Resource
writeStats(dspaceItem, UsageEvent.Action.REMOVE, user_ip, user_agent, xforwardedfor, headers, request, context);
log.trace("Deleting item.");
org.dspace.content.Collection collection = org.dspace.content.Collection.find(context,
dspaceItem.getCollections()[0].getID());
collection.removeItem(dspaceItem);
org.dspace.content.Collection collection = collectionService.find(context, dspaceItem.getCollections().get(0).getID());
collectionService.removeItem(context, collection, dspaceItem);
context.complete();
}
@@ -757,7 +742,7 @@ public class ItemsResource extends Resource
*/
@DELETE
@Path("/{item_id}/metadata")
public Response deleteItemMetadata(@PathParam("item_id") Integer itemId, @QueryParam("userIP") String user_ip,
public Response deleteItemMetadata(@PathParam("item_id") String itemId, @QueryParam("userIP") String user_ip,
@QueryParam("userAgent") String user_agent, @QueryParam("xforwardedfor") String xforwardedfor,
@Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException
{
@@ -774,33 +759,27 @@ public class ItemsResource extends Resource
log.trace("Deleting metadata.");
// TODO Rewrite without deprecated object. Leave there only generated metadata.
Metadatum[] value = dspaceItem.getMetadata("dc", "date", "accessioned", org.dspace.content.Item.ANY);
Metadatum[] value2 = dspaceItem.getMetadata("dc", "date", "available", org.dspace.content.Item.ANY);
Metadatum[] value3 = dspaceItem.getMetadata("dc", "identifier", "uri", org.dspace.content.Item.ANY);
Metadatum[] value4 = dspaceItem.getMetadata("dc", "description", "provenance", org.dspace.content.Item.ANY);
dspaceItem.clearMetadata(org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY,
String valueAccessioned = itemService.getMetadataFirstValue(dspaceItem, "dc", "date", "accessioned", org.dspace.content.Item.ANY);
String valueAvailable = itemService.getMetadataFirstValue(dspaceItem, "dc", "date", "available", org.dspace.content.Item.ANY);
String valueURI = itemService.getMetadataFirstValue(dspaceItem, "dc", "identifier", "uri", org.dspace.content.Item.ANY);
String valueProvenance = itemService.getMetadataFirstValue(dspaceItem, "dc", "description", "provenance", org.dspace.content.Item.ANY);
itemService.clearMetadata(context, dspaceItem, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY,
org.dspace.content.Item.ANY);
dspaceItem.update();
// Add there generated metadata
dspaceItem.addMetadata(value[0].schema, value[0].element, value[0].qualifier, null, value[0].value);
dspaceItem.addMetadata(value2[0].schema, value2[0].element, value2[0].qualifier, null, value2[0].value);
dspaceItem.addMetadata(value3[0].schema, value3[0].element, value3[0].qualifier, null, value3[0].value);
dspaceItem.addMetadata(value4[0].schema, value4[0].element, value4[0].qualifier, null, value4[0].value);
// Add their generated metadata
itemService.addMetadata(context, dspaceItem, "dc", "date", "accessioned", null, valueAccessioned);
itemService.addMetadata(context, dspaceItem, "dc", "date", "available", null, valueAvailable);
itemService.addMetadata(context, dspaceItem, "dc", "identifier", "uri", null, valueURI);
itemService.addMetadata(context, dspaceItem, "dc", "description", "provenance", null, valueProvenance);
dspaceItem.update();
context.complete();
}
catch (SQLException e)
{
processException("Could not delete item(id=" + itemId + "), SQLException. Message: " + e, context);
}
catch (AuthorizeException e)
{
processException("Could not delete item(id=" + itemId + "), AuthorizeExcpetion. Message: " + e, context);
}
catch (ContextException e)
{
processException("Could not delete item(id=" + itemId + "), ContextException. Message:" + e.getMessage(), context);
@@ -837,7 +816,7 @@ public class ItemsResource extends Resource
*/
@DELETE
@Path("/{item_id}/bitstreams/{bitstream_id}")
public Response deleteItemBitstream(@PathParam("item_id") Integer itemId, @PathParam("bitstream_id") Integer bitstreamId,
public Response deleteItemBitstream(@PathParam("item_id") String itemId, @PathParam("bitstream_id") String bitstreamId,
@QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
@QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers, @Context HttpServletRequest request)
throws WebApplicationException
@@ -851,14 +830,14 @@ public class ItemsResource extends Resource
context = createContext(getUser(headers));
org.dspace.content.Item item = findItem(context, itemId, org.dspace.core.Constants.WRITE);
org.dspace.content.Bitstream bitstream = org.dspace.content.Bitstream.find(context, bitstreamId);
org.dspace.content.Bitstream bitstream = bitstreamService.findByIdOrLegacyId(context, bitstreamId);
if (bitstream == null)
{
context.abort();
log.warn("Bitstream(id=" + bitstreamId + ") was not found.");
return Response.status(Status.NOT_FOUND).build();
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, bitstream, org.dspace.core.Constants.DELETE))
else if (!authorizeService.authorizeActionBoolean(context, bitstream, org.dspace.core.Constants.DELETE))
{
context.abort();
log.error("User(" + getUser(headers).getEmail() + ") is not allowed to delete bitstream(id=" + bitstreamId + ").");
@@ -870,13 +849,17 @@ public class ItemsResource extends Resource
request, context);
log.trace("Deleting bitstream...");
for (org.dspace.content.Bundle bundle : item.getBundles())
Iterator<Bundle> bundleIterator = item.getBundles().iterator();
while(bundleIterator.hasNext())
{
for (org.dspace.content.Bitstream bit : bundle.getBitstreams())
Bundle bundle = bundleIterator.next();
Iterator<BundleBitstream> bundleBitstreamIterator = bundle.getBitstreams().iterator();
while (bundleBitstreamIterator.hasNext())
{
if (bit == bitstream)
BundleBitstream bundleBitstream = bundleBitstreamIterator.next();
if (bundleBitstream.getBitstream().getID() == bitstream.getID())
{
bundle.removeBitstream(bitstream);
bundleService.removeBitstream(context, bundle, bitstream);
}
}
}
@@ -915,10 +898,6 @@ public class ItemsResource extends Resource
*
* @param metadataEntry
* Metadata field to search by.
* @param scheme
* Scheme of metadata(key).
* @param value
* Value of metadata field.
* @param headers
* If you want to access the item as the user logged into context,
* header "rest-dspace-token" must be set to token value retrieved
@@ -947,30 +926,6 @@ public class ItemsResource extends Resource
List<Item> items = new ArrayList<Item>();
String[] metadata = mySplit(metadataEntry.getKey());
try
{
context = createContext(getUser(headers));
// TODO Repair, it ends by error:
// "java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: expected - got CLOB"
/*
* if (metadata.length == 3){
* itemIterator = org.dspace.content.Item.findByMetadataField(context, metadata[0],
* metadata[1], metadata[2], value);
* } else if (metadata.length == 2){
* itemIterator = org.dspace.content.Item.findByMetadataField(context, metadata[0],
* metadata[1], null, value);
* } else {
* context.abort();
* log.error("Finding failed, bad metadata key.");
* throw new WebApplicationException(Response.Status.NOT_FOUND);
* }
*
* if (itemIterator.hasNext()) {
* item = new Item(itemIterator.next(), "", context);
* }
*/
// Must used own style.
if ((metadata.length < 2) || (metadata.length > 3))
{
@@ -979,40 +934,15 @@ public class ItemsResource extends Resource
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
String sql = "SELECT RESOURCE_ID, TEXT_VALUE, TEXT_LANG, SHORT_ID, ELEMENT, QUALIFIER " +
"FROM METADATAVALUE " +
"JOIN METADATAFIELDREGISTRY ON METADATAVALUE.METADATA_FIELD_ID = METADATAFIELDREGISTRY.METADATA_FIELD_ID " +
"JOIN METADATASCHEMAREGISTRY ON METADATAFIELDREGISTRY.METADATA_SCHEMA_ID = METADATASCHEMAREGISTRY.METADATA_SCHEMA_ID " +
"WHERE " +
"SHORT_ID='" + metadata[0] + "' AND " +
"ELEMENT='" + metadata[1] + "' AND ";
if (metadata.length > 3)
try
{
sql += "QUALIFIER='" + metadata[2] + "' AND ";
}
if (org.dspace.storage.rdbms.DatabaseManager.isOracle())
{
sql += "dbms_lob.compare(TEXT_VALUE, '" + metadataEntry.getValue() + "') = 0 AND ";
}
else
{
sql += "TEXT_VALUE='" + metadataEntry.getValue() + "' AND ";
}
if (metadataEntry.getLanguage() != null)
{
sql += "TEXT_LANG='" + metadataEntry.getLanguage() + "'";
}
else
{
sql += "TEXT_LANG is null";
}
context = createContext(getUser(headers));
TableRowIterator iterator = org.dspace.storage.rdbms.DatabaseManager.query(context, sql);
while (iterator.hasNext())
Iterator<org.dspace.content.Item> itemIterator = itemService.findByMetadataField(context, metadataEntry.getSchema(), metadataEntry.getElement(), metadataEntry.getQualifier(), metadataEntry.getValue());
while (itemIterator.hasNext())
{
TableRow row = iterator.next();
org.dspace.content.Item dspaceItem = this.findItem(context, row.getIntColumn("RESOURCE_ID"),
org.dspace.core.Constants.READ);
org.dspace.content.Item dspaceItem = itemIterator.next();
Item item = new Item(dspaceItem, "", context);
writeStats(dspaceItem, UsageEvent.Action.VIEW, user_ip, user_agent, xforwardedfor, headers,
request, context);
@@ -1020,7 +950,6 @@ public class ItemsResource extends Resource
}
context.complete();
}
catch (SQLException e)
{
@@ -1029,8 +958,11 @@ public class ItemsResource extends Resource
catch (ContextException e)
{
processException("Context error:" + e.getMessage(), context);
}
finally
} catch (AuthorizeException e) {
processException("Authorize error:" + e.getMessage(), context);
} catch (IOException e) {
processException("IO error:" + e.getMessage(), context);
} finally
{
processFinally(context);
}
@@ -1063,12 +995,12 @@ public class ItemsResource extends Resource
* Is thrown when item with passed id is not exists and if user
* has no permission to do passed action.
*/
private org.dspace.content.Item findItem(org.dspace.core.Context context, int id, int action) throws WebApplicationException
private org.dspace.content.Item findItem(org.dspace.core.Context context, String id, int action) throws WebApplicationException
{
org.dspace.content.Item item = null;
try
{
item = org.dspace.content.Item.find(context, id);
item = itemService.findByIdOrLegacyId(context, id);
if (item == null)
{
@@ -1076,7 +1008,7 @@ public class ItemsResource extends Resource
log.warn("Item(id=" + id + ") was not found!");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
else if (!AuthorizeServiceImpl.authorizeActionBoolean(context, item, action))
else if (!authorizeService.authorizeActionBoolean(context, item, action))
{
context.abort();
if (context.getCurrentUser() != null)

View File

@@ -7,7 +7,6 @@
*/
package org.dspace.rest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@@ -71,13 +70,8 @@ public class Resource
*/
protected static org.dspace.core.Context createContext(EPerson person) throws ContextException
{
org.dspace.core.Context context = null;
try
{
context = new org.dspace.core.Context();
context.getDBConnection().setAutoCommit(false); // Disable autocommit.
org.dspace.core.Context context = new org.dspace.core.Context();
//context.getDBConnection().setAutoCommit(false); // Disable autocommit.
if (person != null)
{
@@ -86,15 +80,6 @@ public class Resource
return context;
}
catch (SQLException e)
{
if ((context != null) && (context.isValid()))
{
context.abort();
}
throw new ContextException("Could not create context, SQLException. Message: " + e, e);
}
}
/**
* Records a statistics event about an object used via REST API.

View File

@@ -23,8 +23,9 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService;
import org.dspace.rest.common.Status;
import org.dspace.rest.common.User;
import org.dspace.rest.exceptions.ContextException;
@@ -38,6 +39,7 @@ import org.dspace.rest.exceptions.ContextException;
*/
@Path("/")
public class RestIndex {
protected EPersonService epersonService = EPersonServiceFactory.getInstance().getEPersonService();
private static Logger log = Logger.getLogger(RestIndex.class);
@javax.ws.rs.core.Context public static ServletContext servletContext;
@@ -212,7 +214,7 @@ public class RestIndex {
if(ePerson != null) {
//DB EPerson needed since token won't have full info, need context
EPerson dbEPerson = EPerson.findByEmail(context, ePerson.getEmail());
EPerson dbEPerson = epersonService.findByEmail(context, ePerson.getEmail());
String token = Resource.getToken(headers);
Status status = new Status(dbEPerson.getEmail(), dbEPerson.getFullName(), token);
return status;
@@ -223,8 +225,6 @@ public class RestIndex {
Resource.processException("Status context error: " + e.getMessage(), context);
} catch (SQLException e) {
Resource.processException("Status eperson db lookup error: " + e.getMessage(), context);
} catch (AuthorizeException e) {
Resource.processException("Status eperson authorize exception: " + e.getMessage(), context);
} finally {
context.abort();
}

View File

@@ -8,16 +8,21 @@
package org.dspace.rest;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authenticate.AuthenticationMethod;
import org.dspace.authenticate.factory.AuthenticateServiceFactory;
import org.dspace.authenticate.service.AuthenticationService;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.factory.EPersonServiceFactory;
import org.dspace.eperson.service.EPersonService;
import org.dspace.rest.common.User;
/**
@@ -30,13 +35,15 @@ import org.dspace.rest.common.User;
public class TokenHolder
{
private static final Logger log = Logger.getLogger(TokenHolder.class);
public static String TOKEN_HEADER = "rest-dspace-token";
private static Map<String, String> tokens = new HashMap<String, String>(); // Map with pair Email,token
private static Map<String, EPerson> persons = new HashMap<String, EPerson>(); // Map with pair token,Eperson
/**
* Collection holding the auth-token, and the corresponding EPerson's UUID
*/
private static BiMap<String, UUID> tokenPersons = HashBiMap.create();
/**
* Login user into rest api. It check user credentials if they are okay.
@@ -53,32 +60,30 @@ public class TokenHolder
*/
public static String login(User user) throws WebApplicationException
{
AuthenticationService authenticationService = AuthenticateServiceFactory.getInstance().getAuthenticationService();
EPersonService epersonService = EPersonServiceFactory.getInstance().getEPersonService();
org.dspace.core.Context context = null;
String token = null;
try
{
context = new org.dspace.core.Context();
EPerson dspaceUser = EPerson.findByEmail(context, user.getEmail());
if ((dspaceUser == null) || (!dspaceUser.checkPassword(user.getPassword())))
{
token = null;
}
else if (tokens.containsKey(user.getEmail()))
{
token = tokens.get(user.getEmail());
}
else
int status = authenticationService.authenticate(context, user.getEmail(), user.getPassword(), null, null);
if (status == AuthenticationMethod.SUCCESS)
{
EPerson ePerson = epersonService.findByEmail(context, user.getEmail());
if(tokenPersons.inverse().containsKey(ePerson.getID())) {
token = tokenPersons.inverse().get(ePerson.getID());
} else {
token = generateToken();
persons.put(token, dspaceUser);
tokens.put(user.getEmail(), token);
tokenPersons.put(token, ePerson.getID());
}
}
log.trace("User(" + user.getEmail() + ") has been logged.");
log.trace("User(" + user.getEmail() + ") has been logged in.");
context.complete();
}
catch (SQLException e)
{
@@ -86,12 +91,6 @@ public class TokenHolder
log.error("Could not read user from database. Message:" + e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
catch (AuthorizeException e)
{
context.abort();
log.error("Could not find user, AuthorizeException. Message:" + e);
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
finally
{
if ((context != null) && (context.isValid()))
@@ -115,7 +114,15 @@ public class TokenHolder
*/
public static EPerson getEPerson(String token)
{
return persons.get(token);
try {
EPersonService epersonService = EPersonServiceFactory.getInstance().getEPersonService();
UUID epersonID = tokenPersons.get(token);
Context context = new Context();
return epersonService.find(context, epersonID);
} catch (SQLException e) {
log.error(e);
return null;
}
}
/**
@@ -127,17 +134,16 @@ public class TokenHolder
*/
public static boolean logout(String token)
{
if ((token == null) || (persons.get(token) == null))
if ((token == null) || (! tokenPersons.containsKey(token)))
{
return false;
}
String email = persons.get(token).getEmail();
EPerson person = persons.remove(token);
if (person == null)
UUID personID = tokenPersons.remove(token);
if (personID == null)
{
return false;
}
tokens.remove(email);
return true;
}

View File

@@ -15,8 +15,12 @@ import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.log4j.Logger;
import org.dspace.content.Bundle;
import org.dspace.content.BundleBitstream;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.BundleService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
/**
* Created with IntelliJ IDEA.
@@ -27,6 +31,9 @@ import org.dspace.core.Constants;
*/
@XmlRootElement(name = "bitstream")
public class Bitstream extends DSpaceObject {
protected BitstreamService bitstreamService = ContentServiceFactory.getInstance().getBitstreamService();
protected BundleService bundleService = ContentServiceFactory.getInstance().getBundleService();
Logger log = Logger.getLogger(Bitstream.class);
private String bundleName;
@@ -45,29 +52,29 @@ public class Bitstream extends DSpaceObject {
}
public Bitstream(org.dspace.content.Bitstream bitstream, String expand) throws SQLException{
public Bitstream(org.dspace.content.Bitstream bitstream, String expand, Context context) throws SQLException{
super(bitstream);
setup(bitstream, expand);
setup(bitstream, expand, context);
}
public void setup(org.dspace.content.Bitstream bitstream, String expand) throws SQLException{
public void setup(org.dspace.content.Bitstream bitstream, String expand, Context context) throws SQLException{
List<String> expandFields = new ArrayList<String>();
if(expand != null) {
expandFields = Arrays.asList(expand.split(","));
}
//A logo bitstream might not have a bundle...
if(bitstream.getBundles() != null & bitstream.getBundles().length >= 0) {
if(bitstream.getParentObject().getType() == Constants.ITEM) {
bundleName = bitstream.getBundles()[0].getName();
if(bitstream.getBundles() != null & bitstream.getBundles().size() >= 0) {
if(bitstreamService.getParentObject(context, bitstream).getType() == Constants.ITEM) {
bundleName = bitstream.getBundles().get(0).getBundle().getName();
}
}
description = bitstream.getDescription();
format = bitstream.getFormatDescription();
format = bitstreamService.getFormatDescription(context, bitstream);
sizeBytes = bitstream.getSize();
retrieveLink = "/bitstreams/" + bitstream.getID() + "/retrieve";
mimeType = bitstream.getFormat().getMIMEType();
mimeType = bitstreamService.getFormat(context, bitstream).getMIMEType();
sequenceId = bitstream.getSequenceID();
CheckSum checkSum = new CheckSum();
checkSum.setCheckSumAlgorith(bitstream.getChecksumAlgorithm());
@@ -75,7 +82,7 @@ public class Bitstream extends DSpaceObject {
this.setCheckSum(checkSum);
if(expandFields.contains("parent") || expandFields.contains("all")) {
parentObject = new DSpaceObject(bitstream.getParentObject());
parentObject = new DSpaceObject(bitstreamService.getParentObject(context, bitstream));
} else {
this.addExpand("parent");
}
@@ -83,11 +90,11 @@ public class Bitstream extends DSpaceObject {
if(expandFields.contains("policies") || expandFields.contains("all")) {
// Find policies without context.
List<ResourcePolicy> tempPolicies = new ArrayList<ResourcePolicy>();
Bundle[] bundles = bitstream.getBundles();
for (Bundle bundle : bundles) {
List<org.dspace.authorize.ResourcePolicy> bitstreamsPolicies = bundle.getBitstreamPolicies();
List<BundleBitstream> bundleBitstreams = bitstream.getBundles();
for (BundleBitstream bundleBitstream : bundleBitstreams) {
List<org.dspace.authorize.ResourcePolicy> bitstreamsPolicies = bundleService.getBitstreamPolicies(context, bundleBitstream.getBundle());
for (org.dspace.authorize.ResourcePolicy policy : bitstreamsPolicies) {
if (policy.getResourceID() == this.getId()) {
if(policy.getdSpaceObject() == bitstream) {
tempPolicies.add(new ResourcePolicy(policy));
}
}

View File

@@ -8,8 +8,8 @@
package org.dspace.rest.common;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.content.ItemIterator;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.ItemService;
import org.dspace.core.Context;
@@ -18,6 +18,7 @@ import javax.xml.bind.annotation.XmlRootElement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
@@ -29,6 +30,9 @@ import java.util.List;
*/
@XmlRootElement(name = "collection")
public class Collection extends DSpaceObject {
protected CollectionService collectionService = ContentServiceFactory.getInstance().getCollectionService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
Logger log = Logger.getLogger(Collection.class);
//Relationships
@@ -58,13 +62,13 @@ public class Collection extends DSpaceObject {
expandFields = Arrays.asList(expand.split(","));
}
this.setCopyrightText(collection.getMetadata(org.dspace.content.Collection.COPYRIGHT_TEXT));
this.setIntroductoryText(collection.getMetadata(org.dspace.content.Collection.INTRODUCTORY_TEXT));
this.setShortDescription(collection.getMetadata(org.dspace.content.Collection.SHORT_DESCRIPTION));
this.setSidebarText(collection.getMetadata(org.dspace.content.Collection.SIDEBAR_TEXT));
this.setCopyrightText(collectionService.getMetadata(collection, org.dspace.content.Collection.COPYRIGHT_TEXT));
this.setIntroductoryText(collectionService.getMetadata(collection, org.dspace.content.Collection.INTRODUCTORY_TEXT));
this.setShortDescription(collectionService.getMetadata(collection, org.dspace.content.Collection.SHORT_DESCRIPTION));
this.setSidebarText(collectionService.getMetadata(collection, org.dspace.content.Collection.SIDEBAR_TEXT));
if(expandFields.contains("parentCommunityList") || expandFields.contains("all")) {
org.dspace.content.Community[] parentCommunities = collection.getCommunities();
List<org.dspace.content.Community> parentCommunities = collection.getCommunities();
for(org.dspace.content.Community parentCommunity : parentCommunities) {
this.addParentCommunityList(new Community(parentCommunity, null, context));
}
@@ -73,7 +77,7 @@ public class Collection extends DSpaceObject {
}
if(expandFields.contains("parentCommunity") | expandFields.contains("all")) {
org.dspace.content.Community parentCommunity = (org.dspace.content.Community) collection.getParentObject();
org.dspace.content.Community parentCommunity = (org.dspace.content.Community) collectionService.getParentObject(context, collection);
this.setParentCommunity(new Community(parentCommunity, null, context));
} else {
this.addExpand("parentCommunity");
@@ -81,18 +85,13 @@ public class Collection extends DSpaceObject {
//TODO: Item paging. limit, offset/page
if(expandFields.contains("items") || expandFields.contains("all")) {
ItemIterator childItems;
if(limit != null && limit >= 0 && offset != null && offset >= 0) {
childItems = collection.getItems(limit, offset);
} else {
childItems = collection.getItems();
}
Iterator<org.dspace.content.Item> childItems = itemService.findByCollection(context, collection, limit, offset);
items = new ArrayList<Item>();
while(childItems.hasNext()) {
org.dspace.content.Item item = childItems.next();
if(ItemService.isItemListedForUser(context, item)) {
if(itemService.isItemListedForUser(context, item)) {
items.add(new Item(item, null, context));
}
}
@@ -101,14 +100,14 @@ public class Collection extends DSpaceObject {
}
if(expandFields.contains("license") || expandFields.contains("all")) {
setLicense(collection.getLicense());
setLicense(collectionService.getLicense(collection));
} else {
this.addExpand("license");
}
if(expandFields.contains("logo") || expandFields.contains("all")) {
if(collection.getLogo() != null) {
this.logo = new Bitstream(collection.getLogo(), null);
this.logo = new Bitstream(collection.getLogo(), null, context);
}
}
else {
@@ -119,7 +118,7 @@ public class Collection extends DSpaceObject {
this.addExpand("all");
}
this.setNumberItems(collection.countItems());
this.setNumberItems(itemService.countItems(context, collection));
}
public Bitstream getLogo() {

View File

@@ -8,7 +8,11 @@
package org.dspace.rest.common;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CommunityService;
import org.dspace.content.service.ItemService;
import org.dspace.core.Context;
import javax.ws.rs.WebApplicationException;
@@ -28,6 +32,10 @@ import java.util.List;
*/
@XmlRootElement(name = "community")
public class Community extends DSpaceObject{
protected CommunityService communityService = ContentServiceFactory.getInstance().getCommunityService();
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
private static Logger log = Logger.getLogger(Community.class);
//Exandable relationships
@@ -55,14 +63,14 @@ public class Community extends DSpaceObject{
expandFields = Arrays.asList(expand.split(","));
}
this.setCopyrightText(community.getMetadata(org.dspace.content.Community.COPYRIGHT_TEXT));
this.setIntroductoryText(community.getMetadata(org.dspace.content.Community.INTRODUCTORY_TEXT));
this.setShortDescription(community.getMetadata(org.dspace.content.Community.SHORT_DESCRIPTION));
this.setSidebarText(community.getMetadata(org.dspace.content.Community.SIDEBAR_TEXT));
this.setCountItems(community.countItems());
this.setCopyrightText(communityService.getMetadata(community, org.dspace.content.Community.COPYRIGHT_TEXT));
this.setIntroductoryText(communityService.getMetadata(community, org.dspace.content.Community.INTRODUCTORY_TEXT));
this.setShortDescription(communityService.getMetadata(community, org.dspace.content.Community.SHORT_DESCRIPTION));
this.setSidebarText(communityService.getMetadata(community, org.dspace.content.Community.SIDEBAR_TEXT));
this.setCountItems(itemService.countItems(context, community));
if(expandFields.contains("parentCommunity") || expandFields.contains("all")) {
org.dspace.content.Community parentCommunity = community.getParentCommunity();
org.dspace.content.Community parentCommunity = (org.dspace.content.Community) communityService.getParentObject(context, community);
if(parentCommunity != null) {
setParentCommunity(new Community(parentCommunity, null, context));
}
@@ -71,11 +79,12 @@ public class Community extends DSpaceObject{
}
if(expandFields.contains("collections") || expandFields.contains("all")) {
org.dspace.content.Collection[] collectionArray = community.getCollections();
collections = new ArrayList<Collection>();
for(org.dspace.content.Collection collection : collectionArray) {
if(AuthorizeServiceImpl.authorizeActionBoolean(context, collection, org.dspace.core.Constants.READ)) {
collections.add(new Collection(collection, null, context, null, null));
List<org.dspace.content.Collection> collections = community.getCollections();
List<org.dspace.rest.common.Collection> restCollections = new ArrayList<>();
for(org.dspace.content.Collection collection : collections) {
if(authorizeService.authorizeActionBoolean(context, collection, org.dspace.core.Constants.READ)) {
restCollections.add(new Collection(collection, null, context, null, null));
} else {
log.info("Omitted restricted collection: " + collection.getID() + " _ " + collection.getName());
}
@@ -85,10 +94,10 @@ public class Community extends DSpaceObject{
}
if(expandFields.contains("subCommunities") || expandFields.contains("all")) {
org.dspace.content.Community[] communityArray = community.getSubcommunities();
List<org.dspace.content.Community> communities = community.getSubcommunities();
subcommunities = new ArrayList<Community>();
for(org.dspace.content.Community subCommunity : communityArray) {
if(AuthorizeServiceImpl.authorizeActionBoolean(context, subCommunity, org.dspace.core.Constants.READ)) {
for(org.dspace.content.Community subCommunity : communities) {
if(authorizeService.authorizeActionBoolean(context, subCommunity, org.dspace.core.Constants.READ)) {
subcommunities.add(new Community(subCommunity, null, context));
} else {
log.info("Omitted restricted subCommunity: " + subCommunity.getID() + " _ " + subCommunity.getName());
@@ -100,7 +109,7 @@ public class Community extends DSpaceObject{
if(expandFields.contains("logo") || expandFields.contains("all")) {
if(community.getLogo() != null) {
logo = new Bitstream(community.getLogo(), null);
logo = new Bitstream(community.getLogo(), null, context);
}
} else {
this.addExpand("logo");

View File

@@ -8,6 +8,8 @@
package org.dspace.rest.common;
import org.atteo.evo.inflector.English;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.DSpaceObjectService;
import org.dspace.rest.Resource;
import javax.xml.bind.annotation.XmlElement;
@@ -15,6 +17,7 @@ import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Created with IntelliJ IDEA.
@@ -25,8 +28,11 @@ import java.util.List;
*/
@XmlRootElement(name = "dspaceobject")
public class DSpaceObject {
//legacyID
private Integer id;
private String uuid;
private String name;
private String handle;
private String type;
@@ -42,10 +48,12 @@ public class DSpaceObject {
}
public DSpaceObject(org.dspace.content.DSpaceObject dso) {
setId(dso.getID());
//setId(); legacyID
setUUID(dso.getID().toString());
setName(dso.getName());
setHandle(dso.getHandle());
setType(dso.getTypeText().toLowerCase());
DSpaceObjectService dspaceObjectService = ContentServiceFactory.getInstance().getDSpaceObjectService(dso);
setType(dspaceObjectService.getTypeText(dso).toLowerCase());
}
public Integer getId() {
@@ -96,4 +104,12 @@ public class DSpaceObject {
public void addExpand(String expandableAttribute) {
this.expand.add(expandableAttribute);
}
public String getUUID() {
return uuid;
}
public void setUUID(String uuid) {
this.uuid = uuid;
}
}

View File

@@ -8,10 +8,15 @@
package org.dspace.rest.common;
import org.apache.log4j.Logger;
import org.dspace.app.util.MetadataExposureServiceImpl;
import org.dspace.authorize.AuthorizeServiceImpl;
import org.dspace.app.util.factory.UtilServiceFactory;
import org.dspace.app.util.service.MetadataExposureService;
import org.dspace.authorize.factory.AuthorizeServiceFactory;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.Bundle;
import org.dspace.content.Metadatum;
import org.dspace.content.MetadataField;
import org.dspace.content.MetadataValue;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.ItemService;
import org.dspace.core.Context;
import javax.ws.rs.WebApplicationException;
@@ -33,6 +38,10 @@ import java.util.List;
@SuppressWarnings("deprecation")
@XmlRootElement(name = "item")
public class Item extends DSpaceObject {
protected ItemService itemService = ContentServiceFactory.getInstance().getItemService();
protected MetadataExposureService metadataExposureService = UtilServiceFactory.getInstance().getMetadataExposureService();
protected AuthorizeService authorizeService = AuthorizeServiceFactory.getInstance().getAuthorizeService();
Logger log = Logger.getLogger(Item.class);
String isArchived;
@@ -60,10 +69,12 @@ public class Item extends DSpaceObject {
if(expandFields.contains("metadata") || expandFields.contains("all")) {
metadata = new ArrayList<MetadataEntry>();
Metadatum[] dcvs = item.getMetadata(org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY);
for (Metadatum dcv : dcvs) {
if (!MetadataExposureServiceImpl.isHidden(context, dcv.schema, dcv.element, dcv.qualifier)) {
metadata.add(new MetadataEntry(dcv.getField(), dcv.value, dcv.language));
List<MetadataValue> metadataValues = itemService.getMetadata(item, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY, org.dspace.content.Item.ANY);
for (MetadataValue metadataValue : metadataValues) {
MetadataField metadataField = metadataValue.getMetadataField();
if (!metadataExposureService.isHidden(context, metadataField.getMetadataSchema().getName(), metadataField.getElement(), metadataField.getQualifier())) {
metadata.add(new MetadataEntry(metadataField.toString('.'), metadataValue.getValue(), metadataValue.getLanguage()));
}
}
} else {
@@ -82,7 +93,7 @@ public class Item extends DSpaceObject {
if(expandFields.contains("parentCollectionList") || expandFields.contains("all")) {
this.parentCollectionList = new ArrayList<Collection>();
org.dspace.content.Collection[] collections = item.getCollections();
List<org.dspace.content.Collection> collections = item.getCollections();
for(org.dspace.content.Collection collection : collections) {
this.parentCollectionList.add(new Collection(collection, null, context, null, null));
}
@@ -92,7 +103,8 @@ public class Item extends DSpaceObject {
if(expandFields.contains("parentCommunityList") || expandFields.contains("all")) {
this.parentCommunityList = new ArrayList<Community>();
org.dspace.content.Community[] communities = item.getCommunities();
List<org.dspace.content.Community> communities = itemService.getCommunities(context, item);
for(org.dspace.content.Community community : communities) {
this.parentCommunityList.add(new Community(community, null, context));
}
@@ -103,12 +115,14 @@ public class Item extends DSpaceObject {
//TODO: paging - offset, limit
if(expandFields.contains("bitstreams") || expandFields.contains("all")) {
bitstreams = new ArrayList<Bitstream>();
Bundle[] bundles = item.getBundles();
List<Bundle> bundles = item.getBundles();
for(Bundle bundle : bundles) {
org.dspace.content.Bitstream[] itemBitstreams = bundle.getBitstreams();
for(org.dspace.content.Bitstream itemBitstream : itemBitstreams) {
if(AuthorizeServiceImpl.authorizeActionBoolean(context, itemBitstream, org.dspace.core.Constants.READ)) {
bitstreams.add(new Bitstream(itemBitstream, null));
List<org.dspace.content.BundleBitstream> itemBundleBitstreams = bundle.getBitstreams();
for(org.dspace.content.BundleBitstream itemBundleBitstream : itemBundleBitstreams) {
if(authorizeService.authorizeActionBoolean(context, itemBundleBitstream.getBitstream(), org.dspace.core.Constants.READ)) {
bitstreams.add(new Bitstream(itemBundleBitstream.getBitstream(), null, context));
}
}
}

View File

@@ -8,6 +8,7 @@
package org.dspace.rest.common;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.regex.Pattern;
/**
* @author peterdietz, Rostislav Novak (Computing and Information Centre, CTU in
@@ -64,4 +65,23 @@ public class MetadataEntry
this.language = language;
}
public String getSchema() {
String[] fieldPieces = key.split(Pattern.quote("."));
return fieldPieces[0];
}
public String getElement() {
String[] fieldPieces = key.split(Pattern.quote("."));
return fieldPieces[1];
}
public String getQualifier() {
String[] fieldPieces = key.split(Pattern.quote("."));
if(fieldPieces.length == 3) {
return fieldPieces[2];
} else {
return null;
}
}
}

View File

@@ -22,9 +22,9 @@ public class ResourcePolicy{
private Integer id;
private Action action;
private Integer epersonId;
private Integer groupId;
private Integer resourceId;
private String epersonId; //UUID
private String groupId; //UUID
private String resourceId; //UUID
private String resourceType;
private String rpDescription;
private String rpName;
@@ -49,16 +49,15 @@ public class ResourcePolicy{
break;
}
this.epersonId = dspacePolicy.getEPersonID();
this.groupId = dspacePolicy.getGroupID();
this.resourceId = dspacePolicy.getResourceID();
this.epersonId = dspacePolicy.getEPerson().getID().toString();
this.groupId = dspacePolicy.getGroup().getID().toString();
this.resourceId = dspacePolicy.getdSpaceObject().getID().toString();
this.rpDescription = dspacePolicy.getRpDescription();
this.rpName = dspacePolicy.getRpName();
this.rpType = dspacePolicy.getRpType();
this.startDate = dspacePolicy.getStartDate();
this.endDate = dspacePolicy.getEndDate();
switch(dspacePolicy.getResourceType()) {
switch(dspacePolicy.getdSpaceObject().getType()) {
case org.dspace.core.Constants.BITSTREAM:
this.resourceType = "bitstream";
break;
@@ -109,27 +108,27 @@ public class ResourcePolicy{
this.action = action;
}
public Integer getEpersonId() {
public String getEpersonId() {
return epersonId;
}
public void setEpersonId(Integer epersonId) {
public void setEpersonId(String epersonId) {
this.epersonId = epersonId;
}
public Integer getGroupId() {
public String getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public Integer getResourceId() {
public String getResourceId() {
return resourceId;
}
public void setResourceId(Integer resourceId) {
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}