Tuesday 4 October 2016

Proposal

https://drive.google.com/file/d/0B_xWEVSNrbirdnJXZHNRN0RmdFE/view?usp=sharing

https://drive.google.com/file/d/0B_xWEVSNrbirdnRTZHUySGZKOWc/view?usp=sharing

Monday 23 May 2016

Why You Need to Check Your Residual Plots for Regression Analysis: Or, To Err is Human, To Err Randomly is Statistically Divine


29
Residual illustration
Anyone who has performed ordinary least squares (OLS) regression analysis knows that you need to check the residual plots in order to validate your model. Have you ever wondered why? There are mathematical reasons, of course, but I’m going to focus on the conceptual reasons. The bottom line is that randomness and unpredictability are crucial components of any regression model. If you don’t have those, your model is not valid.
Why? To start, let’s breakdown and define the 2 basic components of a valid regression model:
Response = (Constant + Predictors) + Error 
Another way we can say this is:
Response = Deterministic + Stochastic

The Deterministic Portion

This is the part that is explained by the predictor variables in the model. The expected value of the response is a function of a set of predictor variables. All of the explanatory/predictive information of the model should be in this portion.

The Stochastic Error

Stochastic is a fancy word that means random and unpredictable. Error is the difference between the expected value and the observed value. Putting this together, the differences between the expected and observed values must be unpredictable. In other words, none of the explanatory/predictive information should be in the error.
The idea is that the deterministic portion of your model is so good at explaining (or predicting) the response that only the inherent randomness of any real-world phenomenon remains leftover for the error portion. If you observe explanatory or predictive power in the error, you know that your predictors are missing some of the predictive information. Residual plots help you check this!
Statistical caveat: Regression residuals are actually estimates of the true error, just like the regression coefficients are estimates of the true population coefficients.

Using Residual Plots

Using residual plots, you can assess whether the observed error (residuals) is consistent with stochastic error. This process is easy to understand with a die-rolling analogy. When you roll a die, you shouldn’t be able to predict which number will show on any given toss. However, you can assess a series of tosses to determine whether the displayed numbers follow a random pattern. If the number six shows up more frequently than randomness dictates, you know something is wrong with your understanding (mental model) of how the die actually behaves. If a gambler looked at the analysis of die rolls, he could adjust his mental model, and playing style, to factor in the higher frequency of sixes. His new mental model better reflects the outcome.
The same principle applies to regression models. You shouldn’t be able to predict the error for any given observation. And, for a series of observations, you can determine whether the residuals are consistent with random error. Just like with the die, if the residuals suggest that your model is systematically incorrect, you have an opportunity to improve the model.
So, what does random error look like for OLS regression? The residuals should not be either systematically high or low. So, the residuals should be centered on zero throughout the range of fitted values. In other words, the model is correct on average for all fitted values. Further, in the OLS context, random errors are assumed to produce residuals that are normally distributed. Therefore, the residuals should fall in a symmetrical pattern and have a constant spread throughout the range. Here's how residuals should look:
Minitab's residuals versus fits plot
Now let’s look at a problematic residual plot. Keep in mind that the residuals should not contain any predictive information.
Minitab's residuals versus fit plot with bad residuals
In the graph above, you can predict non-zero values for the residuals based on the fitted value. For example, a fitted value of 8 has an expected residual that is negative. Conversely, a fitted value of 5 or 11 has an expected residual that is positive.
The non-random pattern in the residuals indicates that the deterministic portion (predictor variables) of the model is not capturing some explanatory information that is “leaking” into the residuals. The graph could represent several ways in which the model is not explaining all that is possible. Possibilities include:
  • A missing variable
  • A missing higher-order term of a variable in the model to explain the curvature
  • A missing interaction between terms already in the model
