JMS Message Structure
As discussed in Chapter 2, "Java Message Service," the JMS message is composed of a header, properties, and body, and it is typed based on the message data contained within the message body. The JMS message class hierarchy is organized such that the Message interface, which is the root interface for all the JMS message types, defines the header fields, property facility, and associated accessor methods. The Message interface is extended by the body-specific message interfacesBytesMessage, TextMessage, StreamMessage, MapMessage, and ObjectMessagewhich define the accessor methods associated with their specific body type.
It should be noted that in the interest of conciseness and clarity, when discussing attribute types I use the common interface classes (see Table 2-1), such as Destination. Depending on the messaging domain being used, the corresponding domain-specific interface, such as Queue or Topic, could be substituted.
The message header is comprised of the following fields, which are present in every JMS message. Setter and getter methods are provided for all fields, but as detailed, setting a value often has no effect if the message is being sent and the field is populated by the provider on completion of the send.
JMSDestination: JMSDestination holds a Destination object that represents the destination to which the message is being sentfor example, Queue or Topic. Its value is set by the provider after completion of the send and matches the destination associated with the MessageProducer. A getter method is defined to allow the receiving application to access the value of JMSDestination. However, although a setter method is provided, the value of JMSDestination is ignored during a send.
JMSDeliveryMode: JMSDeliveryMode is used to define the persistence of a message. A nonpersistent message is not logged to a persistent message store by the provider, implying that the message cannot be recovered in the event of a provider process failure. Persistent messages, on the other hand, are logged and are thus recoverable by the provider when it restarts. JMSDeliveryMode holds an integer value defined by the interface DeliveryMode. DeliveryMode contains two static integer values: NONPERSISTENT and PERSISTENT. The value of JMSDeliveryMode is set by the provider after completion of the send. It is based on the value specified by the sending method, which can be either DeliveryMode.NONPERSISTENT or DeliveryMode.PERSISTENT. The provider defaults to persistent delivery if no value is specified. As with JMSDestination, any value set by the setter method is ignored on send. A getter method provides access to the populated value.
JMSExpiration: JMSExpiration stores the expiration time of the message. This is calculated as the current time plus a specified timeToLive. The value of timeToLive is specified on the sending method in milliseconds, and the provider populates JMSExpiration (type Long) with the computed value in milliseconds on completion of the send. If a value for timeToLive is not specified or is specified as zero, JMSExpiration is set to zero, signifying that the message does not expire. Any value set for JMSExpiration is ignored on the send. Once a message has expired, the JMS client is unable to retrieve the message. Typically, the message is discarded by the provider at this point. JMSExpiration provides a convenient way to clean up messages that have a well-defined relevance period, such as a reply to a request that has arrived late.
JMSPriority: JMS defines transmission priority levels 0 to 9, with 0 as the lowest priority and 9 as the highest. It additionally specifies that priorities 0 to 4 should be considered gradations of normal delivery and priorities 5 to 9 as gradations of expedited delivery. The provider populates JMSPriority (type int) on completion of the send based on the value specified by the sending method.
JMSTimeStamp: The JMSTimeStamp field is populated by the provider during the send; the value set is in the format of a normal Java millisecond time value.
JMSMessageID: JMSMessageID uniquely identifies a message. It is defined as a String and ignored if set when the message is sent. It is populated with a provider-assigned value on completion of the send. The provider-assigned identifier is prefixed with ID:.
JMSCorrelationID: The JMSCorrelationID field is typically used to link two messages together. For example, in order to link a given reply to a request, the JMS client could specify that the JMSCorrelationID of the incoming reply should match the JMSMessageID of the sent request. This requires the servicing client to set the JMSCorrelationID of the reply to the JMSMessageID of the request before sending the reply. Consequently, if used, this field is set by the JMS client, as shown:
//set correlationID replyMsg.setJMSCorrelationID(requestMsg.getJMSMessageID());
JMS additionally allows for the case where the JMS client needs to use a specific value for linking messages; in this case an alternative string value can be set, but it should not be prefixed with ID:. If the JMS client is servicing a request from a non-JMS client and needs to assign a specific value for use with such clients, JMS defines a byte array optional type for JMSCorrelationID. However, providers are not required to implement support for this optional type.
JMSReplyTo: JMSReplyTo is set by the client and takes as value a Destination object that specifies where replies to this message are to be sent. This implies that this field is set only if a reply is required. By default it is set to null. JMSReplyTo can be set as shown:
//set reply to destination Queue replyQ = (Queue)ctx.lookup(jmsReplyQ); requestMsg.setJMSReplyTo(replyQ);
JMSType: JMSType contains a message type identifier that is set by the client. Its purpose is to enable clients of providers who provide a message definition repository to associate with the contained message body a reference to its physical format definition in the provider's message repository.
JMSRedelivered: The JMSRedelivered field takes a Boolean value set by the provider to signify that the message has been previously delivered to the client. It is only relevant when consuming a message and serves to alert the client (if checked) that it has previously attempted processing of this message. Recall from our discussion of message consumers and "poison" messages in Chapter 1, "Enterprise Messaging," that JMSRedelivered can help address the issue of infinite repeated processing, which could occur if the message is being processed within a transaction and being redelivered because processing failed.
Overriding Message Header Fields
JMS allows providers to provide a means for JMS administrators to override the client's settings for JMSDeliveryMode, JMSExpiration, and JMSPriority. This could be to enforce company policy or adopted best practice, or to change the behavior of the client without having to change code. JMS does not define specifically how this facility should be implemented, but IBM JMS providers utilize the administered objects, specifically the Destination object, to provide this feature. As discussed in Chapter 2, administered objects are stored outside the application in a JNDI namespace and contain vendor-specific settings. The Destination objects defined for IBM JMS providers allow values for JMSDeliveryMode, JMSExpiration, and JMSPriority to be set. By default they are set to "application specifies," but if set to an explicit value, they override any settings specified by the client on the sending method. We review the IBM JMSadministered objects in detail in Chapter 6, "IBM JMSAdministered Objects."
Properties are used to add optional fields to the header. A property can be specified by the application, be one of the standard properties defined by JMS, or be provider-specific. When sending a message, properties can be set using associated setter methods. In the received message, properties are read-only, and any attempt to set the properties on a received message results in a MessageNotWriteableException. If it is desired to modify the properties of a received messagefor instance, the application is performing a brokering function and needs to modify the attributes of the message before forwarding it to the next destinationthen the clearProperties() method is called on the message object.
Consider an audit application that tracks all orders being sent but wants to log an entry only if the order value is over a certain amount. An approach to solving this problem is to have the application process every order message passed to it and check the contents of the message to ascertain if the order value is above the threshold. A more efficient approach is to have the client application tell the provider that of all the messages sent to it, only those with an order value greater than some specified amount should be delivered. Application-specific properties enable this approach by offering a basis for a provider to filter messages based on application-specific criteria.
Continuing with our example, the sending application defines and assigns a value to an application-specific property, which we call orderValue. The message is then sent. The audit application defines a message selector (more on this in the next section) that details the selection criteria based on the application-specific property orderValue. The provider subsequently passes the sent message to the audit application only if the selection criteria are satisfied.
Why go through all this? Why not simply specify the selection criteria based on the "total cost" field in the message? The answer is quite simply that message selectors cannot operate on the message body. If message selectors did operate on the message body, then providers would have to have a means to successfully parse each message (a nontrivial task; see "Message Definition"), and we would be faced with the same performance bottleneck that having the application check each message would attract. In addition, this approach assumes that the data we want to filter on is contained in the message, which is not necessarily the case.
Handling the filter property as an optional header field is obviously much more efficient, as the provider understands the structure of the header, and given the typically small size of the header relative to the body, the property can be accessed much more quickly. Application-specific properties are typed and can be boolean, byte, short, int, long, float, double, and String. The properties are set by the sending application on the outbound message. For example,
//set property on outgoing message outMessage.setIntProperty("orderValue", 3000);
Setter methods exist for each type, and they accept as arguments the property name and the associated value. A setObjectProperty() method is provided if the objectified version of the primitive types is to be used. As would be expected, corresponding getter methods are defined. Application-specific properties are used not only for selection criteria, but for a wealth of reasons, such as a means of specifying processing flags that can't be carried in the message. However, it is for use in message selection that they are most often considered. A list of application-specific properties defined for a message can be retrieved by calling getPropertyNames() on the message, which returns an Enumeration object.
Standard properties are additional header fields defined by JMS, which further define the message. Apart from two noted exceptions, JMSXGroupID and JMSXGroupSeq, support for all other standard properties is optional. To determine which are supported by a given JMS provider, you can obviously read provider-specific documentation or use ConnectionMetaData.getJMSXPropertyNames() as shown:
// retrieve factory ConnectionFactory factory = /*JNDI LOOKUP*/ // create connection Connection connection = factory.createConnection(); //retrieve information describing the connection ConnectionMetaData connInfo = connection.getMetaData(); //getJMSXPropertyNames Enumeration propNames = connInfo.getJMSXPropertyNames();
ConnectionMetaData is a useful JMS interface that provides information that describes a JMS provider's implementation. It offers access to details such as JMS version, provider name, and other information. The IBM JMS providers support the following standard properties.
JMSXUserID: JMSXUserID contains the identity of the user sending the message. It is set by the provider on send and usually resolves to the user ID under which the client application is running. It is defined as a String.
JMSXAppID: JMSXAppID is the identifier associated with the application sending the message. It is similarly set by the provider on send. It is defined as a String.
JMSXDeliveryCount: JMSXDeliveryCount defines the number of times that a message has been delivered. It complements JMSRedelivered, which simply signifies that a message has been previously delivered, by providing a count of the number of times delivery as been attempted. It is set by the provider when the message is received.
JMSXGroupID and JMSXGroupSeq: JMSXGroupID and JMSXGroupSeq together uniquely define a message as belonging to a particular group of messages and being at a certain position (sequence) in the group. They are set by the client before sending and are defined using the set<type>Property methods as shown (they are defined as a String and int respectively):
//set group properties on outgoing message outMessage.setStringProperty("JMSXGroupID", "10000001"); outMessage.setIntProperty("JMSXGroupSeq", 1);
As the name suggests, JMS offers a means for providers to include specific fields in the header. The stated purpose is to support communication with non-JMS clients that might require certain properties set. Thus, they should never be used when knowingly communicating between two JMS clients. As would be expected, IBM JMS providers do specify a number of provider-specific properties, given that the messaging provider can be accessed using a variety of APIs and languages (see Chapter 5, "IBM JMS Providers"). Provider-specific properties are prefixed by JMS_<vendor_name>, in our case JMS_IBM; however, the properties are not detailed here because they do not add much to our JMS-specific discussion at this time. In Chapter 7, "JMS Implementation Scenarios," where we examine a usage scenario that involves knowingly communicating with a non-JMS client, we explore the use of provider-specific properties in a more appropriate context.
A JMS message selector is used by a JMS client to specify which messages it is interested in. It is based on values contained in the message header, which includes standard header fields as well as optional fields that have been added via application-, standard-, or provider-specific properties. As noted earlier, a message selector cannot refer to message body values. A message selector is a Boolean expression that, when it evaluates to true, results in the matched message being passed to the client. It is defined as a String, and its syntax is based on a subset of the SQL92 conditional syntax.
Creating a selector involves generating a String that conforms to the defined syntax. For instance, continuing with our previous example of the audit application that wants to receive messages only if the orderValue (specified as an application-specific property) is greater than a certain threshold, the message selector would be of the form
//Set selector String selector = "orderValue > 2500";
Another common use of message selectors is to match a reply message to the original request based on the JMSCorrelationID, as shown (note that the syntax requires quotes around Strings):
//Set selector String messageID = requestMsg.getJMSMessageID(); String selector = "JMSCorrelationID ='" + messageID + "'";
The syntax for message selectors enables pattern matching whereby the selector can match a variety of messages. For example, to match all messages that have a postal code that begins with SOsuch as SO53 2NW and SO51 2JNthe selector would be of the form
//Set selector String selector = "postalcode LIKE 'SO%'";
Given that a message selector is a Boolean expression, expressions can be combined using constructs such as AND or OR:
//Set selector String selector = "stock = 'IBM' OR stock = 'Microsoft' AND price = 100";
Once a message selector is defined, it is associated with the MessageConsumer that will check the specified destination for messages (we examine this in more detail in Chapter 4, "Using the JMS API"):
//get reply QueueReceiver receiver = session.createQueueReceiver(replyQ, selector); TextMessage replyMsg = receiver.receive();
JMS enables fairly sophisticated patterns to be defined for message selectors, and the rules regarding selector syntax defined by JMS are extensive. They are reproduced in Appendix A for your convenience. In all cases it is important to remember that message selectors can be specified only on header values and not the message body. It is thus not uncommon to find application-specific properties being defined that duplicate certain fields in the message body so that the message can be selected based on what is essentially message content.
As discussed in Chapter 2, JMS supports five types of message bodies, with each body type represented by a different message interface: BytesMessage, TextMessage, StreamMessage, MapMessage, and ObjectMessage. The choice of message type used is to a great extent, but not exclusively, governed by the nature of the data being sent. To recap,
BytesMessage stores data as a sequence of bytes, supports the most basic representation of data, and thus can contain varied payloads.
TextMessage stores data as a String, a common representation of enterprise data.
StreamMessage stores data as a sequence of typed fields, for example, JohnDoe33, defined as a sequence of two strings (John, Doe), and an integer (33).
MapMessage stores data as a set of key-value pairs. The key is defined as a string, and the value is typedfor example, Age:33, where Age is the key and 33 the integer value.
ObjectMessage stores a serialized Java object.
BytesMessage and TextMessage are probably the most common type of message used. Both handle data in a form that facilitates the easy exchange of data across the enterprise between JMS applications as well as non-JMS applications. The common physical formats adoptedXML, tagged/delimited, and record-orientedreadily lend themselves to byte or string representations and thus can be easily transported using BytesMessage or TextMessage. In particular, a record-oriented format rendered in a byte array is often the format of choice for exchanging data with legacy applications.
ObjectMessage is specialized in its use, as it stores a serialized Java object. Clearly, the recipient must be able to deserialize the received Java object, and thus the use of this message type is generally associated with JMS-to-JMS communication. The representation of data as a Java object can be efficient from the JMS client's point of view, as no explicit parsing or construction of the message body is required. The exchange of the object's class definition between JMS clients is also a trivial exercise, as this is part of everyday Java programming practice. However, when you consider messaging within an enterprise, rarely are all the interacting applications written in Java. More importantly, even if the ultimate destination is a JMS client, the message may pass through other infrastructure applications, such as message trackers that are not Java-based. Even when the target application is Java-based, another consideration, particularly with off-the-shelf packages, is whether the application supports the use of class definitions as the basis for defining data that will be exchanged. In truth, you are more likely to find support for XML than for Java objects. Consequently, the use of the ObjectMessage places more restrictions on who can ultimately process the contained data (object) and may not provide as flexible a solution in comparison to one built on the exchange of a non-language-based format such as XML.
StreamMessage and MapMessage are rather unique in that while JMS defines the interface, it does not actually specify the associated physical constructstring, serialized object, or byte arrayin which the typed sequence or key-value pairs are contained. The stated reason for this is that JMS provides these message types in support of JMS providers whose native implementation supports some form of self-defining format, the idea being that the provider renders the StreamMessage or MapMessage in its native format, facilitating the exchange of data with native clientsthat is, non-JMS clients that use the provider's native (proprietary) API. Given that the IBM JMS providers do not have a native self-defining format (data is generally treated as being opaque), the value of StreamMessage and MapMessage for this purpose is questionable.
With the IBM JMS providers, the contents of StreamMessage and MapMessage are rendered in XML, a standards-based self-describing format.
A StreamMessage is rendered in the following format:
<stream> <elt dt='datatype '>value</elt> <elt dt='datatype '>value</elt> ..... </stream>
Every field is sent using the same tag name, elt, where elt contains an XML attribute, dt, that specifies the data type of the field in the sequence and has as value the actual contents of the field. The default type is String, so dt='string ' is omitted for string elements.
A MapMessage takes the form:
<map> <elementName1 dt='datatype '>value</elementName1> <elementName2 dt='datatype '>value</elementName2> ..... </map>
In this case, elementName1 ..... N maps to the key in the key-value pair.
Given that StreamMessage and MapMessage are rendered as XML by the IBM JMS providers, they do enable the exchange of data in a flexible form. In the case where the user does not want to develop XML data formats, they provide one out of the box that can be readily used. From the perspective of the JMS client, they do insulate the client from the fact that the data is XML, providing a simple interface to manipulate data, and unlike for ObjectMessage, the data can be handled by non-JMS and non-Java clients. However, because the implementation of StreamMessage and MapMessage is provider-specific, they should be used carefully. If it is desired to exchange data in XML, then defining an XML structure and using a BytesMessage or TextMessage provides a more generic, flexible, and portable approach.
As with properties, the body of a received message is read-only and cannot be directly modified by the receiving application. If the application wishes to populate the body of a received message with data, then it calls the clearBody() method on the message.