Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JMS BytesMessage to String in java and use the same bytesmessage in another process

Tags:

java

string

jms

My code is listening to an IBM MQ. Receives JMS BytesMessage, converts it to string in the receiver class and pass on the same JMS BytesMessage to another processor class. Processor class again converts it into String. Both receiver class and processor class use the same code like below to get the string from BytesMessage. I am getting the right string in the Receiver class but when trying to get the string from the BytesMessage in Processor class its returning empty string. Please advise what has to be done in addition to preserve the JMS BytesMessage so that it gets converted to String in the Processor class as well.

Code that sends message to processor:

String strMessage = null;
strMessage = getStringFromMessage(Message message)
process(message)

Code used for String Conversion:

if (message instanceof BytesMessage){
 BytesMessage byteMessage = (BytesMessage) message;
 byte[] byteData = null;
 byteData = new byte[(int) byteMessage.getBodyLength()];
 byteMessage.readBytes(byteData);
 stringMessage =  new String(byteData);
}
like image 912
Shankar Anand Avatar asked Oct 27 '25 18:10

Shankar Anand


1 Answers

I found the solution. I added the below code after reading the message for the first time

byteMessage.reset()

This has reset the cursor position to the beginning and hence i am able to read it in the processor. So my final code in the receiver will look like below

if (message instanceof BytesMessage){
BytesMessage byteMessage = (BytesMessage) message;
byte[] byteData = null;
byteData = new byte[(int) byteMessage.getBodyLength()];
byteMessage.readBytes(byteData);
byteMessage.reset();
stringMessage =  new String(byteData);
}

The reason to read it again is the i started reading it in the receiver to perform some recovery functionality. I wanted to implement that without touching the framework. Initial framework is to read the message only in the processor.

like image 50
Shankar Anand Avatar answered Oct 30 '25 07:10

Shankar Anand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!