Update a node property using an AEM bundle

In the previous session, we have seen how to obtain a Resource. We later, translated the Resource into a Page object, and then programmatically obtained its title. We will see one more example. Here, using an AEM bundle, we will write a property to the Page we created. In this case too, we need to use a Resource object to obtain a Session object using which we can save what we write.

Let us start:

  1. Create a new interface: SearchService.java.
    (There is a reason for using this name. In the next session, we are going to discuss about searching.)
  2. Add the following method.
    public void addProperty();.
  3. Create the implementation class: SearchServiceImpl.java
  4. Implement the addProperty() method.
  5. Get the ResourceResolver.
    (Visit the previous post to see what the code accomplishes.)
    Map<String, Object> param = new HashMap<String, Object>();  
    param.put(ResourceResolverFactory.SUBSERVICE, "readService");
    ResourceResolver resourceResolver=null;
    resourceResolver = resolverFactory.getServiceResourceResolver(param);
  6. Obtain the resource.
    Resource pageResource = resourceResolver.getResource("/content/aem-company/jcr:content");

    Note that we need to add the property to the jcr:content node of the page we created.

  7. Translate the resource into a node using the adaptTo() class.
    Node myNode = pageResource.adaptTo(Node.class);
  8. Set a property to the node.
    myNode.setProperty("author", "sunil");
  9. Obtain the session from resourceResolver.
    Session session = resourceResolver.adaptTo(Session.class);
  10. Save the session:
  11. Deploy the bundle.
  12. Add a method in the bundleservice component.
    com.aemcompany.myproject.SearchService searchService=sling.getService(com.aemcompany.myproject.SearchService.class);
  13. Access the page so that the method is called.
  14. Log into CRXDELite.
  15. See the page properties and ensure that the new property is added.
    That’s it. See you soon.

Comments are closed.