Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Wednesday, July 13, 2011

ResultSetExtractor in Spring


Create the entry in the database:
For this we will take flight database and flight entity as our pojo class.
See - Create flights in database and corresponding pojo class

Now using the ResultSetExtractor
First we will implement result set extractor
public class FlightResultSetExtractor implements ResultSetExtractor<List<Flight>> {

   @Override
   public Object extractData(ResultSet rs) throws SQLException {
      List<Flight> flightList = new ArrayList<Flight>();      
      while(rs.next){
         Flight flight = new Flight();
         flight.setFlightNo(rs.getString(1));
         flight.setCarrierName(rs.getString(2));
         flightList.add(flight);
      }
      return list;
  }
}

Now using the ResultSetExtractor
Initialize JdbcTemplate as jdbcTemplate first
public List<Flight> getAllTodaysFlight(){
   String sql = "Get all flights where date=?";
   Date today = getTodaysDate();
   Object[] args = {date};
   FlightResultSetExtractor extractor = new FlightResultSetExtractor();
   return jdbcTemplate.query(src, args, extractor);
}

Wednesday, June 29, 2011

Writing method interceptors using Spring AOP

Spring is a great Java technology that has become a very popular application framework during the past few years. My intention is not to go through the whole concepts and architectural details of the framework, because that kind of information can be easily looked up starting at http://www.springframework.org. As the article title indicates, I intend to provide hands-on examples showing the minimal requirements to bundle certain Spring functionalities in your Java applications. So, because I will not go into the “what’s under the hood” approach unless absolutely necessary, most of the examples might require the knowledge of basic Spring concepts. Anyway, the basic idea is that you must RTFM before deciding if Spring is right for your application.
The first example is a short look at a simple method intercepting strategy. You can read all about this and the whole Spring AOP API here.The source code for this example can be found here. In the project directory run ant compile run to launch the application.
For the beginning let’s consider that we have the service MyService that that has a method doSomething() performing an operation which takes a long time to execute. Below you can see the (pretty dumb) code of this method.
public class MyService {
  public void doSomething() {
    for (int i = 1; i < 10000; i++) {
      System.out.println("i=" + i);
    }
  }
}

In order to print out the performance statistics on the method call, we must first implement the interceptor that actually calculates the execution time for this method. To do this we need to implement the org.aopalliance.intercept.MethodInterceptor interface shipped with Spring. This is actually a callback providing access to the actual call of the methods of our service. The JavaDoc for this interface is here.

public class ServiceMethodInterceptor implements MethodInterceptor {
  public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = methodInvocation.proceed();
    long duration = System.currentTimeMillis() - startTime;
    Method method = methodInvocation.getMethod();
    String methodName = method.getDeclaringClass().getName()  
                                   + "." + method.getName();
    System.out.println("Method '" + methodName  
                         + "' took " + duration + " milliseconds to run");
    return null;
  }
}

Next we need to proxy our service in order to obtain an instance whose methods are being intercepted by our ServiceMethodInterceptor. To achieve this, all it takes is a little magic in Spring’s bean configuration file, as you can see below.

<beans>
  <bean id="myService" class="com.test.MyService">
  </bean>

  <bean id="interceptor" class="com.test.ServiceMethodInterceptor">
  </bean>

  <bean id="interceptedService" class="org.springframework
                      .aop.framework.ProxyFactoryBean">
    <property name="target">
      <ref bean="myService"/>
    </property>
    <property name="interceptorNames">
      <list>
        <value>interceptor</value>
      </list>
    </property>
  </bean>
</beans>

The key in this XML snippet is Spring’s built-in class org.springframework.aop.framework.ProxyFactoryBean which provides the actual proxying of our service. In order to obtain the desired effect we must set the target and interceptorNames properties for this bean. The target property represents the name of the bean that we want to proxy, which in our case is the myService bean. The interceptorNames property holds a list of bean names that will be used as interceptors for the proxied bean. So, yes, you can define more than one interceptor for your bean.
As everything seems to be packed pretty nice, all we need to do now is to have our service instantiated using Spring and call itâs doSomething method.

