Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sling resource vs nodes

Tags:

java

sling

I'm having trouble understanding why you would use resources instead of nodes in sling. So say I have something simple accessing nodes like below:

NodeIterator headerNode = currentNode.getNodes();
//loop through and do something with the nodes.

How would you work in resources instead of nodes. I've heard you should generally work in resources in sling not nodes. But why? I really don't understand what the benefit to this would be. I think I'm having trouble grasping what resources are as well. I know there's documentation but I can't find any code samples on how to use them.

like image 683
Delmon Young Avatar asked May 16 '13 00:05

Delmon Young


1 Answers

The main documentation to look at is http://sling.apache.org/documentation/the-sling-engine/resources.html which explains the Resource concept and how you work with them.

The API is somewhat different from the JCR nodes API, but uses similar concepts. The one thing which is definitely simpler with Resources is accessing property values, as you get them in a ValueMap and missing properties don't throw exceptions for example.

The above docs should explain the main patterns, in short those are:

  • You get a Resource from the Sling Request, or using a ResourceResolver service
  • A Resource can be adapted to a ValueMap to access its properties
  • A Resource can be adapted to a Node if you need to switch to the JCR API
  • Resource.listChildren(...) is similar to Node.getNodes()
  • Resource.getResourceResolver() provides a ResourceResolver that gives access to other Resources by searching or by path.

The Resource exists to abstract the content storage, to make it possible to use other backends than JCR in Sling and to unify Sling's view on the data and content that it uses internally.

For application-level programming, in my opinion the JCR API is very nice, I wouldn't use Resource instead just for the sake of it. But there are some cases where the Resource API makes things simpler.

like image 98
Bertrand Delacretaz Avatar answered Oct 07 '22 05:10

Bertrand Delacretaz