50.2. Implementing the Message Interface
How to implement a custom message
Example 50.2, “Custom Message Implementation” outlines how to implement a message by extending the
DefaultMessage
class.
Example 50.2. Custom Message Implementation
import org.apache.camel.Exchange; import org.apache.camel.impl.DefaultMessage; public class CustomMessage extends DefaultMessage { 1 public CustomMessage() { 2 // Create message with default properties... } @Override public String toString() { 3 // Return a stringified message... } @Override public CustomMessage newInstance() { 4 return new CustomMessage( ... ); } @Override protected Object createBody() { 5 // Return message body (lazy creation). } @Override protected void populateInitialHeaders(Map<String, Object> map) { 6 // Initialize headers from underlying message (lazy creation). } @Override protected void populateInitialAttachments(Map<String, DataHandler> map) { 7 // Initialize attachments from underlying message (lazy creation). } }
- 1
- Implements a custom message class, CustomMessage, by extending the
org.apache.camel.impl.DefaultMessage
class. - 2
- Typically, you need a default constructor that creates a message with default properties.
- 3
- Override the
toString()
method to customize message stringification. - 4
- The
newInstance()
method is called from inside theMessageSupport.copy()
method. Customization of thenewInstance()
method should focus on copying all of the custom properties of the current message instance into the new message instance. TheMessageSupport.copy()
method copies the generic message properties by callingcopyFrom()
. - 5
- The
createBody()
method works in conjunction with theMessageSupport.getBody()
method to implement lazy access to the message body. By default, the message body isnull
. It is only when the application code tries to access the body (by callinggetBody()
), that the body should be created. TheMessageSupport.getBody()
automatically callscreateBody()
, when the message body is accessed for the first time. - 6
- The
populateInitialHeaders()
method works in conjunction with the header getter and setter methods to implement lazy access to the message headers. This method parses the message to extract any message headers and inserts them into the hash map,map
. ThepopulateInitialHeaders()
method is automatically called when a user attempts to access a header (or headers) for the first time (by callinggetHeader()
,getHeaders()
,setHeader()
, orsetHeaders()
). - 7
- The
populateInitialAttachments()
method works in conjunction with the attachment getter and setter methods to implement lazy access to the attachments. This method extracts the message attachments and inserts them into the hash map,map
. ThepopulateInitialAttachments()
method is automatically called when a user attempts to access an attachment (or attachments) for the first time by callinggetAttachment()
,getAttachments()
,getAttachmentNames()
, oraddAttachment()
.