Identifying and fixing the problem so that the predictors now explain the information that they missed before should produce a good-looking set of residuals!
In addition to the above, here are two more specific ways that predictive information can sneak into the residuals:
  • The residuals should not be correlated with another variable. If you can predict the residuals with another variable, that variable should be included in the model. In Minitab’s regression, you can plot the residuals by other variables to look for this problem.
     
  • Adjacent residuals should not be correlated with each other (autocorrelation). If you can use one residual to predict the next residual, there is some predictive information present that is not captured by the predictors. Typically, this situation involves time-ordered observations. For example, if a residual is more likely to be followed by another residual that has the same sign, adjacent residuals are positively correlated. You can include a variable that captures the relevant time-related information, or use a time series analysis. In Minitab’s regression, you can perform the Durbin-Watson test to test for autocorrelation.

Are You Seeing Non-Random Patterns in Your Residuals?

I hope this gives you a different perspective and a more complete rationale for something that you are already doing, and that it’s clear why you need randomness in your residuals. You must explain everything that is possible with your predictors so that only random error is leftover. If you see non-random patterns in your residuals, it means that your predictors are missing something.
If you're learning about regression, read my regression tutorial!

You'll Never Miss a Post!

Give us your e-mail, and we'll give you a weekly summary of the latest blog posts.
Sign Me Up >
 

Comments

Name: Vijay • Sunday, March 3, 2013
Jim-excellent blog. Just learning about regression diagnostics in an MBA class and this blog just did a beautiful job of explaining why we have to examine the residuals. Thanks

Name: Maggie • Monday, April 14, 2014
Thank you, Jim for your excellent explanations. Although I'm using PHStat2 in an MBA class, your Minitab insight works just as well for me! If only you'd written my text book! Thanks, again, and I'll continue to refer to your site.

Name: Jim Frost • Friday, April 18, 2014
Hi Maggie, thank you so much for your very kind words. I'm glad that you found my blogs helpful! I hope you have your own fun adventures in statistics!

Jim

Name: Shilpa • Friday, June 13, 2014
This is really helpful. Thank you so much for sharing it.:)

Name: Ram subramanian • Wednesday, June 25, 2014
Very informative, Thanks a lot

Name: shivraj ghadge • Tuesday, July 1, 2014
nice

Name: Justine • Friday, August 1, 2014
Clear explanation. Thank You so much

Name: Jamil • Friday, September 5, 2014
Thanks for this amazing explanation. It is really helpful.

 

Thursday 17 March 2016

Java Reflection Part I

Java Reflection Example

Reference: http://tutorials.jenkov.com/java-reflection/index.html
Here is a quick Java Reflection example to show you what using reflection looks like:

Test.java

public class Test {

private String a;
private Integer b;
public Test(String a, Integer b) {
super();
this.a = a;
this.b = b;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public Integer getB() {
return b;
}
public void setB(Integer b) {
this.b = b;
}
}

     This example obtains the Class object from the class called Test. Using the class object the example gets a list of the
    methods in that class, iterates the methods and print out their names.

Exactly how all this works is explained in further detail throughout the rest of this tutorial (in other texts). 
Mainmethod2.java
public class Mainmethod2 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Method[] methods = Test.class.getMethods();

for(Method method : methods){
   System.out.println("method = " + method.getName());
}
}

o/p:
method = getA
method = setA
method = getB
method = setB
method = wait
method = wait
method = wait
method = equals
method = toString
method = hashCode
method = getClass
method = notify
method = notifyAll


Monday 14 March 2016

AMQP Tutorial 1