public class Test {
  public static void main(String[] args) {
    ApplicationContext ctx =  
           new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
    MyService myService = (MyService)ctx.getBean("interceptedService");
    myService.doSomething();
  }
}

So we need to look up the interceptedService bean in order to get the proxied service, but if we choose to remove the performance monitor we can simply lookup the initial myService bean.
Normally, after the method doSomething has run, you should see, as the last output line, something like this:
Method 'com.test.MyService.doSomething' took 281 milliseconds to run

Except from the MethodInterceptor Spring also offers other method interception strategies. For example you can choose to handle a method execution right before or immediately after the actual call, or when an exception is thrown during the execution of your method. The reference documentation about these types of interceptors that Spring offers is available here.

Please note that basic performance monitoring can also be achieved by using Spring’s built-in PerformanceMonitorInterceptor. We used this logic just as a sample for method intercepting, but as your intuition might tell you, this is just one of the many things you can do with this feature of Spring. For example, if you need to implement a fine-grained security module, you might choose not to allow the method call to execute if the user does not have rights on the business method. So, basically, you will have to see for yourself how you can use this functionality in your application.
I hope you find this article useful.

Wednesday, June 22, 2011

RMI using spring

Let us look at Spring’s support to Remoting.

Spring supports remoting for several different Remote Procedure Call models, including Remote Method Invocation (RMI), Caucho’s Hessian and Burlap, and Spring’s own HTTP invoker.

Spring offers a POJO-based programming model for both your server and client, no matter which remoting solution you choose. This is accomplished using a proxy factory bean that enables you to wire remote services into properties of your other beans as if they were local objects.

The client makes calls to the proxy as if the proxy were providing the service functionality. The proxy communicates with the remote service on behalf of the client. It handles the details of connecting and making remote calls to the remote service.

If the call to the remote service results in a java.rmi.RemoteException, the proxy handles that exception and rethrows it as an unchecked
org.springframework.remoting.RemoteAccessException. Remote exceptions usually signal problems such as network or configuration issues that can’t be gracefully recovered from. Since there’s usually very little that a client can do to gracefully recover from a remote exception, rethrowing a RemoteAccessException makes it optional for the client to handle the exception.

Spring simplifies the RMI model by providing a proxy factory bean that enables you to wire RMI services into your Spring application is if they were local JavaBeans. Spring also provides a remote exporter that makes short work of converting your Spring-managed beans into RMI services.

Spring’s RmiProxyFactoryBean is a factory bean that creates a proxy to an RMI service. RmiProxyFactoryBean produces a proxy object that talks to remote RMI services on behalf of the client. The client talks to the proxy through the service’s interface as if the remote service were just a local POJO.

RmiProxyFactoryBean certainly simplifies the use of RMI services in a Spring application. But that’s only half of an RMI conversation.

Spring provides an easier way to publish RMI services. Instead of writing RMI-specific classes with methods that throw RemoteException, you simply write a POJO that performs the functionality of your service. Spring handles the rest.

For a typical Spring Application we need the following files:

1. An interface that defines the functions.

2. An Implementation that contains properties, its setter and getter methods, functions etc.

3. A XML file called Spring configuration file.

4. Client program that uses the function

Because the service interface doesn’t extend java.rmi.Remote and none of its methods throw java.rmi.RemoteException, this trims the interface down a bit. But more importantly, a client accessing the service through this interface will not have to catch exceptions that they probably won’t be able to deal with. Instead of generating a server skeleton and client stub using rmic and manually adding it to the RMI registry (as you would in conventional RMI), we’ll use Spring’s RmiServiceExporter.

RmiServiceExporter exports any Spring-managed bean as an RMI service. RmiServiceExporter works by wrapping the bean in an adapter class. The adapter class is then bound to the RMI registry and proxies requests to the service class.

Example Code
The simplest way to use RmiServiceExporter to expose the employeeService bean as an RMI service is to configure it in Spring with the following XML:

<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
        <property name="serviceName" value="employee-service"/>
        <property name="service" ref="employeeService"/>
        <property name="serviceInterface" value="rmi.common.EmployeeI"/>
        <property name="registryPort" value="1234"/>
</bean>

