Custom Transformers
Now that we have seen out-of-the-box transformers, it is time to see how we can create our own Transformers should the need arise.
Let us look at an example of a TradePublisher that will produce
Trade messages with a Trade POJO as a payload. In the example, the
consumer is not interested in receiving a Java Object but is expecting a
name-value paired map. Can we tweak the TradePublisher to produce the Trade data compatible with
that of a receiver? Yes, we can, but what if we have another receiver that
may come up a few weeks later and be interested in consuming XML-formatted
Trade messages?
Ideally, the producers should be unaware of consumers or their
requirements. They only talk via an intermediary called
message. This enables the applications to be decoupled,
too. Our TradePublisher produces the
Trades in a universal format—a POJO.
Before the message hits the receiver, a transformer needs to be plugged in.
Trade Map Transformer
Because the receiver is expecting name-value pairs of the Trade
data, we need to transform the message into the expected format before
sending to the consumer. One way to do this is to create a class that
transforms the POJO to a name-value pair. The TradeMapTransformer class defined below
satisfies this requirement:
public class TradeMapTransformer { public Map<String, String> transform(Trade t) { Map<String,String> tradeNameValuesMap = new HashMap<String,String>(); tradeNameValuesMap.put("TRADE_ID", t.getId()); tradeNameValuesMap.put("TRADE_ACCOUNT", ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access