Almost all the components we write, there is a need to traverse the node and retrieve properties from a node. Usually we end writing large amount of code, adding null checks and checking hasProperty() in each if block.
There is one java class provided by sling which will make our developer life very easy. The class name is “ResourceUtil”.
ResourceUtil provides many static method which will help us finding resource and then get ValueMap of the properties that are present on that resource/node.
Example:
For code like:
Resource myResource = resourceResolver.getResource(“/content/mypage/jcr:content”);
String value1 = “”;
String value1 = “”;
if(null != myResource) {
if(myResource.hasProperty(“key”)) {
value = myResource.getProperty(“key”);
}
if(myResource.hasProperty(“key2”)) {
value2 = myResource.getProperty(“key2”);
}
}
We can write this code using ResourceUtil class is:
Resource myResource = resourceResolver.getResource(“/content/mypage/jcr:content”);
ValueMap valueMap = ResourceUtil.getValueMap(myResource);
String value1 = valueMap.get(“key1″,””);
String value1 = valueMap.get(“key2″,””);
So if you see the above block, i have not used any if blocks to check for null values or hasProperty. ResourceUtil takes care of the null checks and provides us with the empty value if the resource doesn’t exists.
ResourceUtil has many other important methods as well. Explore it.
Happy CQ learning! 🙂
Leave a comment