Spring cloud stream Message Type Conversion Issue

as63010
as63010 Member Posts: 14

Hi Team,

We get the type casting issue when spring cloud stream reply the message to non spring cloud stream service.

com.solacesystems.jcsmp.impl.BytesMessageImpl cannot be cast to com.solacesystems.jcsmp.TextMessage"

Code:

Below is the code used in the non spring cloud stream service which is type casting to text message which sent by spring cloud stream service.

textMessage.setText(((TextMessage)replyMessage).getText());

Do we need to type cast to BytesMessage and use getData API and convert to String?

Comments

  • Aaron
    Aaron Member, Administrator, Moderator, Employee Posts: 644 admin
    edited September 2021 #2

    HI @as63010 ..! Yeah, that's exactly right. The Spring Cloud Stream binder supports all of the standard formats of a Solace message (bytes, text, map, stream), and so your receiving app should do some checks:

    if (message instanceof TextMessage) {
      String payload = ((TextMessage)message).getText();
      // work with that
    } else if (message instanceof BytesMessage) {
      byte[] payload = ((BytesMessage)messsage).getData();
      // work with bytes.
      // if you know it's a UTF-8 string, you can do something else like:
      //   String payload = new String(((BytesMessage)messsage).getData(),Charset.forName("UTF-8"));
    } else ... 
    

    And a tip, because lots of people hit this problem: don't use getBytes() as that is a legacy leftover method for retrieving the XML Content portion of the message, which is disused. BytesMessage is getData(). Weird, I know.