When sending XML to JMS should I use TextMessage or BytesMessage

14,394

I agree with jos' comment to your question. First off, you should choose the kind of message type that best expresses the semantics of your content. Reading the TextMessage Javadoc, I'd go for that:

This message type can be used to transport text-based messages, including those with XML content.

So if you do run into trouble with your text message encoding, then there's probably some mis-configuration on the client / server side. But that shouldn't be a motivation for abusing a different message type that was not primarily intended for text transfer, such as BytesMessage.

N.B: Even with BytesMessage, you can get the encoding wrong. Imagine:

// Send that data through JMS
byte[] data1 = "source text".getBytes("ISO-8859-1");

// Receive the byte stream on the other side. Ooops
String data2 = new String(data1, "UTF-8");
Share:
14,394
Spence
Author by

Spence

Microelectronics Engineer with an IT Degree. Total masochist... Personally, I think that C# and .Net are wonderful additions to our world. Now if we could work out how to get all that power into a microcontroller :D

Updated on July 20, 2022

Comments

  • Spence
    Spence almost 2 years

    I have found some quite conflicting information on the web and I think that each different JMS provider may also alter the answer too.

    I'm trying to understand when sending XML into a JMS system (e.g. ActiveMQ) whether I should use a

    • BytesMessage : I can guarantee that the XML is serialized correctly and the preamble will match the actual encoding. Furthermore I can be sure that the client will be able to get the raw representation correctly.

    • TextMessage : There are APIs in many of the queue implementations for sending XML easily. I also understand that there are "encoding" information attached to the messages. But I risk encoding the message (and writing it's preamble) in one format and receiving it as another.

    Does anyone have a definitive answer, or at least some reasons why you would choose one over the other?

  • Spence
    Spence almost 12 years
    True, but the libraries I'm using in .Net will look for byte order marks given a stream of data and correctly identify the encoding. Plus my xml has the preamble. But what I'm hearing is that the jury is out.
  • PaulS
    PaulS over 4 years
    Interestingly (I'm working a similar type issue currently) - in Java 8, the code snippet works: data1= "[B@3d4eac69" and data2="source text", which is the original text.