Wednesday, February 8, 2012

Spring Timer Example

In this blog i will show you how to implement Timer in Spring.

1. Write a Java class with a method which you want to run.
 
package com.msn.spring.scheduling;
  import java.util.Date;

     public class Schedule {
    /*

    This method prints Date
    */

    public void printMessage( ){
        System.out.println(new Date());
        }
 
    }

2. Connfigure this class as a bean in Spring configuration file

 <bean id="scheduler" class="com.msn.spring.scheduling.Schedule" />

3. Configure the following beans with the details like which method to call, and the time period
   
    <bean id="schedulerTask"
 class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
    <property name="targetObject" ref="scheduler" />
    <property name="targetMethod" value="printMessage" />
</bean> 

<bean id="timerTask"
    class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask" ref="schedulerTask" />
    <property name="period" value="1000" /><!--  Here i have configures period property with 1000 mill seconds. So printMessage( ) wiill be called every 1 sec -->
</bean>

<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
    <property name="scheduledTimerTasks">
        <list>
            <ref local="timerTask" />
        </list>
    </property>
</bean>


4. Write a test class which loads the spring configuration file

Test.java
-----------
package com.msn.spring.scheduling;

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

/**
 *
 * @author Naidu */
public class Test {
    public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("com/msn/spring/scheduling/scheduleContext.xml");       
     }
   
}





ScheduleContext.xml
----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

  <beans>       

<bean id="scheduler" class="com.msn.spring.scheduling.Schedule" />
 <bean id="schedulerTask"
  class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
    <property name="targetObject" ref="scheduler" />
    <property name="targetMethod" value="printMessage" />
</bean> 
<bean id="timerTask"
    class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask" ref="schedulerTask" />
    <property name="period" value="1000" />
</bean>
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
    <property name="scheduledTimerTasks">
        <list>
            <ref local="timerTask" />
        </list>
    </property>
</bean>

  </beans>






When i run the Test class, printMessage( ) will start executing every one second.







 

Spring JMS with ActiveMQ Message Broker

In this blog i will show you how to use Spring JmsTemplate with ActiveMQ as Message Broker.
You need to have the following jars in your project lib folder

1. activemq-core-5.4.3.jar ( you can download the Active MQ distribtion from this link. you can find this activemq-core jar in lib folder after extracting the downloaded zip)

2. Javaee-api.jar (download this jar from this link)

3. spring 3 jars( which you can download from springsource site)

I will be using NetBeans7.1 latest relase .

Step1. Create a new java project
2. Right click on project node and select properties and add the above mentioned jars to library(activemq-core.jar,javaee-api.jar and spring jars).


If you are using netbeans IDE you can add spring jars by selecting Add Library button and select the spring jar in the list.

3.Create a class Called JMSService which contains send( ) and receive( ) methods.


 /*
This method is used for sending messages to the destination( in this case this send message to Queue)
*/
     public void sendMessage(){
     
        jmsTemplate.send( new MessageCreator(){
                public Message createMessage(Session session) throws JMSException{
                        return session.createTextMessage("Hello");
                        }
                }
        );
      }
/*
.This receives message from the queue
*/

  public String receiveMessage(){
    try {
        TextMessage receivedMessage=(TextMessage) jmsTemplate.receive();
        return(String)receivedMessage.getText();
        } catch(JMSException jmsException){
    throw JmsUtils.convertJmsAccessException(jmsException);
    }
}

JMSService.java
-----------------------
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.msn.jms;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.support.JmsUtils;

public class JMSService {
    private JmsTemplate jmsTemplate;
    public JMSSender(JmsTemplate template){
        this.jmsTemplate=template;
    }
    public void sendMessage(){
      
        jmsTemplate.send( new MessageCreator(){
                public Message createMessage(Session session) throws JMSException{
                        return session.createTextMessage("Hello");
                        }
                }
        );
      }
       public String receiveMessage(){
    try {
        TextMessage receivedMessage=(TextMessage) jmsTemplate.receive();
        return(String)receivedMessage.getText();
        } catch(JMSException jmsException){
    throw JmsUtils.convertJmsAccessException(jmsException);
    }
}

  }







4. Configure ConnectionFactory,Queue(destination), JmsTemplate and JMSService as beans in the spring configuration file
  jmscontext.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

  <beans>       
<bean id="connectionFactory"  class="org.apache.activemq.spring.ActiveMQConnectionFactory">
    <property name ="brokerURL" value="tcp://localhost:61616"/>
</bean>
<bean id="queue" class="org.apache.activemq.command.ActiveMQQueue">
    <constructor-arg value="queue1"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory"/>
    <property name="defaultDestinationName" value="queue1"/>
</bean>
<bean id="messageService" class="com.msn.jms.JMSService" >
    <constructor-arg ref="jmsTemplate"/>
   
</bean>
  </beans>


5. Create a Test class with main method which tests JMSService send(  ) and receive( ) methods.

  JMSClient.java
-----------------

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.msn.jms;

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

/**
 *
 * @author snaidu26
 */
public class MessageClient {
    public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("com/msn/jms/jmscontext.xml");       
        JMSSender sender=(JMSSender) ctx.getBean("messageService");
        sender.sendMessage();
        System.out.println("Message sent to server");
        System.out.println("Message Received: "+sender.receiveMessage());
       
       
    }
   
}




















6. Project Structure looks like :
  

7.When we run the MessageClient