Send Object Message JMS

In previous example you saw how to send simple string message and XML file using JMS. Today I will show you how to send Object thorough message. JMS API support sending object through message only condition is object should be Serializable before sending. We will use Person.java class which implements Serializable interface with three attribute. As this class is implementing Serializable interface so that we can send through message. Please follow steps below:

Tools used:

  • JBoss application server jboss-6.1.0.Final community version (You can use any version of JBoss application server which you could download from here). If you are using version other than jboss-6.1.0.Final community version only JMS configuration will be different and use this tutorial to configure Queue and topic.
  • Eclipse Kepler (You could use any version of eclipse above 4.2)

Steps:

  • Configure JMS Queue destination on jboss server : Go to jboss-6.1.0.Final\server\default\deploy\hornetq\hornetq-jms.xml and add below Queue:
<queue name="testQueue">
   <entry name="/javahonk/queue"/>
</queue>
  • Create maven project JMSSendObjectMessage and below is final project snap shot where we have create publisher subscriber  and one model class Person which will be send through messaging

Send Object Message JMS

  •  Configure JBoss application server in eclipse using this tutorial
  • To include include all JBoss related jars to to class path: right click project –> properties –> Java build path –> on library tab click add library… –> Server runtime –> if you configured Jboss in eclipse you will see JBoss Runtime server choose it –> click finish.

Java classes:

  • Person.java that will be send through message:
package com.javahonk.model;
 
import java.io.Serializable;
 
public class Person implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private String firstName;
	private String lastName;
	private String location;
	
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
 
}
  •  JMSQueuePublisher.java:
package com.javahonk;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;

import com.javahonk.model.Person;

public class JMSQueuePublisher {
	
	String destinationName = "javahonk/queue";
	Context ic = null;
	ConnectionFactory cf = null;
	Connection connection = null;
	Queue queue = null;
	Session session = null;
	MessageProducer publisher = null;

	public static void main(String[] args) throws Exception {
		
		try {
			
			JMSQueuePublisher jBossJMSTopicPublisher = new JMSQueuePublisher();
			jBossJMSTopicPublisher.initializeConnection();

			// Read from command line
			BufferedReader commandLine = new java.io.BufferedReader(new InputStreamReader(System.in));

			// Loop until the word "exit" is typed
			while (true) {
				String s = commandLine.readLine();
				if (s.equalsIgnoreCase("exit")) {
					jBossJMSTopicPublisher.close(); // close down connection
					System.exit(0);// exit program
				} else{
					jBossJMSTopicPublisher.sendJMSMessageOnTopic(s);					
				}	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Context getInitialContext() throws javax.naming.NamingException {

		Properties p = new Properties();
		p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		p.put(Context.URL_PKG_PREFIXES, " org.jboss.naming:org.jnp.interfaces");
		p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		return new javax.naming.InitialContext(p);
	}
	
	public void initializeConnection() throws Exception {
		
		ic = getInitialContext();
		cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
		queue = (Queue) ic.lookup(destinationName);
		connection = cf.createConnection();	
		session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
		publisher = session.createProducer(queue);
		connection.start();
		
	}

	public void sendJMSMessageOnTopic(String s) throws Exception {
		
		String value[] = s.split("\\s+");
		
		Person person = new Person();
		person.setFirstName(value[0]);
		person.setLastName(value[1]);
		person.setLocation(value[2]);
		
		ObjectMessage objMessage = session.createObjectMessage();
		objMessage.setObject(person);
		publisher.send(objMessage);		
	}
	
	/* Close the JMS connection */
	public void close() throws Exception {
		try {
			connection.close();
		} finally {
			if (ic != null) {
				try {
					ic.close();
				} catch (Exception e) {
					throw e;
				}
			}

			try {
				if (connection != null) {
					connection.close();
				}
			} catch (JMSException jmse) {
				System.out.println("Could not close connection " + connection + " exception was " + jmse);
			}
		}
	}

}
  • JMSQueueSubscriber.java:
package com.javahonk;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;

import com.javahonk.model.Person;

public class JMSQueueSubscriber implements MessageListener {
	
	String destinationName = "javahonk/queue";
	Context ic = null;
	ConnectionFactory cf = null;
	Connection connection = null;
	Queue queue = null;
	Session session = null;
	MessageProducer publisher = null;
	
	public static void main(String[] args) throws Exception {
		
		try {
			
			JMSQueueSubscriber jBossJMSTopicSubscriber = new JMSQueueSubscriber();
			jBossJMSTopicSubscriber.initializeConnection();

			// Read from command line
			BufferedReader commandLine = new java.io.BufferedReader(new InputStreamReader(System.in));

			// Loop until the word "exit" is typed
			while (true) {
				String s = commandLine.readLine();
				if (s.equalsIgnoreCase("exit")) {
					jBossJMSTopicSubscriber.close(); // close down connection
					System.exit(0);// exit program
				}	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Context getInitialContext() throws javax.naming.NamingException {

		Properties p = new Properties();
		p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		p.put(Context.URL_PKG_PREFIXES, " org.jboss.naming:org.jnp.interfaces");
		p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		return new javax.naming.InitialContext(p);
	}
	
	public void initializeConnection() throws Exception {
		
		ic = getInitialContext();
		cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
		queue = (Queue) ic.lookup(destinationName);
		connection = cf.createConnection();	
		session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
		MessageConsumer subscriber = session.createConsumer(queue);
		subscriber.setMessageListener(this);
		connection.start();
		
	}
	
	/* Close the JMS connection */
	public void close() throws Exception {
		try {
			connection.close();
		} finally {
			if (ic != null) {
				try {
					ic.close();
				} catch (Exception e) {
					throw e;
				}
			}

			try {
				if (connection != null) {
					connection.close();
				}
			} catch (JMSException jmse) {
				System.out.println("Could not close connection " + connection + " exception was " + jmse);
			}
		}
	}

	public synchronized void onMessage(Message message) {
		
		try {
			ObjectMessage objectMessage = (ObjectMessage) message;
			Person person = (Person)objectMessage.getObject();
			if (null != person) {
				System.out.println("First name: "+person.getFirstName());
				System.out.println("Last name: "+person.getLastName());
				System.out.println("Location: "+person.getLocation());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}	

}
  • Start JBoss server: To run above program you will have start JBoss first. You can start JBoss either form inside your eclipse or go to %JBOSS_HOME%/bin –> Double click run.bat to start the server. Once server is started it will pick up configured topic automatically.
  • Both class has main method start them separately as java application. Once both started go to publisher console and pass value which you want to send to the subscriber. Below is example:

Publisher console – Enter value separated by space for firstName, lastName and location then press enter:

Send Object Message JMS

Subscriber console – Subscriber will process Person object and print its value on console:

Send Object Message JMS

  • That’s it for more details on JMS messaging please refer oracle here

Leave a Reply

Your email address will not be published. Required fields are marked *