Skip to content

Instantly share code, notes, and snippets.

@bdelacretaz
Last active July 1, 2016 13:17
Show Gist options
  • Save bdelacretaz/9cbb07de84f2ae74e6a54438522686ff to your computer and use it in GitHub Desktop.
Save bdelacretaz/9cbb07de84f2ae74e6a54438522686ff to your computer and use it in GitHub Desktop.
Groovy JsonBuilder with simulated Sling resource wrapper
// Experimenting with Groovy JsonBuilder as a way to implement
// a JSON builder script engine for Sling
// The Sling .jsonbuild script would only contain the part
// between // SCRIPT markers below, the rest is glue that
// this new scripting engine would provide
// We'll probably need a Groovy-friendly wrapper
// with convenience methods for the current resource,
// where the tree navigation starts from
class Resource {
String path
def props = [ : ]
Resource(path) {
this.path = path
props["title"] = "This is ${this.path}"
}
// get a specific child resource
def child(path) {
new Resource(this.path + "/" + path)
}
// get list of child resources, simulating a query
def children(prefix, number) {
def result = []
for(i in 1..number) {
result << child(prefix + "_" + i)
}
result
}
}
// The Sling script engine would provide the current
// resource wrapped in this r variable
r = new Resource("/currentResource")
out = new java.io.OutputStreamWriter(System.out)
new groovy.json.StreamingJsonBuilder(out) .
// SCRIPT - this is the part that's supplied as a Sling script
root {
def kids = r.child("sub").children("kid", 3)
path r.path
title r.props.title
childCount kids.size
childPaths kids.collect { r -> path:r.path }
}
// SCRIPT ends here
out.flush()
/* Typical output
{
"root": {
"path": "/currentResource",
"title": "This is /currentResource",
"childCount": 3,
"childPaths": [
"/currentResource/sub/kid_1",
"/currentResource/sub/kid_2",
"/currentResource/sub/kid_3"
]
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment