Skip to content

Commit

Permalink
Added test for size retrieval, moved number-of-objs retrieval to /res…
Browse files Browse the repository at this point in the history
…t/describe response
  • Loading branch information
ajs6f committed Feb 7, 2013
1 parent 5fa0704 commit 1a5d140
Show file tree
Hide file tree
Showing 7 changed files with 130 additions and 63 deletions.
53 changes: 31 additions & 22 deletions src/main/java/org/fcrepo/modeshape/AbstractResource.java
Expand Up @@ -15,7 +15,6 @@
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.Workspace;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
Expand Down Expand Up @@ -64,8 +63,6 @@ public abstract class AbstractResource extends Constants {
@Inject
protected PidMinter pidMinter;

static protected Workspace ws;

/**
* A convenience object provided by ModeShape for acting against the JCR
* repository.
Expand All @@ -85,26 +82,19 @@ public void initialize() throws LoginException, NoSuchWorkspaceException,
session.logout();
}

protected synchronized Response deleteResource(final String path,
Session session) throws RepositoryException {

logger.debug("Attempting to delete resource at path: " + path);

if (session.nodeExists(path)) {
protected synchronized Response deleteResource(final Node resource)
throws RepositoryException {

if (session.hasPermission(path, "remove")) {
// ws.getLockManager().lock(path, true, true, Long.MAX_VALUE,
// "");
session.getNode(path).remove();
session.save();
session.logout();
logger.debug("Finished deleting resource at path: " + path);
return noContent().build();
} else {
return four03;
}
logger.debug("Attempting to delete resource at path: "
+ resource.getPath());
final Session session = resource.getSession();
if (session.hasPermission(resource.getPath(), "remove")) {
resource.remove();
session.save();
session.logout();
return noContent().build();
} else {
return four04;
return four03;
}
}

Expand All @@ -125,11 +115,30 @@ public static Long getNodePropertySize(Node node)
return size;
}

/**
* Alter the total repository size.
*
* @param change
* the amount by which to [de|in]crement the total repository
* size
* @param session
* the javax.jcr.Session in which the originating mutation is
* occurring
* @throws PathNotFoundException
* @throws RepositoryException
*/
protected void updateRepositorySize(Long change, Session session)
throws PathNotFoundException, RepositoryException {
logger.debug("updateRepositorySize called with change quantity: "
+ change);
Property sizeProperty = session.getNode("/objects").getProperty("size");
Long previousSize = sizeProperty.getLong();
sizeProperty.setValue(previousSize + change);
logger.debug("Previous repository size: " + previousSize);
synchronized (sizeProperty) {
sizeProperty.setValue(previousSize + change);
session.save();
}
logger.debug("Current repository size: " + sizeProperty.getLong());
}

protected Long getRepositorySize(Session session)
Expand Down
31 changes: 25 additions & 6 deletions src/main/java/org/fcrepo/modeshape/FedoraDatastreams.java
Expand Up @@ -232,12 +232,21 @@ private URI addDatastreamNode(final String pid, final String dsPath,
ds.setProperty("fedora:ownerId", "Fedo Radmin");
if (created) {
ds.setProperty("fedora:created", Calendar.getInstance());
}
ds.setProperty("jcr:lastModified", Calendar.getInstance());
session.save();
if (created) {
/*
* we save before updating the repo size because the act of
* persisting session state creates new system-curated nodes and
* properties which contribute to the footprint of this resource
*/
updateRepositorySize(
getObjectSize(session.getNode("/objects/" + pid))
- oldObjectSize, session);
// now we save again to persist the repo size
session.save();
}
ds.setProperty("jcr:lastModified", Calendar.getInstance());
session.save();
session.logout();
logger.debug("Finished adding datastream node at path: " + dsPath);
return uriInfo.getAbsolutePath();
Expand Down Expand Up @@ -390,11 +399,16 @@ public Response getDatastreamHistoryOld(@PathParam("pid") final String pid,
@Path("/{dsid}")
public Response deleteDatastream(@PathParam("pid") String pid,
@PathParam("dsid") String dsid) throws RepositoryException {
final String dsPath = "/objects/" + pid + "/" + dsid;
final Session session = repo.login();
final Node ds = session.getNode("/objects/" + pid + "/" + dsid);
updateRepositorySize(0L - getContentSize(ds) - getNodePropertySize(ds),
session);
return deleteResource("/objects/" + pid + "/" + dsid, session);
final Node ds;
if (session.nodeExists(dsPath)) {
ds = session.getNode(dsPath);
} else {
return four04;
}
updateRepositorySize(0L - getDatastreamSize(ds), session);
return deleteResource(ds);
}

private DatastreamProfile getDSProfile(Node ds) throws RepositoryException,
Expand All @@ -419,6 +433,11 @@ private String getDSMimeType(Node ds) throws ValueFormatException,
return b.getMimeType();
}

public static Long getDatastreamSize(Node ds) throws ValueFormatException,
PathNotFoundException, RepositoryException {
return getNodePropertySize(ds) + getContentSize(ds);
}

public static Long getContentSize(Node ds) throws ValueFormatException,
PathNotFoundException, RepositoryException {
return ds.getNode(JCR_CONTENT).getProperty(JCR_DATA).getBinary()
Expand Down
28 changes: 10 additions & 18 deletions src/main/java/org/fcrepo/modeshape/FedoraObjects.java
Expand Up @@ -75,7 +75,14 @@ public Response ingest(@PathParam("pid") final String pid)
obj.addMixin("fedora:owned");
obj.setProperty("fedora:ownerId", "Fedo Radmin");
obj.setProperty("jcr:lastModified", Calendar.getInstance());
session.save();
/*
* we save before updating the repo size because the act of
* persisting session state creates new system-curated nodes and
* properties which contribute to the footprint of this resource
*/
updateRepositorySize(getObjectSize(obj), session);
// now we save again to persist the repo size
session.save();
session.logout();
logger.debug("Finished ingest with pid: " + pid);
Expand Down Expand Up @@ -133,24 +140,9 @@ public String apply(NodeType type) {
public Response deleteObject(@PathParam("pid") final String pid)
throws RepositoryException {
final Session session = repo.login();
updateRepositorySize(
0L - getObjectSize(session.getNode("/objects/" + pid)), session);
return deleteResource("/objects/" + pid, session);
}

/**
* Provides the number of objects in the repository
*
* @return the number of objects found
* @throws RepositoryException
*/
@GET
@Path("/numObjects")
public Long getNumObjects() throws RepositoryException {
final Session session = repo.login();
Long numObjects = session.getNode("/objects").getNodes().getSize();
session.logout();
return numObjects;
final Node obj = session.getNode("/objects/" + pid);
updateRepositorySize(0L - getObjectSize(obj), session);
return deleteResource(obj);
}

/**
Expand Down
27 changes: 15 additions & 12 deletions src/main/java/org/fcrepo/modeshape/FedoraRepository.java
@@ -1,5 +1,6 @@
package org.fcrepo.modeshape;

import static com.google.common.collect.ImmutableMap.builder;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.TEXT_XML;
import static javax.ws.rs.core.Response.ok;
Expand All @@ -26,7 +27,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;

/**
Expand All @@ -45,37 +45,38 @@ public class FedoraRepository extends AbstractResource {
@Path("/describe/modeshape")
public Response describeModeshape() throws JsonGenerationException,
JsonMappingException, IOException, RepositoryException {

final Session session = repo.login();
logger.debug("Repository name: "
+ repo.getDescriptor(Repository.REP_NAME_DESC));
final Builder<String, Object> repoproperties = ImmutableMap.builder();
final Builder<String, Object> repoproperties = builder();
for (final String key : repo.getDescriptorKeys()) {
if (repo.getDescriptor(key) != null)
repoproperties.put(key, repo.getDescriptor(key));
}

// add in node namespaces
final NamespaceRegistry reg = ws.getNamespaceRegistry();
final Builder<String, String> namespaces = ImmutableMap.builder();
final NamespaceRegistry reg = session.getWorkspace()
.getNamespaceRegistry();
final Builder<String, String> namespaces = builder();
for (final String prefix : reg.getPrefixes()) {
namespaces.put(prefix, reg.getURI(prefix));
}
repoproperties.put("node.namespaces", namespaces.build());

// add in node types
final NodeTypeManager ntmanager = (NodeTypeManager) ws
.getNodeTypeManager();
final Builder<String, String> nodetypes = ImmutableMap.builder();
final NodeTypeManager ntmanager = (NodeTypeManager) session
.getWorkspace().getNodeTypeManager();
final Builder<String, String> nodetypes = builder();
NodeTypeIterator i = ntmanager.getAllNodeTypes();
while (i.hasNext()) {
NodeType nt = i.nextNodeType();
nodetypes.put(nt.getName(), nt.toString());
}
repoproperties.put("node.types", nodetypes.build());

return ok(
mapper.writerWithType(Map.class).writeValueAsString(
repoproperties.build())).build();
Map<String, Object> props = repoproperties.build();
session.logout();
return ok(mapper.writerWithType(Map.class).writeValueAsString(props))
.build();
}

@GET
Expand All @@ -87,6 +88,8 @@ public DescribeRepository describe() throws LoginException,
Session session = repo.login();
DescribeRepository description = new DescribeRepository();
description.repositorySize = getRepositorySize(session);
description.numberOfObjects = session.getNode("/objects").getNodes()
.getSize();
session.logout();
return description;
}
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/org/fcrepo/modeshape/foxml/FedoraOXML.java
Expand Up @@ -26,7 +26,7 @@
@Path("/foxml")
public class FedoraOXML extends AbstractResource {

private final Logger logger = Logger.getLogger(FedoraOXML.class);
//private final Logger logger = Logger.getLogger(FedoraOXML.class);

@PUT
@Path("/{filename}")
Expand All @@ -37,8 +37,6 @@ public Response addFOXML(@PathParam("filename") final String filename,
final Session session = repo.login();
if (session.hasPermission("/foxml", "add_node")) {
final String foxmlpath = "/foxml/" + filename;
logger.debug("Adding or updating FOXML file at " + ws.getName()
+ ":" + foxmlpath);
jcrTools.uploadFile(session, foxmlpath, foxml);
session.save();
session.logout();
Expand Down
Expand Up @@ -11,6 +11,9 @@ public class DescribeRepository {
@XmlElement
protected String repositoryVersion = FEDORA_VERSION;

@XmlElement
public Long numberOfObjects;

@XmlElement
public Long repositorySize;

Expand Down
47 changes: 45 additions & 2 deletions src/test/java/org/fcrepo/modeshape/FedoraRepositoryTest.java
@@ -1,12 +1,16 @@
package org.fcrepo.modeshape;

import static java.util.regex.Pattern.DOTALL;
import static java.util.regex.Pattern.compile;
import static javax.ws.rs.core.MediaType.TEXT_XML;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.regex.Matcher;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
Expand Down Expand Up @@ -50,10 +54,49 @@ public void testDescribe() throws Exception {
int status = client.executeMethod(method);
assertEquals(200, status);
final String description = method.getResponseBodyAsString();
logger.debug("Found a repository description:\n" + description);
logger.debug("Found the repository description:\n" + description);
assertTrue(
"Failed to find a proper repo versiom",
"Failed to find a proper repo version",
compile("<repositoryVersion>.*?</repositoryVersion>").matcher(
description).find());
}

@Test
public void testDescribeSize() throws Exception {
GetMethod describeMethod = new GetMethod(serverAddress
+ "rest/describe");
describeMethod.addRequestHeader("Accept", TEXT_XML);
int status = client.executeMethod(describeMethod);
assertEquals(200, status);
String description = describeMethod.getResponseBodyAsString();
logger.debug("Found a repository description:\n" + description);
Matcher check = compile("<repositorySize>([0-9]+)</repositorySize>",
DOTALL).matcher(description);
Long oldSize = null;
while (check.find()) {
oldSize = new Long(check.group(1));
}

PostMethod createObjMethod = new PostMethod(serverAddress
+ "rest/objects/fdfgdgsa");
assertEquals(201, client.executeMethod(createObjMethod));

GetMethod newDescribeMethod = new GetMethod(serverAddress
+ "rest/describe");
newDescribeMethod.addRequestHeader("Accept", TEXT_XML);
status = client.executeMethod(newDescribeMethod);
assertEquals(200, status);
String newDescription = newDescribeMethod.getResponseBodyAsString();
logger.debug("Found another repository description:\n" + newDescription);
Matcher newCheck = compile("<repositorySize>([0-9]+)</repositorySize>",
DOTALL).matcher(newDescription);
Long newSize = null;
while (newCheck.find()) {
newSize = new Long(newCheck.group(1));
}
logger.debug("Old size was: " + oldSize + " and new size was: "
+ newSize);
assertTrue("No increment in size occurred when we expected one!",
oldSize < newSize);
}
}

0 comments on commit 1a5d140

Please sign in to comment.