Skip to content

Instantly share code, notes, and snippets.

@ahmed-musallam
Last active June 8, 2022 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahmed-musallam/b5cf0e4623049fea2b4251dc5c32bc6a to your computer and use it in GitHub Desktop.
Save ahmed-musallam/b5cf0e4623049fea2b4251dc5c32bc6a to your computer and use it in GitHub Desktop.

Estimate the total size of a JCR path

This servlet basically finds all binaries in a path and aggrigates their sizes to estimate the path size. Helpful to estimate a package size before creating it.

Usage

deploy EstimatePathSize.java in a bundle to your local AEM instance. use the following url pattern to get size: <aem-server>/bin/pathsize.json/<JCR path>

example, to get size of /content/dam you can run:

http://localhost:4502/bin/pathsize.json/content/dam/

returns the JSON:

{
   result: "4602938KB"
}

Groovy console code

EstimatePathSize.groovy can be copied and pasted to grovy console: https://github.com/OlsonDigital/aem-groovy-console. Does the same thing as the servlet.

// this code is the same as the servlet but for grovy console: https://github.com/OlsonDigital/aem-groovy-console
// OPTIONS
def PATH = '/content/dam/'
def query = createQuery([path:PATH, type:'nt:file', 'p.limit':'99999999999999999'])
def result = query.getResult();
long totalSizeInKB = 0
result.getHits().each{
def node = it.node
if(!node) return; // cannot get node for some reason
def nodeSizeInKB = node.getProperty("jcr:content/jcr:data").getLength() / 1024;
totalSizeInKB = totalSizeInKB + nodeSizeInKB;
}
println totalSizeInKB+' KB'
package sample.core.servlets;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.Hit;
import com.day.cq.search.result.SearchResult;
import com.day.crx.packaging.JSONResponse;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Servlet that gets the size (in KB) of all binaries (nt:file) in a path
*/
@SlingServlet
(
paths = "/bin/pathsize",
extensions = "json",
methods = "GET"
)
public class EstimatePathSize extends SlingSafeMethodsServlet {
private static final String jcr_data = JcrConstants.JCR_CONTENT+"/"+JcrConstants.JCR_DATA;
private static final Logger log = LoggerFactory.getLogger(EstimatePathSize.class);
@Reference
private QueryBuilder queryBuilder;
@Override
protected void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException, IOException {
// get the resource by the suffix
// for example, in the request /bin/pathsize.json/apps, "/apps" is the suffix and that's the resource obtained here.
Resource resource = request.getRequestPathInfo().getSuffixResource();
// resource is null, does not exist, not null, exists
boolean exists = resource == null? false : true;
String path = request.getRequestPathInfo().getSuffix();
if(!exists)
{
response.sendError(400, "path does not exist: "+ path);
return;
}
else
{
try
{
long sizeInKb = getPathSize(path, request.getResourceResolver().adaptTo(Session.class));
writeResponse(response, sizeInKb+"KB");
} catch (RepositoryException e)
{
response.sendError(500);
log.error("error with one of the search result hits", e);
}
}
}
/**
* Gets the combined sizes of all binaries in the tree at path
* @param path The path to check
* @param session The jcr session to use
* @return The size in KB (Kilobyte)
* @throws RepositoryException
*/
private long getPathSize(String path, Session session) throws RepositoryException {
Map<String, String> map = new HashMap<String, String>();
map.put("path", path);
map.put("type", JcrConstants.NT_FILE); // find nt:file nodes
map.put("p.limit", Integer.toString(Integer.MAX_VALUE)); // no limit
Query query = queryBuilder.createQuery(PredicateGroup.create(map), session);
SearchResult result = query.getResult();
long totalSizeInKB = 0;
// Iterate over the Hits and get size
for (final Hit hit : result.getHits()) {
Node node = hit.getNode();
if(node == null) continue;
totalSizeInKB = totalSizeInKB + node.getProperty(jcr_data).getLength() / 1024;
}
return totalSizeInKB;
}
private void writeResponse(SlingHttpServletResponse response, String result) throws ServletException, IOException
{
// make the response content type JSON
response.setContentType(JSONResponse.APPLICATION_JSON_UTF8);
response.getWriter().write("{\"result\": \""+result+"\"}"); // Should use a JSON library, but its dead-simple, there is no need...
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment