Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

SOLVED

Listener event not triggered

rajareddych
Level 2
Level 2

I am using below code to dynamically assign an ID to a component/template. Seems this is not getting triggered. Please help

import javax.jcr.Node;

import javax.jcr.RepositoryException;

import javax.jcr.Session;

import javax.jcr.observation.Event;

import javax.jcr.observation.EventListener;

import javax.jcr.observation.ObservationManager;

import javax.jcr.observation.EventIterator;

import org.apache.sling.api.resource.ResourceResolver;

import org.apache.sling.api.resource.ResourceResolverFactory;

import org.apache.sling.jcr.api.SlingRepository;

import org.osgi.service.component.annotations.Activate;

import org.osgi.service.component.annotations.Component;

import org.osgi.service.component.annotations.Deactivate;

import org.osgi.service.component.annotations.Reference;

import org.osgi.framework.BundleContext;

import org.osgi.service.component.ComponentContext;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.util.HashMap;

import java.util.Map;

import java.util.UUID;

@Component(

immediate=true,

service= EventListener.class

)

public class UniqueIDListener implements EventListener {

    private Logger log = LoggerFactory.getLogger(this.getClass());

   

    private BundleContext bundleContext;

       

    @Reference

    private SlingRepository repository;

 

    //Inject a Sling ResourceResolverFactory

    @Reference

    private ResourceResolverFactory resolverFactory;

    private Session session;

    private ObservationManager observationManager;

   

    public void run() {

    log.info("Unique ID Process Running..");

    }

   

    @Activate

    public void activate(ComponentContext context) throws Exception {

    this.bundleContext = context.getBundleContext();

  

        log.info("Activating Unique ID");

        try {

        //Invoke adaptTo method to create a Session

            Map<String, Object> param = new HashMap<String, Object>();

    param.put(ResourceResolverFactory.SUBSERVICE, "datawrite");

  

    ResourceResolver resolver = resolverFactory.getServiceResourceResolver(param);

Session session = resolver.adaptTo(Session.class);

           

    //Setup the event handler to respond to a new node under /content/experience-fragments/aem

    observationManager = session.getWorkspace().getObservationManager();

//    final String[] nodetypes = {"cq:Page"};

    final String path = "/content/experience-fragments/ahm/language_masters/english/widgets"; //define path

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

  

        } catch (Exception e) {

            log.error("Unable to register session", e);

            throw new Exception(e);

        }

    }

 

    @Deactivate

    public void deactivate(ComponentContext componentContext) throws RepositoryException {

  

    if (observationManager != null) {

    observationManager.removeEventListener(this);

    }

        if (session != null) {

        session.logout();

        session = null;

        }

    }

   

    //Defines logic that is fired when the event occurs

    public void onEvent(EventIterator itr) {

    UUID id = UUID.randomUUID();

  

        try {

        while (itr.hasNext()) {

                Event newEvent = itr.nextEvent();

 

                //log the time when the event occurred

                log.info("A new node was added.. : {}", newEvent.getPath());

 

                //Check if node exists and it is a content node of the newly created page

                if (session.nodeExists(newEvent.getPath()) && session.getNode(newEvent.getPath()).getProperty("jcr:primaryType").getString().equals("cq:PageContent")) {

                    Node contentNode = session.getNode(newEvent.getPath());

 

                    if (contentNode.getProperty("resourceID") != null) {

                    contentNode.setProperty("resourceID", id.toString());

                    } 

                } 

            } session.save(); 

        } catch(Exception e){ 

            log.error("Error while treating page creation events",e);

        } 

    } 

}

1 Accepted Solution
smacdonald2008
Correct answer by
Level 10
Level 10

Reason it's not working is because this code does not work for Event Handlers:

Map<String, Object> param = new HashMap<String, Object>();

param.put(ResourceResolverFactory.SUBSERVICE, "datawrite");

ResourceResolver resolver = resolverFactory.getServiceResourceResolver(param);

Session session = resolver.adaptTo(Session.class);

That code works for most other use cases. For Event Listeners - use this:

@Reference

     org.apache.sling.jcr.api.SlingRepository repository;

     

     @Activate

     public void activate(ComponentContext context) throws Exception {

     log.info("activating ExampleObservation");

     try {

         adminSession = repository.loginService("datawrite",null);

         adminSession.getWorkspace().getObservationManager().addEventListener(

          this, //handler

          Event.PROPERTY_ADDED|Event.NODE_ADDED, //binary combination of event types

          "/apps/example", //path

          true, //is Deep?

          null, //uuids filter

          null, //nodetypes filter

          false);

Creating an Event Listener for Adobe Experience Manager 6.4

View solution in original post

2 Replies
smacdonald2008
Correct answer by
Level 10
Level 10

Reason it's not working is because this code does not work for Event Handlers:

Map<String, Object> param = new HashMap<String, Object>();

param.put(ResourceResolverFactory.SUBSERVICE, "datawrite");

ResourceResolver resolver = resolverFactory.getServiceResourceResolver(param);

Session session = resolver.adaptTo(Session.class);

That code works for most other use cases. For Event Listeners - use this:

@Reference

     org.apache.sling.jcr.api.SlingRepository repository;

     

     @Activate

     public void activate(ComponentContext context) throws Exception {

     log.info("activating ExampleObservation");

     try {

         adminSession = repository.loginService("datawrite",null);

         adminSession.getWorkspace().getObservationManager().addEventListener(

          this, //handler

          Event.PROPERTY_ADDED|Event.NODE_ADDED, //binary combination of event types

          "/apps/example", //path

          true, //is Deep?

          null, //uuids filter

          null, //nodetypes filter

          false);

Creating an Event Listener for Adobe Experience Manager 6.4

View solution in original post