Create a custom JCR event

In this session, we will see how to create a custom event and manage it. A custom event helps you to manage a specific activity happened on an AEM instance. For example, you want to send an e-mail to an editor as soon as an AEM page is created by a content creator; so that the editor is aware that the page needs to be edited at a later stage.

Let us start. We will create a new AEM component for creating a custom event.

  1. Inside com.aemcompany.myproject.impl, create a new class EventManagerImpl.java.
    Note that the class is extended by EventListener interface that provides you the methods to manage the event.
  2. Create the following class variables:
    private SlingRepository repository;
    private ResourceResolverFactory resolverFactory;
    private Session session;
    private ObservationManager observationManager;
  3. Create an activate() method.
    This method gets called when the component get activated.
  4. Create a session object.
    session = repository.loginAdministrative(null);
  5. Create an  observationManager object.
    observationManager = session.getWorkspace().getObservationManager();
  6. Use the observationManager’s addEventListener method to create a custom event.
    observationManager.addEventListener(this, Event.NODE_ADDED, "/content", true, null, null, false);
  7. Implement an onEvent method.
    We will use this method to log an event whenever the custom event is fired.

    public void onEvent(EventIterator itr) {
    log.info("A new node was added to /content ");                       
    }
  8. Create deactivate() method basically to ensure to log the session out before the component gets deactivated. (Which is not explained, since it’s not directly related to the custom event.)
  9. Now, let us test it. Got to the Content folder and create a new test page.
  10. Open the log file and observe that the onEvent method is called.

 

Comments are closed.