Spring and Quartz Integration Using Custom Annotation

We know Spring has support for integrating with Quartz framework.
But as of now Spring supports only static xml declarative approach only.
If you want to see how to integrate Spring+Quartz you can refer Spring + Quartz Integration .

As part of my pet project requirement I got to schedule the Jobs dynamically and I though of following 2 options:
1. Using Annotations for providing Job Metada
2. Loading the Job Metadata from Database

For now I thought of going ahead with Annotation based approach and I want to integrate it with Spring as well.
Here is how I did it.

1. Create a Custom Annotation QuartzJob

package com.sivalabs.springsamples.jobscheduler;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.stereotype.Component;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@Scope("prototype")
public @interface QuartzJob
{

String name();
String group() default "DEFAULT_GROUP";
String cronExp();
}

2. Create an ApplicationListener to scan for all the Job implementation classes and schedule them using Quartz scheduler.

package com.sivalabs.springsamples.jobscheduler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.JobDetailBean;

public class QuartJobSchedulingListener
implements ApplicationListener<ContextRefreshedEvent>
{
@Autowired
private Scheduler scheduler;

@Override
public void onApplicationEvent(ContextRefreshedEvent event)
{
try
{
ApplicationContext applicationContext = event.getApplicationContext();
List<CronTriggerBean> cronTriggerBeans = this.loadCronTriggerBeans(applicationContext);
this.scheduleJobs(cronTriggerBeans);
}
catch (Exception e)
{
e.printStackTrace();
}
}

private List<CronTriggerBean> loadCronTriggerBeans(ApplicationContext applicationContext)
{
Map<String, Object> quartzJobBeans =
applicationContext.getBeansWithAnnotation(QuartzJob.class);

Set<String> beanNames = quartzJobBeans.keySet();

List<CronTriggerBean> cronTriggerBeans = new ArrayList<CronTriggerBean>();

for (String beanName : beanNames)
{
CronTriggerBean cronTriggerBean = null;
Object object = quartzJobBeans.get(beanName);
System.out.println(object);
try
{
cronTriggerBean = this.buildCronTriggerBean(object);
}
catch (Exception e)
{
e.printStackTrace();
}

if(cronTriggerBean != null)
{
cronTriggerBeans.add(cronTriggerBean);
}
}
return cronTriggerBeans;
}

public CronTriggerBean buildCronTriggerBean(Object job) throws Exception
{
CronTriggerBean cronTriggerBean = null;
QuartzJob quartzJobAnnotation =
AnnotationUtils.findAnnotation(job.getClass(), QuartzJob.class);

if(Job.class.isAssignableFrom(job.getClass()))
{
System.out.println("It is a Quartz Job");
cronTriggerBean = new CronTriggerBean();
cronTriggerBean.setCronExpression(quartzJobAnnotation.cronExp());
cronTriggerBean.setName(quartzJobAnnotation.name()+"_trigger");
//cronTriggerBean.setGroup(quartzJobAnnotation.group());
JobDetailBean jobDetail = new JobDetailBean();
jobDetail.setName(quartzJobAnnotation.name());
//jobDetail.setGroup(quartzJobAnnotation.group());
jobDetail.setJobClass(job.getClass());
cronTriggerBean.setJobDetail(jobDetail);
}
else
{
throw new RuntimeException(job.getClass()+" doesn't implemented "+Job.class);
}
return cronTriggerBean;
}

protected void scheduleJobs(List<CronTriggerBean> cronTriggerBeans)
{
for (CronTriggerBean cronTriggerBean : cronTriggerBeans)
{
JobDetail jobDetail = cronTriggerBean.getJobDetail();
try
{
scheduler.scheduleJob(jobDetail, cronTriggerBean);
}
catch (SchedulerException e)
{
e.printStackTrace();
}
}
}
}

3. Create a customized JobFactory to use Spring beans as Job implementation objects.

package com.sivalabs.springsamples.jobscheduler;

import org.quartz.Job;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public class SpringQuartzJobFactory extends SpringBeanJobFactory
{
@Autowired
private ApplicationContext ctx;

@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception
{
@SuppressWarnings("unchecked")
Job job = ctx.getBean(bundle.getJobDetail().getJobClass());
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
bw.setPropertyValues(pvs, true);
return job;
}
}

4. Create the Job implementation classes and Annotate them using @QuartzJob

package com.sivalabs.springsamples.jobscheduler;

import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

@QuartzJob(name="HelloJob", cronExp="0/5 * * * * ?")
public class HelloJob extends QuartzJobBean
{
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException
{
System.out.println("Hello Job is running @ "+new Date());
System.out.println(this.hashCode());
}
}

5. Configure the SchedulerFactoryBean and QuartJobSchedulingListener in applicationContext.xml













6. Test Client

package com.sivalabs.springsamples;

import org.quartz.Job;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sivalabs.springsamples.jobscheduler.HowAreYouJob;
import com.sivalabs.springsamples.jobscheduler.InvalidJob;

public class TestClient
{
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(context);
}

}

Spring + Quartz + JavaMail Integration Tutorial

Quartz is a job scheduling framework which is used to schedule the jobs to be executed on the specified time schedule.
JavaMail is an API to send/recieve emails from Java Applications.

Spring has integration points to integrate Quartz and JavaMail which makes easy to use those APIs.

Lets create a small demo application to show how to integrate Spring + Quartz + JavaMail.

Our application is to send birthday wishes emails to friends everyday at 6 AM.