Here the employeeService bean is wired into the service property to indicate that RmiServiceExporter is going to export the bean as an RMI service. ServiceName property names the RMI service and the serviceInterface property specifies the interface implemented by the service.

<bean id="employeeService" class="rmi.server.EmployeeImpl">
</bean>

Now let us look at an example...

Let us have simple employee recruitment service exposed through EmployeeI interface which contains methods to add, remove and get number of employees.

public class Employee implements Serializable {
 private String name;
 private String address;
 
 public Employee(String name,String address){
  this.name = name;
  this.address = address;
 }
 
 // getters and setters
}


public interface EmployeeI {
 
 public void addEmployee(Employee employee);
 
 public void removeEmployee(Employee employee);

    public List<Employee> getEmployees();  
    
}

Here is the implementation for EmployeeI interface.

public class EmployeeImpl implements EmployeeI{

    private List<Employee> employees = new ArrayList<Employee>();

    public void addEmployee(Employee employee) {
     employees.add(employee);
    }
    
    public void removeEmployee(Employee employee){
     employees.remove(employee);
    }

    public List<Employee> getEmployees() {
        return employees;
    }
}

On the server side, we need to configure Spring to export the service through RMI. As we discussed earlier we can do it by RmiServiceExporter.
The interface can be accessed by using RmiProxyFactoryBean, or via plain RMI in case of a traditional RMI service. The RmiServiceExporter explicitly supports the exposing of any non-RMI services via RMI invokers. Of course, we first have to set up our service in the Spring container:

<beans>
    <bean id="employeeService" class="rmi.server.EmployeeImpl"/>        
    
    <bean class="org.springframework.remoting.rmi.RmiServiceExporter">
        <property name="serviceName" value="employee-service"/>
        <property name="service" ref="employeeService"/>
        <property name="serviceInterface" value="rmi.common.EmployeeI"/>
        <property name="registryPort" value="1234"/>
    </bean>
</beans>

Now to run the server side service you need Spring context initialization.
public class EmpServerDemo {
 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext 
                  ("rmi/server/rmi-server-context.xml");
 }
}


Now let us have a look at client side.

To link in the service on the client, we'll create a separate Spring container, containing the simple object and the service linking configuration bits:

<beans>
    <bean id="employeeService"  
             class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
        <property name="serviceUrl" value="rmi://localhost:1234/employee-service"/>
        <property name="serviceInterface" value="rmi.common.EmployeeI"/>
    </bean>
</beans>

You can make client calls through the below code...

public class EmpClientDemo {
 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext 
                       ("rmi/client/rmi-client-context.xml");
  EmployeeI employee = (EmployeeI) ctx.getBean("employeeService");
  employee.addEmployee(new Employee("Prashant", "address1"));
  employee.addEmployee(new Employee("Sneha", "address2"));
  List<Employee> employees = employee.getEmployees();
  System.out.println("Total number of employees: " + employees.size());
  Iterator<Employee> it = employees.iterator();
  while (it.hasNext()) {
   Employee emp = (Employee) it.next();
   System.out.println(" " + emp);
  }
 }
}

Therefore, the client will not be aware of the fact that the service is running remote and even less about the fact that its method calls are marshaled through RMI. The Spring bean configuration file takes care of these details, so the client code will not be affected if we change the remoting strategy or even if we choose to run the service in-process.

First run the EmpServerDemo in one console to launch the RMI server and then run the EmpClientDemo in another console.

Monday, June 20, 2011

Spring JdbcTemplate to retrieve List and Map

org.springframework.jdbc.core.JdbcTemplate used to perform query for specific result through out some query parameters. Some of the basic queries like query, queryForList, QueryForObject as the common understandings of the methods name. A query or queryForList method returns a list of desired rows but queryForMap returns only a single row where all the column names are key of the Map.
To retrieve a list, org.springframework.jdbc.core.RowMapper can be used along with java.sql.ResultSet. A sample code is like,

List sampleClassList = 
      jdbcTemplate.query(query, new Object[]{parameters.....},
     new RowMapper() {
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
  SampleClass sampleClass = new SampleClass();
  sampleClass.setValue1(rs.getString("column1"));
  sampleClass.setValue2(rs.getString("column2"));
  return sampleClass;
 }
});

