Senthil Senthil - 3 months ago 27
Groovy Question

Using groovy script HttpBuilder request object, i need to validate the AEM node existence in JCR via http calls

Using groovy script, i am using HTTPBuilder request object: i need to check whether the AEM Parent node exist and create.

Details:
I am using this CLI script http://www.tothenew.com/blog/content-migration-in-aem-using-slingpostservlet/ to create nodes while migrating contents from XML. In the XML file i have a field which contains the full path of the parent node. I need to verify whether that node exist or not. If not i need to create that node. Kindly suggest.

Answer

Since you are using groovy and httpbuilder module, you could simply check if a Http GET on the complete resource path url with a json extention returns a HTTP 200 or a HTTP 404. HTTP 200 means the resource exists, 404 means the node does not exist.

Following is an simple example to determine if a JCR node exists or not. Kindly note that the code below does not create a missing node and is for illustration purpose only.

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.HttpResponseException

import static groovyx.net.http.ContentType.JSON

HTTPBuilder local = new HTTPBuilder("http://localhost:4502")
local.auth.basic("<USERNAME>", "<PASSWORD>")

def getStatus = {
    resourcePath ->
        try {
            local.get(
                    path: resourcePath + ".json",
                    contentType: JSON
            ) {
                resp, reader ->
                    return resp.status
            }
        } catch (HttpResponseException httpResponseException) {
            return httpResponseException.statusCode
        }
}

def nodePath = '/content/geometrixx-outdoors/en/men'
def httpNodeStatus = getStatus(nodePath);
if (httpNodeStatus == 404) {
    println('node : ' + nodePath + ' does not exist. creating node')
    // Code to create node
} else if (httpNodeStatus == 200) {
    println('node : ' + nodePath + ' exists')
    // Node exists
} else {
    println('HTTP Status for node : ' + httpNodeStatus)
    // handle other response codes
}