EVENT HANDLER WHICH SEND MAIL WHEN NODE IS CREATED IN CQ(AEM)
Event
handling can be done in a lot of different ways within CQ, that all
have their cost, their impact, and their benefits.
Five
ways of doing such events are detailed here
- At the JCR level with observation
- At the Sling level with event handlers and jobs
- At the CQ level with workflows & launchers
- Particular case of scheduled event
- Particular case of POST to the repository
JCR
Observer
Is the lowest-level
event handling in CQ. As its name indicates it, is at JCR level and
allows to listen to JCR-level events, gathered in sets (corresponding
to persistence transactions). javax.jcr.observation.Event lists
following types:
·
Event.NODE_ADDED
· Event.NODE_MOVED
· Event.NODE_REMOVED
· Event.PERSIST
· Event.PROPERTY_ADDED
· Event.PROPERTY_CHANGED
· Event.PROPERTY_REMOVED
· Event.NODE_MOVED
· Event.NODE_REMOVED
· Event.PERSIST
· Event.PROPERTY_ADDED
· Event.PROPERTY_CHANGED
· Event.PROPERTY_REMOVED
In
order to listen to such an event, you have to:
·
Manage a live session through which you will listen to the
repository
· Decide how and when you listen to it.
· Implement the handler that receive all JCR events filtered by your definition.
· Decide how and when you listen to it.
· Implement the handler that receive all JCR events filtered by your definition.
STEP WHICH YOU HAVE TO
FOLLOW-----
- Create Maven bundle-If you are not familiar with this follow this link-http://tutorials.jenkov.com/maven/maven-tutorial.html
- Make package in the bundle and inside make java file like
- Paste below code in the java fileimport org.apache.felix.scr.annotations.Component;
import
org.apache.felix.scr.annotations.Service;
import
org.osgi.framework.BundleContext;
import
org.osgi.service.component.ComponentContext;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
java.util.ArrayList;
import
java.util.Arrays;
import
javax.jcr.Node;
import
javax.jcr.Repository;
import
javax.jcr.RepositoryException;
import
javax.jcr.Session;
import
javax.jcr.observation.Event;
import
javax.jcr.observation.EventIterator;
import
javax.jcr.observation.EventListener;
import
javax.jcr.observation.ObservationManager;
import
org.apache.sling.jcr.api.SlingRepository;
import
org.osgi.service.component.ComponentContext;
import
org.apache.felix.scr.annotations.Activate;
import
org.apache.felix.scr.annotations.Component;
import
org.apache.felix.scr.annotations.Properties;
import
org.apache.felix.scr.annotations.Property;
import
org.apache.felix.scr.annotations.Reference;
import
org.apache.felix.scr.annotations.Service;
//Sling
Imports
import
org.apache.sling.api.resource.ResourceResolverFactory ;
import
org.apache.sling.api.resource.ResourceResolver;
import
org.apache.sling.api.resource.Resource;
import
java.text.SimpleDateFormat;
import
java.util.Calendar;
import
org.apache.commons.mail.Email;
import
org.apache.commons.mail.EmailException;
import
org.apache.commons.mail.SimpleEmail;
//mail
api import
import
com.day.cq.mailer.MessageGateway;
import
com.day.cq.mailer.MessageGatewayService;
@Component(metatype=true)
@Service
public
class
Eventhandle implements
Runnable,EventListener {
//Inject
a MessageGatewayService
@Reference
private
MessageGatewayService messageGatewayService;
private
Logger log
= LoggerFactory.getLogger(this.getClass());
private
BundleContext bundleContext;
//Inject
a Sling ResourceResolverFactory
@Reference
private
ResourceResolverFactory resolverFactory;
private
Session session;
private
ObservationManager observationManager;
//Inject
a Sling ResourceResolverFactory to create a Session requited by the
EventHandler
@Reference
private
SlingRepository repository;
public
void
run() {
log.info("Running...");
}
//Place
app
logic here to define the AEM Custom Event Handler
protected
void
activate(ComponentContext ctx) {
this.bundleContext
= ctx.getBundleContext();
try
{
//Invoke
the adaptTo method to create a Session
ResourceResolver
resourceResolver =
resolverFactory.getAdministrativeResourceResolver(null);
session
= resourceResolver.adaptTo(Session.class);
//
Setup the event handler to respond to a new claim under
content/geometrixx
observationManager
= session.getWorkspace().getObservationManager();
final
String[] types = { "nt:unstructured","sling:Folder"
};
final
String path = "/content/geometrixx-outdoors";
// define the path
observationManager.addEventListener(this,
Event.NODE_ADDED,
path, true,
null,
types, false);
log.info("Observing
property changes to {} nodes under {}",
Arrays.asList(types),
path);
}
catch(Exception
e)
{
e.printStackTrace();
}
}
protected
void
deactivate(ComponentContext componentContext) throws
RepositoryException {
if(observationManager
!= null)
{
observationManager.removeEventListener(this);
}
if
(session !=
null)
{
session.logout();
session
= null;
}
}
//Define
app
logic that is fired when the event occurs - simply track the time
//when
the event occurred.
public
void
onEvent(EventIterator itr)
{
log.info("on
event(-) ");//log to check the
event fired or not
Calendar cal =
Calendar.getInstance();
cal.getTime();
SimpleDateFormat
sdf
= new
SimpleDateFormat("HH:mm:ss");
//log
the time when the event occurred
log.info("A
new node was added to content/geometrixx at : "
+cal.getTime());
//EMAIL SEDING
CODE …..
try
{
//ensure
that the execute method is invoked
//Declare
a MessageGateway service
MessageGateway<Email>
messageGateway;
//Set
up the Email message
Email email
= new
SimpleEmail();
//Set
the mail values
String
emailToRecipients = "recipient@gmail.COM";
String
emailCcRecipients = "ccreceipent@gmail.com";
email.addTo(emailToRecipients);
email.addCc(emailCcRecipients);
email.setSubject("node
created");
email.setFrom("youremail@gmail.com");
email.setMsg("This
message is to inform you that the CQ content has been added");
log.info("Here
in execute method"+email);
//Inject
a MessageGateway Service and send the message
messageGateway
= messageGatewayService.getGateway(Email.class);
//
Check the logs to see that messageGateway is not null
messageGateway.send((Email)
email);
log.info("message
send sucessfully");//meaaage in the
error log file //after sending email
}
catch
(Exception e)
{
e.printStackTrace();
log.info("Exception
Area"+e);
}
}
}
- You have to add dependecies in pom.xml that is..
<dependency>
<groupId>com.day.cq</groupId>
<artifactId>cq-mailer</artifactId>
<version>5.6.2</version>
<scope>provided</scope>
</dependency>
- Buid bundle by running and deploy in Console.
- Open http://localhost:5610/system/console/configMgr and Set the properties for gmail like belowSMTP server host name:smt.gmail.comSMTP server port:465SMTP user:youremail@gmail.comSMTP password :your email passwordFrom address :youremail@gmail.comSMTP use SSL :true(for ssl)
- Save it.
- Run Stop and run the Bundle. If everything fine check log message will come when you add node of type untructure and nt:folder inside the path of jcr:node
- Finally email will be received check gmail.
So this is good, but my requirement depends on multiple events. So how can I add multiple events as parameter
ReplyDeleteHi,
DeleteSorry for late answer for handle multiple event i specify 2 methods but second is efficient:-
1-you can make another service and register that event the same way.But this is not efficient way to handle multiple event.
2-you can add other event by same way "observationManager.addEventListener(this, Event.NODE_ADDED, path, true, null, types, false)
and on(EventIterator itr) -it is giving iterator of Events So use itr.nextEvent() -it is returning event like "NODE_REMOVED" in the String Formet
So you can check the condition and based on that you can write your logic on various event fire.
good blog to know basic thanks sir
ReplyDelete