Home > Articles > Web Services > XML

This chapter is from the book

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 interfaces—BytesMessage, TextMessage, StreamMessage, MapMessage, and ObjectMessage—which 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.

Message Header

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 sent—for 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 JMS–administered objects in detail in Chapter 6, "IBM JMS–Administered Objects."

Properties

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 message—for instance, the application is performing a brokering function and needs to modify the attributes of the message before forwarding it to the next destination—then the clearProperties() method is called on the message object.

Application-Specific Properties

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

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);
    

Provider-Specific Properties

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.

Message Selectors

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 SO—such as SO53 2NW and SO51 2JN—the 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.

Message Body

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 typed—for 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 adopted—XML, tagged/delimited, and record-oriented—readily 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 construct—string, serialized object, or byte array—in 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 clients—that 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020