Report asset sizes in Magnolia

Sometimes editors want to know where large assets are "hidden" in Magnolia DAM. For one project, I quickly created a Groovy script to generate a report listing assets by size. I used Magnolia's Groovy App to develop and test the script:

Groovy script in Magnolia Groovy App

Groovy script

			 
 import javax.jcr.PropertyIterator
 import javax.jcr.Property 
 import java.text.NumberFormat
 import java.text.DecimalFormat
 import org.apache.commons.lang3.StringUtils

 def assetPath = "/"

 session = MgnlContext.getJCRSession('dam')
 root = session.getNode(assetPath)

 // sep char for importing into Numbers / Excel
 sep = ";"

 numberPatternMB = "###.##"
 numberPatternKB = "###"
 assetCount = 0

 def sortFunction = {a, b ->
   def aAssetSize = PropertyUtil.getLong(a.getNode("jcr:content"), "size")
   def bAssetSize = PropertyUtil.getLong(b.getNode("jcr:content"), "size")
   return bAssetSize.compareTo(aAssetSize)
 }

 assets = NodeUtil.collectAllChildren(root).findAll { n ->
  n.getProperty("jcr:primaryType").getString() == 'mgnl:as set' && n.hasNode("jcr:content") &&   n.getNode("jcr:content").hasProperty("size")
 }

 def formatContentSize(content) {
   fileSizeInBytes = PropertyUtil.getLong(content, "size")  
   fileSizeInKB = fileSizeInBytes / 1024;
   fileSizeInMB = fileSizeInKB / 1024;

   sizeMB = StringUtils.replace(new DecimalFormat(numberPatternMB).format(fileSizeInMB), ",", ".")
   sizeKB = StringUtils.replace(new DecimalFormat(numberPatternKB).format(fileSizeInKB), ",", ".")

   return sizeMB + "${sep}" + sizeKB + "${sep}"
 }

 println "Size MB${sep}Size KB${sep}Full Path${sep}Filename${sep}Extension${sep}Height (Pixels)${sep}Width (Pixels)\n"

 // display report
 assets.sort(sortFunction).each { a ->
   content = a.getNode("jcr:content")
   ext = PropertyUtil.getString(content, "extension", "--")
   name = PropertyUtil.getString(content, "fileName", "--")
   height = PropertyUtil.getString(content, "height", "--")
   width = PropertyUtil.getString(content, "width", "--")
   println formatContentSize(content) + a.getPath() + "${sep}" + name + "${sep}" + ext + "${sep}" + height + "${sep}" +  width
   assetCount++
 }

 return "Found '${assetCount}' assets in DAM path '${assetPath}'"
    	
		

You can find the file here:  mgnl-dam-asset-sizes.groovy
Change the code as needed.

NOTE: I used a semicolon as column delimiter because this is the standard in Switzerland. In Switzerland, decimals are separated by a dot, not a comma as in Germany.

After executing, you can copy & paste the result into your text editor of choice, save the file to disk as text with a .csv extension, and open it with your favorite spreadsheet application:

Asset size report imported into a spreadsheet

Now you can add some nice colors and formatting and share the spreadsheet with your internal or external client...

Groovy logo