Email.java

package com.sivalabs.reminders;

import java.util.ArrayList;
import java.util.List;

public class Email
{
private String from;
private String[] to;
private String[] cc;
private String[] bcc;
private String subject;
private String text;
private String mimeType;
private List<Attachment> attachments = new ArrayList<Attachment>();

public String getFrom()
{
return from;
}
public void setFrom(String from)
{
this.from = from;
}
public String[] getTo()
{
return to;
}
public void setTo(String... to)
{
this.to = to;
}
public String[] getCc()
{
return cc;
}
public void setCc(String... cc)
{
this.cc = cc;
}
public String[] getBcc()
{
return bcc;
}
public void setBcc(String... bcc)
{
this.bcc = bcc;
}
public String getSubject()
{
return subject;
}
public void setSubject(String subject)
{
this.subject = subject;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public String getMimeType()
{
return mimeType;
}
public void setMimeType(String mimeType)
{
this.mimeType = mimeType;
}
public List<Attachment> getAttachments()
{
return attachments;
}
public void addAttachments(List<Attachment> attachments)
{
this.attachments.addAll(attachments);
}
public void addAttachment(Attachment attachment)
{
this.attachments.add(attachment);
}
public void removeAttachment(int index)
{
this.attachments.remove(index);
}
public void removeAllAttachments()
{
this.attachments.clear();
}
}

Attachment.java

package com.sivalabs.reminders;

public class Attachment
{
private byte[] data;
private String filename;
private String mimeType;
private boolean inline;

public Attachment()
{
}

public Attachment(byte[] data, String filename, String mimeType)
{
this.data = data;
this.filename = filename;
this.mimeType = mimeType;
}
public Attachment(byte[] data, String filename, String mimeType, boolean inline)
{
this.data = data;
this.filename = filename;
this.mimeType = mimeType;
this.inline = inline;
}
public byte[] getData()
{
return data;
}
public void setData(byte[] data)
{
this.data = data;
}
public String getFilename()
{
return filename;
}
public void setFilename(String filename)
{
this.filename = filename;
}

public String getMimeType()
{
return mimeType;
}

public void setMimeType(String mimeType)
{
this.mimeType = mimeType;
}

public boolean isInline()
{
return inline;
}

public void setInline(boolean inline)
{
this.inline = inline;
}

}

EmailService.java

package com.sivalabs.reminders;

import java.util.List;

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class EmailService
{
private JavaMailSenderImpl mailSender = null;
public void setMailSender(JavaMailSenderImpl mailSender)
{
this.mailSender = mailSender;
}

public void sendEmail(Email email) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
// use the true flag to indicate you need a multipart message
boolean hasAttachments = (email.getAttachments()!=null &&
email.getAttachments().size() > 0 );
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, hasAttachments);
helper.setTo(email.getTo());
helper.setFrom(email.getFrom());
helper.setSubject(email.getSubject());
helper.setText(email.getText(), true);

List<Attachment> attachments = email.getAttachments();
if(attachments != null && attachments.size() > 0)
{
for (Attachment attachment : attachments)
{
String filename = attachment.getFilename() ;
DataSource dataSource = new ByteArrayDataSource(attachment.getData(),
attachment.getMimeType());
if(attachment.isInline())
{
helper.addInline(filename, dataSource);
}else{
helper.addAttachment(filename, dataSource);
}
}
}

mailSender.send(mimeMessage);
}
}

BirthdayWisherJob.java

package com.sivalabs.reminders;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class BirthdayWisherJob extends QuartzJobBean
{

private EmailService emailService;
public void setEmailService(EmailService emailService)
{
this.emailService = emailService;
}

@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Sending Birthday Wishes... ");
List<User> usersBornToday = getUsersBornToday();
for (User user : usersBornToday)
{
try
{
Email email = new Email();
email.setFrom("admin@sivalabs.com");
email.setSubject("Happy BirthDay");
email.setTo(user.getEmail());
email.setText("

Dear "+user.getName()+
",
Many Many Happy Returns of the day :-)

");

byte[] data = null;
ClassPathResource img = new ClassPathResource("HBD.gif");
InputStream inputStream = img.getInputStream();
data = new byte[inputStream.available()];
while((inputStream.read(data)!=-1));

Attachment attachment = new Attachment(data, "HappyBirthDay",
"image/gif", true);
email.addAttachment(attachment);

emailService.sendEmail(email);
}
catch (MessagingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

private List<User> getUsersBornToday()
{
List<User> users = new ArrayList<User>();
User user1 = new User("Siva Prasad", "sivaprasadreddy.k@gmail.com", new Date());
users.add(user1);
User user2 = new User("John", "abcd@gmail.com", new Date());
users.add(user2);
return users;
}
}

applicationContext.xml






<ref bean="birthdayWisherCronTrigger" />




<property name="jobDetail" ref="birthdayWisherJob" />
<!-- run every morning at 6 AM -->
<property name="cronExpression" value="0/5 * * * * ?" />



<property name="jobClass" value="com.sivalabs.reminders.BirthdayWisherJob" />












<property name="defaultEncoding" value="UTF-8"/>
<property name="host" value="smtp.gmail.com" />
<property name="port" value="465" />
<property name="protocol" value="smtps" />
<property name="username" value="admin@gmail.com"/>
<property name="password" value="*****"/>


true
true
true





TestClient.java

package com.sivalabs.reminders;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClient {


public static void main(String[] args)
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}

}