Search code examples
aemevent-listenersling

aem cq listener on multiple paths


I am trying to implement an Event listener using the observation manager. I need to listen on multiple paths.

But, we can register a listener on only one path I believe. Is there a way we can listen on multiple paths?

I have tried something like this

String pathvalues = "path1,path2,path3";
List < String > path = Arrays.asList(pathvalues.split(","));
session = repository.loginAdministrative(repository.getDefaultWorkspace());
observationManager = session.getWorkspace().getObservationManager();
for (String paths: path) {
 observationManager.addEventListener(this, Event.NODE_ADDED, paths, true, null, null, false);
}

But this is listening on only the last path it has iterated on. I guess that makes sense, so I'm still stuck.

and I found this on the net, SLING-4564

I implemented it, but somehow its still not listening.

If anyone has any inputs, please do let me know.


Solution

  • For your first issue:

    observationManager.addEventListener(this, Event.NODE_ADDED, paths, true, null, null, false);

    But this is listening on only the last path it has iterated on

    This is by design. The even listener only registers to one path and the last path provided in your loop will be the active path. Everything else before the last call to addEventListener will be ignored.

    There are 2 possible solutions to your problem:

    Register your listener on parent level and filter the events on even invocation.

    OR

    Use eventFilter.setAdditionalPaths(paths); to filter the events on multiple paths as described in SLING-4564

    First approach is more desirable as it allows you to implement optimal and quick filtering based on your logic. For example your quick filter could be to exclude /etc/ so you can easily evaluate the event path and check if it begins with /etc/ and discard it.

    SLING-4564 is basically designed for large activities like OAK startup and as a general guideline for performance, your application specific event listeners should be limited to application or content specific paths rather than being global in nature.