May 8, 2020
Estimated Post Reading Time ~

How-to Retrieve All Properties Including Metadata Of An Asset From AEM

When we need to return all the properties of an Asset (or a Node, Asset is also a node), there is no single method that will return all the properties. We have to do this in a combination. This article details the steps.

Step-by-step guide
For each found result/node, we have to do the following:
  1. Get all the top level properties (Node root level). These include `jcr:created`, `jcr:createdBy`, etc.
  2. Get all `jcr:content` level properties. These include `cq:name`, `cq:lastModified`, etc
  3. Get all `jcr:content\metadata` level properties. These include `dc:title`, any custom metadata etc.
  4. You can add all these to another new `ValueMap` that can hold all the properties of a particular Node/Asset.
Below is a code snippet:
AEMGetAllPropertiesOfAnAsset
Resource resource;
ValueMap mainProperties;
ValueMap assetMetadataProperties;
Resource metadataResource;
ValueMap jcrProperties;
Resource jcrdataResource;
ValueMap allProperties;

for (Hit hit : result.getHits()) {
  //LOGGER.info("nHit path="+hit.getPath()+", title="+hit.getTitle()); resource = hit.getResource();
  
  if(null!=resource){ mainProperties = resource.getValueMap();
    // Add JCR Properties
    jcrdataResource = resource.getChild("jcr:content");
    jcrProperties = ResourceUtil.getValueMap(jcrdataResource);
  
    // Add Metadata properties
    metadataResource = resource.getChild("jcr:content/metadata");
    assetMetadataProperties = ResourceUtil.getValueMap(metadataResource);
    
    // Adding all together
    allProperties = new ValueMapDecorator(new HashMap());
    allProperties.putAll(hit.getProperties());
    allProperties.putAll(mainProperties); // Includes jcr:created createdDate etc.
    allProperties.put("jcr:path",hit.getPath()); //Add Path
    allProperties.putAll(jcrProperties);
    allProperties.putAll(assetMetadataProperties);
    
    //LOGGER.debug("All Asset Properties="+new Gson().toJson(allProperties)); 
  } 
 }


Note
  1. `jcr:path` is not returned by any of the above. So I had to explicitly add it using `hit.getPath`
  2. The name of the node or Asset name can be pulled from `hit.getTitle()`. Of course, this is also returned as part of `cq:name`.
  3. There are other ways to get properties as well. One another way is to get the `Node` and retrieve the properties. `com.day.cq.search.result.Hit` has a method `getNode()` that returns a `java.jcr.Node` interface and you can use that get to fetch the properties.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.