How to write Listeners in Cq5 (Part – I)

At times you want to listen to events and when those events actually happen you need to perform some action. Today, we gonna see how to write listeners in cq5. In AEM you can listen to events at minute level like Properties/node getting added to various other events in workflow etc.

The code example i am putting below is just an example of how you can listen to events at very minute level into the repository.  We bind the code  with an event of Node being added to a certain path. If the node is added then the code is activated and it sets a property at that node.

You have to keep a note that the below listeners if written, will not be cluster aware.  In case you happen to use this code sample, please keep in mind that on each node/property being added the code will execute on each of your servers. This code uses Java Content Repository JCR API. In part 2 we will deal with Sling API that will be cluster aware.

 @Component(metatype = true, immediate = true, label = "Replication Listner", description = "Listen to events")  
 @Service(value = ReplicationListnerConfigure.class )  
 public class ReplicationListnerConfigure implements EventListener{  
 private SlingRepository slingRepo;  
 private ResourceResolverFactory resourceResolverFactory;  
 private Session session;  
 private ResourceResolver resourceResolver;  
 public void activate(ComponentContext componentContext){  
           resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);  
           session = slingRepo.loginAdministrative(null);  
           ObservationManager obsManager = session.getWorkspace().getObservationManager();  
           obsManager.addEventListener(this, Event.NODE_ADDED, "/content/usergenerated/content/", true, null, null, false);  
//listening to events
      }catch(Exception e){  
 public void onEvent(EventIterator events) {  
           Event myEvent = events.nextEvent();  
           try {  
                Resource resource = resourceResolver.resolve(myEvent.getPath());  
                Node node = resource.adaptTo(Node.class);  
                node.setProperty("cq:distribute", true);  //setting the property
           } catch (RepositoryException e) {  
      public void deactivate(ComponentContext componentContext){  


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s