Accessing resource data from JCR repo

Raja picture Raja · Jun 5, 2013 · Viewed 10.3k times · Source

Using sling resource interface I am trying to get access the data saved as a binary property to my JCR node. Currently I am doing it in the following ways , which is returning me a null value.

Resource dataResource = resourceResolver.getResource("/testNode/A/test.txt");
ValueMap properties = dataResource.adaptTo(ValueMap.class);        

String expected = properties.get("jcr:data").toString(); // null
InputStream content = (InputStream) actualProp.get("jcr:data");  // null 

Can anyone let me know what is missing , or what is the best way to read the jcr:data property , which is present as a binary data. The dataResource is a nt:unstructured one.

the output it shows is :- org.apache.sling.jcr.resource.internal.helper.LazyInputStream@4f4c8085

Answer

diffa picture diffa · Jun 10, 2013

You mention that you were using the Sling resource API rather than the JCR API. You can adapt the resource to an InputStream directly from a Resource like so:

Resource dataResource = resourceResolver.getResource("/testNode/A/test.txt/jcr:content");
InputStream is = dataResource.adaptTo(InputStream.class);

As long as the resource is an nt:file or nt:resource, the contents of the jcr:data attribute should be returned as an InputStream.

From there you can read from the InputStream as Tuan suggested in his answer.

You can see an example of this functionality from the following unit test: http://svn.apache.org/repos/asf/sling/whiteboard/fmeschbe/resource/jcr.resource/src/test/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceTest.java