Messsage exchange patterns and the Exchange objectThe Camel API is influenced by APIs such as JBI specification, CXF which defines a concept called Message Exchange Patterns (MEP for short). The MEP defines the messaging style used such as one-way (InOnly) or request-reply (InOut), The Exchange API provides two methods to get a message, either getIn or getOut. Flow of an exchange through a route
Using getIn or getOut methods on ExchangeNow suppose you want to use a Camel Processor to adjust a message. This can be done as follows: public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); // change the message to say Hello exchange.getOut().setBody("Hello " + body); } This seems intuitive and is what you would expect is the right approach to change a message from a Processor. public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); // change the message to say Hello exchange.getOut().setBody("Hello " + body); // copy headers from IN to OUT to propagate them exchange.getOut().setHeaders(exchange.getIn().getHeaders()); } Well that is not all, a Message can also contain attachments so to be sure you need to propagate those as well: public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); // change the message to say Hello exchange.getOut().setBody("Hello " + body); // copy headers from IN to OUT to propagate them exchange.getOut().setHeaders(exchange.getIn().getHeaders(); // copy attachements from IN to OUT to propagate them exchange.getOut().setAttachments(exchange.getIn().getAttachments()); } Now we ensure that all additional data is propagated on the new OUT message. But its a shame we need 2 code lines to ensure data is propagated. public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); // change the existing message to say Hello exchange.getIn().setBody("Hello " + body); }
Changing the IN message directly is possible in Camel as it don't mind. Camel will detect that the Exchange has no OUT message About Message Exchange Pattern and getOutIf the Exchange is using InOnly as the MEP, then you may think that the Exchange has no OUT message. So the example code above is possible for any kind of MEP. The MEP is just a flag on the Exchange which the Consumer and Producer adhere to. |