jms

JMS TextMessage Example

JMS defines several types of messages that can be posted by an application. They all extend the Message interface.

This type carries a java.lang.String as its payload. It is useful for exchanging simple text messages and also for more complex character data, such as XML documents. In this article, we will look into examples of simple as well as XML based TextMessage.

1. Dependencies

In order to send and receive JMS messages to and from a JMS message broker, we need to include the message service library. In this example we are using activeMq so our pom.xml will have dependencies related to spring as well as activeMQ.

pom.xml:

<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.javacodegeeks.jms</groupId>
	<artifactId>springJmsQueue</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-all</artifactId>
			<version>5.12.0</version>
		</dependency>
	</dependencies>
	
</project>

2. TextMessage API

A TextMessage is used to send a message containing a java.lang.String. One can either send a simple text or XML content.

A TextMessage contains two methods setText(String) and getText().

TextMessage:

public interface TextMessage extends Message {
    void setText(String string) throws JMSException;

    String getText() throws JMSException;
}

3. Creating TextMessage

The session object acts as a factory for creating messages. In order to create a TextMessage object, we need to call createTextMessage() method on Session object and pass the text message we want to send. One can also call createTextMessage() first and then later set its text message.

Session:

public interface Session extends Runnable {
...
    TextMessage createTextMessage() throws JMSException;

    TextMessage createTextMessage(String text) throws JMSException;
...
}

4. Sending and Receiving TextMessage

We know how to create a text message. Let’s now send it to a destination and receive it.

Start the broker first.

BrokerLauncher:

package com.javacodegeeks.jms;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;

public class BrokerLauncher {
	public static void main(String[] args) throws URISyntaxException, Exception {
		BrokerService broker = BrokerFactory.createBroker(new URI(
				"broker:(tcp://localhost:61616)"));
		broker.start();		
	}
}

We will call createTextMessage(payload) on Session object to create the text message.

Message msg = session.createTextMessage(payload);

Next, we will send the text message.

producer.send(msg);

JmsTextMessageProducer:

package com.javacodegeeks.jms;

import java.net.URISyntaxException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JmsTextMessageProducer {
	public static void main(String[] args) throws URISyntaxException, Exception {
		Connection connection = null;
		try {
			// Producer
			ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
					"tcp://localhost:61616");
			connection = connectionFactory.createConnection();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			Queue queue = session.createQueue("customerQueue");
			MessageProducer producer = session.createProducer(queue);
			String payload = "Hi, I am text message";
			Message msg = session.createTextMessage(payload);
			System.out.println("Sending text '" + payload + "'");
			producer.send(msg);
			session.close();
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
	}
}

Output:

Sending text 'Hi, I am text message'

Once the message is received we type cast it to TextMessage, since this is the message type we are expecting from the client. In order to access the payload contained by TextMessage object, the consumer calls the getText() method.

JmsTextMessageConsumer:

package com.javacodegeeks.jms;

import java.net.URISyntaxException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JmsTextMessageConsumer {
	public static void main(String[] args) throws URISyntaxException, Exception {
		Connection connection = null;
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				"tcp://localhost:61616");
		connection = connectionFactory.createConnection();
		Session session = connection.createSession(false,
				Session.AUTO_ACKNOWLEDGE);
		try {
			Queue queue = session.createQueue("customerQueue");

			// Consumer
			MessageConsumer consumer = session.createConsumer(queue);
			connection.start();
			TextMessage textMsg = (TextMessage) consumer.receive();
			System.out.println(textMsg);
			System.out.println("Received: " + textMsg.getText());		
		} finally {
			if (session != null) {
				session.close();
			}
			if (connection != null) {
				connection.close();
			}
		}
	}
}

We print here the TextMessage object and the contained payload.

Output:

ActiveMQTextMessage {commandId = 5, responseRequired = true, messageId = ID:INMAA1-L1005-64809-1450096231882-1:1:1:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:INMAA1-L1005-64809-1450096231882-1:1:1:1, destination = queue://customerQueue, transactionId = null, expiration = 0, timestamp = 1450096232122, arrival = 0, brokerInTime = 1450096232124, brokerOutTime = 1450096273254, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@6e3c1e69, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = Hi, I am text message}
Received: Hi, I am text message

5. Overloaded Method of TextMessage Creation

One can also call createTextMessage() first and then later set its text message.

JmsTextMessageProducer2:

package com.javacodegeeks.jms;

import java.net.URISyntaxException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JmsTextMessageProducer2 {
	public static void main(String[] args) throws URISyntaxException, Exception {
		Connection connection = null;
		try {
			// Producer
			ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
					"tcp://localhost:61616");
			connection = connectionFactory.createConnection();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			Queue queue = session.createQueue("customerQueue");
			MessageProducer producer = session.createProducer(queue);
			String payload = "Hi, I am text message";
			TextMessage textMsg = session.createTextMessage();
			textMsg.setText(payload);
			System.out.println("Sending text '" + payload + "'");
			producer.send(textMsg);
			session.close();
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
	}
}

6. Send and Receiving XML

TextMessage message type can also be used to support XML. Since XML is a standard format, it can be safely used as JMS payload to communicate between sub-systems. In this example, we will be creating a JMS TextMessage from an XML Document object and vice versa.

We want to send employee XML from one system to another. We read employee XML file and create a DOM Document object from it. If one wants the DOM document object can be manipulated further. Once we have the DOM document object ready, we will use getXmlAsDOMDocument() method to convert DOM document to a String object.

The string returned from this call is then used to create text message which we will use it to send it to the client.
When a client receives the TextMeessage, the XML document is retrieved. This is then converted to a DOM Document object

emp.xml:

<?xml version="1.0"?>
<employees>
	<employee id="1">
		<name>John</name>
		<age>41</age>
	</employee>
	<employee id="2">
		<name>Raghu</name>
		<age>21</age>
	</employee>	
</employees>

JmsXmlAsTextMessage:

package com.javacodegeeks.jms;

import java.io.StringReader;
import java.io.StringWriter;
import java.net.URISyntaxException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class JmsXmlAsTextMessage {
	public static void main(String[] args) throws URISyntaxException, Exception {
		Connection connection = null;
		try {
			// Producer
			ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
					"tcp://localhost:61616");
			connection = connectionFactory.createConnection();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			Queue queue = session.createQueue("customerQueue");
			MessageProducer producer = session.createProducer(queue);
			Document doc = parseXml();
			String xmlPayload = getXmlAsString(doc);
			Message msg = session.createTextMessage(xmlPayload);
			System.out.println("Sending text '" + xmlPayload + "'");
			producer.send(msg);

			MessageConsumer consumer = session.createConsumer(queue);
			connection.start();
			TextMessage textMsg = (TextMessage) consumer.receive();
			String xml = textMsg.getText();
			System.out.println("Received: '" + xml + "'");
			Document receivedDoc = getXmlAsDOMDocument(xml);
			Node employeesNode = receivedDoc.getFirstChild();
			NodeList nodeList = employeesNode.getChildNodes();
			int empCount = 0;
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node childNode = nodeList.item(i);
				if (childNode.getNodeName().equals("employee")) {
					empCount++;
				}
			}
			System.out.println("emp count: " + empCount);
			session.close();
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
	}

	private static Document parseXml() throws Exception {
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory
				.newDocumentBuilder();
		return documentBuilder.parse(JmsXmlAsTextMessage.class
				.getResourceAsStream("emp.xml"));
	}

	public static String getXmlAsString(Document document) throws Exception {
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		StringWriter writer = new StringWriter();
		transformer
				.transform(new DOMSource(document), new StreamResult(writer));
		String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
		return output;
	}

	public static Document getXmlAsDOMDocument(String xmlString) throws Exception {
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory
				.newDocumentBuilder();
		return documentBuilder.parse(
                new InputSource(new StringReader(xmlString)));
	}
}

Output:

Sending text '			John		41				Raghu		21		'
Received: '			John		41				Raghu		21		'
Document: 1
emp count: 2

7. Download the eclipse project

This was an example about JMS TextMessage.

Download
You can download the full source code of this example here: jmsTextMessageExample.zip

Ram Mokkapaty

Ram holds a master's degree in Machine Design from IT B.H.U. His expertise lies in test driven development and re-factoring. He is passionate about open source technologies and actively blogs on various java and open-source technologies like spring. He works as a principal Engineer in the logistics domain.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button