This is tutorial from Message Driven Architecture.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.integration.samples</groupId>
<artifactId>eda-with-spring</artifactId>
<packaging>jar</packaging>
<version>1.0.0.BUILD-SNAPSHOT</version>
<name>Event Driven Architecture with Spring</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.test.failure.ignore>false</maven.test.failure.ignore>
<!-- versions for commonly-used dependencies -->
<org.apache.activemq.version>5.4.2</org.apache.activemq.version>
<!--
<cglib.version>2.2</cglib.version>
-->
<junit.version>4.7</junit.version>
<log4j.version>1.2.12</log4j.version>
<!--
<hsqldb.version>1.8.0.10</hsqldb.version>
<org.aspectj.version>1.6.5</org.aspectj.version>
-->
<org.easymock.version>2.3</org.easymock.version>
<!--
<org.eclipse.jdt.core.version>3.4.2.v_883_R34x</org.eclipse.jdt.core.version>
-->
<org.mockito.version>1.8.4</org.mockito.version>
<!--
<org.hamcrest.version>1.1</org.hamcrest.version>
<org.slf4j.version>1.5.10</org.slf4j.version>
-->
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
<org.springframework.batch.version>2.1.2.RELEASE</org.springframework.batch.version>
<org.springframework.integration.version>2.0.3.RELEASE</org.springframework.integration.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.1</version>
<!--<scope>provided</scope>-->
</dependency>
<!-- dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<optional>true</optional>
</dependency -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>${org.apache.activemq.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-event</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-file</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-groovy</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-http</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-jms</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mail</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ws</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-xml</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-xmpp</artifactId>
<version>${org.springframework.integration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>${org.springframework.batch.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- test-scoped dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${org.easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
<version>${org.easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${org.mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-test</artifactId>
<version>${org.springframework.integration.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/java</directory>
<includes>
<include>**/*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/java</directory>
<includes>
<include>**/*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
<includes>
<include>**/*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>false</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>repository.springframework.maven.release</id>
<name>Spring Framework Maven Release Repository</name>
<url>http://maven.springframework.org/release</url>
</repository>
<repository>
<id>repository.springframework.maven.milestone</id>
<name>Spring Framework Maven Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
<repository>
<id>repository.springframework.maven.snapshot</id>
<name>Spring Framework Maven Snapshot Repository</name>
<url>http://maven.springframework.org/snapshot</url>
</repository>
</repositories>
</project>

simple-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean class="com.amqp.functions.SimpleEventListener"/>
</beans>

SimpleEventListener.java
package com.amqp.functions;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class SimpleEventListener implements ApplicationListener<ApplicationEvent>{
private final Log logger = LogFactory.getLog(this.getClass());

@Override
public void onApplicationEvent(ApplicationEvent event){
this.logger.info("received event:"+event);
System.out.println(event);
}

}

SimpleEventDemo.java
package com.amqp.functions;

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

public class SimpleEventDemo {

public static void main(String... args){
AbstractApplicationContext context = new ClassPathXmlApplicationContext("simple-context.xml",SimpleEventDemo.class);
context.start();
context.publishEvent(new CustomEvent("testEventSource"));
context.stop();
}
}

Tuesday 8 March 2016

JMS Topic using Spring and Active MQ

Reference: http://half-wit4u.blogspot.in/2014/09/jms-topic-using-spring-and-active-mq.html
A JMS client is an application that uses the services of the message broker. There are two types   of clients, Consumer and Producer. Destinations are the place where message get stored for clients. They can be either queues or topics.

In publish/subscribe model, client which produces message is called Publisher and client which consumes message is known as Subscriber.
Topic is a particular destination where Publisher publishes messages. Subscribers subscribe to topic to consume messages. More than one Subscribers can subscribe to same topic and a message can be consumed by many subscribers.
We are going to divide our publisher and subscriber implementation in two part. First we will learn how to create topic and publish a message [XML as String] into topic.

Apache MQ fully supports Spring for configuration of client and message broker. So we will leverage <amq:> tag in our implementation.
As usual we will create Spring JMS template configuration in our spring context file by following these three steps.

Step 1: Configure Connection Factory
?
1
2
3
4
5
6
7
8
9
10
11
<amq:connectionFactory id="connectionFactory"
  brokerURL="tcp://localhost:61616" closeTimeout="10" />
<bean id="pooledJmsConnectionFactory"
  class="org.apache.activemq.pool.PooledConnectionFactory"
  init-method="start" destroy-method="stop">
  <property name="maxConnections" value="15" />
  <property name="connectionFactory" ref="connectionFactory" />
  <property name="expiryTimeout" value="-1" />
  <property name="maximumActive" value="100" />
</bean>
Step 2: Configure JMS destination

?
1
2
3
4
<bean id="mailDestination"
  class="org.apache.activemq.command.ActiveMQTopic">
  <constructor-arg value="mail.topic" />
</bean>
Configure a JMS Template bean
?
1
2
3
4
5
6
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
 <property name="connectionFactory" ref="pooledJmsConnectionFactory" />
 <property name="defaultDestination" ref="mailDestination" />
 <!-- Topic setting -->
 <property name="pubSubDomain" value="true"/>
</bean>
efine producer bean

?
1
2
3
<bean id="producer" class="com.sarf.jms.MessageProducerBean">
 <property name="jmsTemplate" ref="jmsTemplate" />
</bean>

Note : JmsTemplate is designed for use with Java EE containers which  provide connection pooling capabilities as standardized by the Java EE specifications. So in Non J2EE container, every call to the JmsTemplate.send() method  creates and destroys all the JMS resources (connections, consumers, and producers).
So, In non J2EE container, You should use a pooled connection factory for sending messages with JmsTemplate.

As we already know, our producer context xml file will look like this.
appProdContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
 xmlns:oxm="http://www.springframework.org/schema/oxm"
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:amq="http://activemq.apache.org/schema/core"
 xmlns:jms="http://www.springframework.org/schema/jms"
 default-lazy-init="false"
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://activemq.apache.org/schema/core 
   http://activemq.apache.org/schema/core/activemq-core.xsd
   http://www.springframework.org/schema/jms 
   http://www.springframework.org/schema/jms/spring-jms.xsd
   http://cxf.apache.org/jaxrs
   http://cxf.apache.org/schemas/jaxrs.xsd">

  <amq:connectionFactory id="connectionFactory"
    brokerURL="tcp://localhost:61616" closeTimeout="10" />

  <bean id="pooledJmsConnectionFactory"
   class="org.apache.activemq.pool.PooledConnectionFactory"
   init-method="start" destroy-method="stop">
  <!--  <property name="maxConnections" value="15" /> -->
   <property name="connectionFactory" ref="connectionFactory" />
<!--    <property name="expiryTimeout" value="-1" />
   <property name="maximumActive" value="100" /> -->
  </bean>

  <bean id="mailDestination"
     class="org.apache.activemq.command.ActiveMQTopic">
   <constructor-arg value="mail.topic" />
  </bean>
     
  <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
   <property name="connectionFactory" ref="pooledJmsConnectionFactory" />
   <property name="defaultDestination" ref="mailDestination" />
   <!-- Topic setting -->
   <property name="pubSubDomain" value="true"/>
  </bean>

  <bean id="producer" class="com.springtraining.jmstopic.MessageProducerBean">
   <property name="jmsTemplate" ref="jmsTemplate" />
  </bean>

</beans>

We will define our producer bean and leverage Spring JMS template to send message to destination topic.

MessageProducerBean.java

package com.springtraining.jmstopic;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.support.JmsGatewaySupport;

public class MessageProducerBean extends JmsGatewaySupport{
  //Method receives String object and send
  //it to destination topic as BytesMessage
  public void sendMessage(final String myMessage) {
   getJmsTemplate().send(new MessageCreator() {
   public Message createMessage(Session session) throws JMSException {
   //Create byte message
   BytesMessage message = session.createBytesMessage();
   message.writeBytes(myMessage.getBytes());
   return message;
   }
   });
 }

}


To send a xml message to destination topic, we will use a simple main class ProducerTest.
ProducerTest.java
package com.springtraining.jmstopic;

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


public class ProducerTest {   
 public static void main(String[] args) {
    ApplicationContext context =
     new ClassPathXmlApplicationContext("appProdContext.xml");
     MessageProducerBean mp = (MessageProducerBean) 
                  context.getBean("producer");
     /*String msg = "<messageobject><mailId>hsinay@gmail.com</mailId>"+
      "<message>Hello, This is mail from hsinay@gmail.com</message></messageobject>";*/
     String msg = "<MessageObject><mailId>hsinay@gmail.com</mailId>"+
         "<message>Hello, This is mail from Yanish</message></MessageObject>";
     mp.sendMessage(msg);
     System.out.println("Message sent to destination");
     } 

}

Now we will focus on implementing our subscriber which will consume XML and convert it to MessageObject using Spring OXM (Object XML Mappers).

Our MessageObject class will look like this
MessageObject.java
package com.springtraining.jmstopic;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "MessageObject")
public class MessageObject implements Serializable{
  
  @XmlElement(name = "mailId")
  private String mailId;
   
  @XmlElement(name = "message")
  private String message;
     
 public String getMailId() {
  return mailId;
 }
 public void setMailId(String mailId) {
  this.mailId = mailId;
 }
 public String getMessage() {
  return message;
 }
 public void setMessage(String message) {
  this.message = message;
 }

}

As we configured publisher, we will configure subscriber in our appConsumerContext.xml file.

Step 1: Configure Connection Factory

?
1
2
3
4
5
6
7
8
9
10
11
<amq:connectionFactory id="connectionFactory"
  brokerURL="tcp://localhost:61616" closeTimeout="10" />
<bean id="pooledJmsConnectionFactory"
  class="org.apache.activemq.pool.PooledConnectionFactory"
  init-method="start" destroy-method="stop">
  <property name="maxConnections" value="15" />
  <property name="connectionFactory" ref="connectionFactory" />
  <property name="expiryTimeout" value="-1" />
  <property name="maximumActive" value="100" />
</bean>
Step 2: Declare OXM JAXB Marseller bean

?
1
2
3
<oxm:jaxb2-marshaller id="myMarshaller">
 <oxm:class-to-be-bound name="com.sarf.data.MessageObject" />
</oxm:jaxb2-marshaller>
Step 3: Declare Message Converter bean


?
1
2
3
4
5
<bean id="myMessageConverter"
 class="com.sarf.util.MyMarshallingMessageConverter">
 <property name="marshaller" ref="myMarshaller" />
 <property name="unmarshaller" ref="myMarshaller" />
</bean>
We register the MarshallingMessageConverter to use the JAXB2 marshaller for both marshaller abd unmarshaller. This converter bean will be used by spring message listener container to convert incoming message which contains XML into MessageObject using Spring OXM JAXB.

Step 4: Declare Consumer bean 

?
1
<bean id="consumer" class="com.sarf.jms.MessageConsumerBean" />
Step 5: Define JMS Listener 


?
1
2
3
4
5
6
<jms:listener-container connection-factory="pooledJmsConnectionFactory"
  acknowledge="auto" message-converter="myMessageConverter"
  destination-type="topic" >
  <jms:listener destination="mail.topic" ref="consumer"
   method="onMessage" />
</jms:listener-container>
Message listener container is used to receive messages from a JMS message queue/topic. Here we are creating a message listener container which is using consumer bean reference to delegate messages on onMessage() method.

So our final appConsumerContext.xml will look like
appConsumerContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
 xmlns:oxm="http://www.springframework.org/schema/oxm"
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:amq="http://activemq.apache.org/schema/core"
 xmlns:jms="http://www.springframework.org/schema/jms"
 default-lazy-init="false"
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/oxm 
   http://www.springframework.org/schema/oxm/spring-oxm.xsd
   http://activemq.apache.org/schema/core 
   http://activemq.apache.org/schema/core/activemq-core.xsd
   http://www.springframework.org/schema/jms 
   http://www.springframework.org/schema/jms/spring-jms.xsd
   http://cxf.apache.org/jaxrs
   http://cxf.apache.org/schemas/jaxrs.xsd">

   <amq:connectionFactory id="connectionFactory"
    brokerURL="tcp://localhost:61616" closeTimeout="10" />

    <bean id="pooledJmsConnectionFactory"
          class="org.apache.activemq.pool.PooledConnectionFactory"
     init-method="start" destroy-method="stop">
      <!-- <property name="maxConnections" value="15" /> -->
      <property name="connectionFactory" ref="connectionFactory" />
<!--       <property name="expiryTimeout" value="-1" />
      <property name="maximumActive" value="100" /> -->
    </bean>

    <oxm:jaxb2-marshaller id="myMarshaller">
     <oxm:class-to-be-bound name="com.springtraining.jmstopic.MessageObject" />
    </oxm:jaxb2-marshaller>

    <!-- jaxb used for converting xml to object -->
    <bean id="myMessageConverter"
          class="com.springtraining.jmstopic.MyMarshallingMessageConverter">
     <property name="marshaller" ref="myMarshaller" />
     <property name="unmarshaller" ref="myMarshaller" />
    </bean>

    <bean id="consumer" class="com.springtraining.jmstopic.MessageConsumerBean" />

    <!-- destination-type="durableTopic" -->
    <jms:listener-container connection-factory="pooledJmsConnectionFactory"
 acknowledge="auto" message-converter="myMessageConverter"
 destination-type="topic">
 <jms:listener destination="mail.topic" ref="consumer"
  method="onMessage" />
    </jms:listener-container>

</beans>

After having this configuration file, Now its time to look at our Message Converter class and message consumer class.
MyMarshallingMessageConverter.java
package com.springtraining.jmstopic;

import javax.jms.JMSException;
import javax.jms.Message;
import org.springframework.jms.support.converter.MarshallingMessageConverter;
import org.springframework.jms.support.converter.MessageConversionException;

public class MyMarshallingMessageConverter 
 extends MarshallingMessageConverter {
  @Override
  public Object fromMessage(Message message) 
     throws JMSException, MessageConversionException{
     System.out.println(message.getJMSDestination());
 return super.fromMessage(message);
   }

}

MessageConsumerBean.java
package com.springtraining.jmstopic;

public class MessageConsumerBean {
public void onMessage(MessageObject message) {
 try {
     System.out.println("Mail # "+message.getMailId()+" received." + "Message:"+message.getMessage());
     } catch (Exception e) {
e.printStackTrace();
}
 }

}
We will use this simple ConsumerTest class to initialize the application context in main method to listen to topic.
ConsumerTest.java
package com.springtraining.jmstopic;

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

public class ConsumerTest {
 public static void main(String[] args) {
    ApplicationContext context =
     new ClassPathXmlApplicationContext("appConsumerContext.xml");
     System.out.println("Consumer listening !!!!!!");
   }

}

To run program in single eclipse. Running both Consumer/Publisher.
To.java
package com.springtraining.jmstopic;

public class To {

static String[] str = {};

public static void main(String... args){
ConsumerTest con = new ConsumerTest();
con.main(str);
ProducerTest test = new ProducerTest();
test.main(str);

}

}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sarf</groupId>
<artifactId>JMSMailSystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>JMSMailSystem</name>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>JMSMailSystem</warName>
<outputDirectory>D:\Server\jboss-as-7.1.0.Final\standalone\deployments</outputDirectory>
</configuration>
</plugin>
</plugins>
<finalName>JMSMailSystem</finalName>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>

<!-- <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId>
<version>1.1</version> </dependency> -->
<dependency>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.6</version>
</dependency>

<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.7.0</version>
</dependency>

</dependencies>
<repositories>
<repository>
<id>repository.jboss.org-public</id>
<name>JBoss repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public</url>
</repository>

</repositories>
</project>