In most of the cases developers convert a retrieved list to their desired Map later by manipulating the list. The basic reason behind is a map will not contain duplicate values as key but to a list data can be redundant. Its also possible to get a Map where one column as key and other as value of the map. org.springframework.jdbc.core.ResultSetExtractor can be used for customize results like Map. The following sample code can do this thing. Its really a very good option if one do not want to have duplicate value in a specific column. Its easier to make that thing a key.

Map map = (Map)jdbcTemplate.query(query, new Object[]{parameters....},
     new ResultSetExtractor() {
       public Object extractData(ResultSet rs) throws SQLException {
       Map map = new LinkedHashMap();
       while (rs.next()) {
         String col1 = rs.getString("col1");
         String col2 = rs.getString("col2");
         map.put(col1, col2);
       }
      return map;
   };
});

Sunday, June 12, 2011

Spring ApplicationContext within Servlet

If you want to use Spring-managed beans within you web application, especially Servlet controller and you don't know which implementation of ApplicationContext to use I recommend you to use XmlWebApplicationcontext. This is pretty straightforward as all you have to do is write 4 lines of code (I love Spring ;) - the following lines of code:
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setServletContext(getServletContext());
ctx.setConfigLocations(new String[] { beans definition locations });
ctx.refresh();

Beans definition locations are paths relative to the web root i.e. if you store your bean definitions in WEB-INF/META-INF/services/descriptor.xml you should provide exactly the same string as a config location.

Don't forget to invoke refresh() method.

That's all - isn't Spring beautiful?

BeanFactory in Spring

As its name implies, a bean factory is an implementation of the Factory design pattern. That is, it is a class whose responsibility is to create and dispense beans. The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. When a bean factory hands out objects, those objects are fully configured, are aware of their collaborating objects, and are ready to use.

BeanFactory is a workhorse that initializes beans and calls their lifecycle methods. It should be noted that most lifecycle methods only apply to singleton beans. Spring cannot manage prototype (non-singleton) lifecycles. This is because, after they’re created, prototypes are handed off to the client and the container loses track of it. For prototypes, Spring is really just a replacement for the “new” operator.

A BeanFactory is represented by the interface org.springframework.beans.factory.BeanFactory, and it is having multiple implementations. The most commonly used simple BeanFactory implementation is org.springframework.beans.factory.xml.XmlBeanFactory. (This should be qualified with the reminder that ApplicationContexts are a subclass of BeanFactory, and most users end up using XML variants of ApplicationContext).

Although for most scenarios, almost all user code managed by the BeanFactory does not have to be aware of the BeanFactory, the BeanFactory does have to be instantiated somehow. This can happen via explicit user code such as:

Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
or
ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
        new String[] {"applicationContext.xml", "applicationContext-part2.xml"});
// of course, an ApplicationContext is just a BeanFactory
BeanFactory factory = (BeanFactory) appContext;

Beans are lazily loaded into bean factories, meaning that while the bean factory will immediately load the bean definitions (the description of beans and their properties), the beans themselves will not be instantiated until they are needed. While in case of ApplicationContext Interface beans are pre-loaded. See the posts - ApplicationContext in spring and Lazy and pre-loading of beans in spring. os.

More about ApplicationContext in Spring

While the beans package provides basic functionality for managing and manipulating beans, often in a programmatic way, the context package adds ApplicationContext, which enhances BeanFactory functionality in a more framework-oriented style.

A bean factory is fine for simple applications, but to take advantage of the full power of the Spring Framework, you’ll probably want to load your application beans using Spring’s more advanced container, the application context.

Many users will use ApplicationContext in a completely declarative fashion, not even having to create it manually, but instead relying on support classes such as ContextLoader to automatically start an ApplicationContext as part of the normal startup process of a J2EE web-app. Of course, it is still possible to programmatically create an ApplicationContext.

The basis for the context package is the ApplicationContext interface, located in the org.springframework.context package. Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory. To allow working in a more framework-oriented fashion, using layering and hierarchical contexts, the context package also provides the following:

In most cases, you’ll use the ApplicationContext, which adds more enterprise-level, J2EE functionality, such as

  • internationalization (i18n)
  • custom converters (for converting Strings to Object types)
  • event publication/notification
  • Access to resources, such as URLs and files
  • Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application.
