Search code examples
eventslistenerreplicationaem

AEM 6.3 Set up PageEvent Handler/Listener


Im currently working on setting up a event handler for page creations and deletions on aem to then call one of our vendors API.

Ive been basing my work on a module we already have that listens to replication events.

So far i was able to reproduce that behavior on my module and trigger the code upon replications. However, i only need the calls to the API on Page Publications and deletions.

Ive been trying to find how to diferentiate between replications and page deletions and activations.

So far, it seems that AEM handles crx replications and page publications as the same type of event "type= ACTIVATION".

If i delete a page, it does set the type as "DELETE" so i can work with that to call the API but for the page publications im lost since as i mentioned, AEM looks like it handles CRX replications and pages publications as the same type.

After some research, i found the PageEvent API and I tried to set up a Page Event Listener but it is not getting triggered upon publications or deletions of pages, so im not sure that if what im trying to do its possible or maybe my componet is located on a wrong part of the project to listen for Page Events.

Thanks beforehand


Solution

  • This below code works fine to detect page deletion event :

    @Component(
            service = {
                    EventHandler.class,
                    JobConsumer.class
            },
            immediate = true,
            configurationPolicy = ConfigurationPolicy.OPTIONAL,
            property = {
                    "event.topics=" + PageEvent.EVENT_TOPIC,
                    JobConsumer.PROPERTY_TOPICS + "=" + "aem/custom/event"
            }
    )
    
    public class CustomEventHandler implements EventHandler, JobConsumer {
    
        @Override
        public void handleEvent(Event event) {
            PageEvent pageEvent = PageEvent.fromEvent(event);
            Map<String, Object> properties = new HashMap<>();
            properties.put("pageEvent", pageEvent);
            jobManager.addJob("aem/custom/event", properties);
        }
    
        @Override
        public JobResult process(Job job) {
            PageEvent pageEvent = (PageEvent) job.getProperty("pageEvent");
            try {
                if (pageEvent != null && pageEvent.isLocal()) {
                    Iterator<PageModification> modificationsIterator = pageEvent.getModifications();
                    while (modificationsIterator.hasNext()) {
                        PageModification modification = modificationsIterator.next();
    
                        if (PageModification.ModificationType.DELETED.equals(modification.getType())) {
                            // Your logic
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("Error : ", e);
            }
            return JobResult.OK;
        }
    }