Chapter 23
896
We've already seen examples of message creation and message setting in the Publisher and Sender
examples. The Publisher example creates and resets the contents of a text message and an object message:
textMessage = topicSession.createTextMessage();
textMessage.setText(msg);
objectMessage = topicSession.createObjectMessage();
objectMessage.setObject(object);
The client creates the message using the create[type]() method of the Session object, where [type]
is one of the above message types. The client can set the message body of an existing message using the
set[type](Type newMessageBody) method. A message body cannot be set if the message is read-only.
Transactions
In JMS a group of messages can act as a single unit of work for transactional purposes. If an error occurs
while the group of messages is being processed, the entire unit of work is re-processed.
Transactions are controlled at the session level. A session may be specified as transacted upon creation.
Each session supports a series of transactions, where each transaction is a group of messages. If an error
occurs while any message in the group is being processed, a rollback is performed on the entire group.
If a producer does a transacted send the server holds all of the messages in the transacted group until
the producer commits the transaction, at which point the messages are all delivered at once. If an error
occurs and the transaction is rolled back then none of the messages are sent.
If a consumer does a transacted receive all of the messages are held on the server until the consumer
commits the transaction, at which point the broker stops holding the messages. If an error occurs during
the transaction all of the messages in the group are re-sent to the consumer.
The client determines when the transaction is complete and commits or rolls back the transaction using
the commit() or rollback() method of the Session.
The JMS specification does not require that JMS implementations provide support for distributed
transactions. Some JMS vendors provide support for distributed transactions through the Java
Transaction API.
JMS and XML
Often developers wish to transport XML data in JMS messages. There is no JMS message type for XML
data but the body of a text message may be used to transport XML data. To send an XML document in
a JMS message, simply convert the document into a String, create a text message out of the String,
then send the message.
Note that some vendors provide an XMLMessage type, but this is not a required by the JMS
specification. For example, both BEA's WebLogic
(http://commerce.bea.com/downloads/weblogic_server.jsp) and Progress Software's
SonicMQ (http://www.progress.com/sonicmq) support XMLMessage.
Upon receipt of the XML message, the message consumer may parse the XML using a DOM or SAX
parser, or just read the XML message as a string.