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.
- 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. - Create the following class variables:
private SlingRepository repository; private ResourceResolverFactory resolverFactory; private Session session; private ObservationManager observationManager;
- Create an activate() method.
This method gets called when the component get activated. - Create a session object.
session = repository.loginAdministrative(null);
- Create an observationManager object.
observationManager = session.getWorkspace().getObservationManager();
- Use the observationManager’s addEventListener method to create a custom event.
observationManager.addEventListener(this, Event.NODE_ADDED, "/content", true, null, null, false);
- 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 "); } - 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.)
- Now, let us test it. Got to the Content folder and create a new test page.
- Open the log file and observe that the onEvent method is called.
Leave a comment