Last active
July 5, 2016 12:40
-
-
Save bdelacretaz/dc0a0ec4fada97fa2151bf3b74aa4788 to your computer and use it in GitHub Desktop.
Sling .groovy rendering script that uses Groovy's JsonBuilder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sling .groovy rendering script that uses Groovy's JsonBuilder | |
// Requires the groovy, groovy-json, groovy-templates and groovy-jsr233 bundles, so | |
// that /system/console/status-slingscripting lists the Groovy engine. | |
// Also requires adding "groovy" as an additional extension to the | |
// org.apache.sling.scripting.core.impl.ScriptCacheImpl config | |
import groovy.json.StreamingJsonBuilder | |
def builder = new StreamingJsonBuilder(out) | |
def getChildren(r) { | |
r.resourceResolver.listChildren(r) | |
} | |
def maybe(r, output, name) { | |
// We might want a lazy adaptor for props | |
def props = r.adaptTo org.apache.sling.api.resource.ValueMap.class | |
if(props.get(name) != null) { | |
output << [ "${name}":props.get(name) ] | |
} | |
} | |
def basics(r) { | |
// We might want a lazy adaptor for props | |
def props = r.adaptTo org.apache.sling.api.resource.ValueMap.class | |
def result = [ path:r.path ] | |
maybe(r, result, "title") | |
maybe(r, result, "sling:resourceType") | |
result | |
} | |
def recurse(r) { | |
def result = basics(r) | |
def kids = getChildren(r) | |
if(kids.hasNext()) { | |
result << [ children:kids.collect { recurse(it) } ] | |
} | |
result | |
} | |
builder . "${resource.name}" { | |
def mimeTypes = sling.getService(org.apache.sling.commons.mime.MimeTypeService.class) | |
date new java.util.Date() | |
"mime-type" mimeTypes.getMimeType(request.requestPathInfo.extension) | |
resource recurse(resource) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment