CQ - Check whether the resource object is valid

10.1k views Asked by At

I need to check whether the resource object is valid or not for the below 'resource' object. For example If I pass any url like getResource("some path which is not available in cq") in this case I need to restrict it

Resource resource= resourceResolver.getResource(/content/rc/test/jcr:content");
Node node = resource.adaptTo(Node.class);
String parentPagePath= node.getProperty("someproperty").getValue().getString();

Is there any way to do?

2

There are 2 answers

0
Thomas On BEST ANSWER

If you are using getResource a null check is sufficient. If you use resolve, then you have to use the !ResourceUtil.isNonExistingResource(resource). On Node level you can check the existence of a property with hasProperty.

0
Sabya On

As Thomas said , ResourceResolver.getResource() returns null if the path you provide as argument does not exist. A null check on the resource should get your problem solved .

Resource resource= resourceResolver.getResource("some path which is not available in cq");
if(resource != null){
Node node = resource.adaptTo(Node.class);
String parentPagePath= node.getProperty("someproperty").getValue().getString();
}

Just a side note : Its mostly better to play around with a wrapper than to work with a lower level API unless there is a compelling reason to do so.

Hence , I would recommend you to deal with ValueMap(Sling API) to retrieve/set properties of Node rather than dealing with the Node (JCR API)

Resource resource= resourceResolver.getResource("some path which is not available in cq");
    if(resource != null){
    ValueMap mapWithAllTheValues = resource.adaptTo(ValueMap.class);
    String parentPagePath= mapWithAllTheValues.get("someproperty", String.class);
    }

Ref : https://docs.adobe.com/docs/en/cq/5-6-1/javadoc/org/apache/sling/api/resource/ResourceResolver.html#getResource(java.lang.String)