You could also implement your own ApplicationContext and add support for loading from other resources (such as a database). While many Contexts are available for loading beans, you’ll only need a few, which are listed below. The others are internal classes that are used by the framework itself.

1. ClassPathXmlApplicationContext: Loads context files from the classpath (that is, WEB-INF/classes or WEB-INF/lib for JARs) in a web application. Initializes using a
new ClassPathXmlApplicationContext(path)

where path is the path to the file. The path argument can also be a String array of paths. This is a good context for using in unit tests.

2. FileSystemXmlApplicationContext: Loads context files from the file system, which is nice for testing. Initializes using a
new FileSystemXmlApplicationContext (path)

where path is a relative or absolute path to the file. The path argument can also be a String array of paths.

3. XmlWebApplicationContext: Loads context files internally by the ContextLoaderListener, but can be used outside of it. For instance, if you are running a container that doesn’t load Listeners in the order specified in web.xml, you may have to use this in another Listener. Below is the code to use this Loader.

XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setServletContext(ctx);
context.refresh();


Once you’ve obtained a reference to a context, you can get references to beans using
ctx.getBean(beanId)

You will need to cast it to a specific type, but that’s the easy part. Of the above contexts, ClassPathXmlApplicationContext is the most flexible. It doesn’t care where the files are, as long as they’re in the classpath. This allows you to move files around and simply change the classpath.

A side from the additional functionality offered by application contexts, another big difference between an application context and a bean factory is how singleton beans are loaded. A bean factory lazily loads all beans, deferring bean creation until the getBean() method is called. An application context is a bit smarter and preloads all singleton beans upon context startup. By preloading singleton beans, you ensure that they will be ready to use when needed—your application won’t have to wait for them to be created.

Spring + Quartz + JavaMail Integration Tutorial

Introduction

Quartz is a job scheduling framework which is used to schedule the jobs to be executed on the specified time schedule. Quartz can be downloaded from here. We discussed about quartz earlier - Quartz Example.
JavaMail is an API to send/recieve emails from Java Applications. JavaMail API 1.4.3 can be downloaded from here.
Spring has integration points to integrate Quartz and JavaMail which makes easy to use those APIs.

Example
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.
Lets look at the implementation now.

Email.java
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
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
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
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("xyz@gmail.com.com");
    email.setSubject("Happy BirthDay");
    email.setTo(user.getEmail());
    email.setText("<h1>Dear "+user.getName()+
      ", 
Many Many Happy Returns of the day :-)</h1>");
      
    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("Kinshuk Chandra", "kinshuk.ram.k@gmail.com", new Date());
  users.add(user1);
  User user2 = new User("John", "abcd@gmail.com", new Date());
  users.add(user2);
  return users;
 }
}

spring config file - applicationContext.xml
<beans>
 
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
 <property name="triggers">
  <list>
   <ref bean="birthdayWisherCronTrigger" />
  </list>
 </property>
 </bean>
 <bean id="birthdayWisherCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
  <property name="jobDetail" ref="birthdayWisherJob" />
  <!-- run every morning at 6 AM -->
  <property name="cronExpression" value="0/5 * * * * ?" />
 </bean>
 
 <bean name="birthdayWisherJob" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="com.vaani.email.jobs.BirthdayWisherJob" />
  <property name="jobDataAsMap">
   <map>
    <entry key="emailService" value-ref="emailService"></entry>
   </map>
  </property>
 </bean>
  
 <bean id="emailService" class="com.vaani.email.services.EmailService">
  <property name="mailSender" ref="mailSender"></property>
 </bean>
  
 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <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="*****"/>
  <property name="javaMailProperties">
   <props>
    <prop key="mail.smtps.auth">true</prop>
    <prop key="mail.smtps.starttls.enable">true</prop>
    <prop key="mail.smtps.debug">true</prop>
   </props>
  </property>
 </bean>
  
</beans>

MailClientDemo.java
package com.vaani.email.main;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class MailClientDemo {
 
  
 public static void main(String[] args) 
 {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
 }
 
}


Chitika