Accessing the body of a split entrySet in Apache Camel

JMoore :

The body of my message contains a HashMap.

I split this message by its entrySet:

.from(FROM)
   .aggregate(...)

   // create an iterable
   .transform(simple("${in.body.entrySet()}"))

   // split over the Iterable
   .split(body())
      .process(new ReadMapEntry())
      .to(TO)
   .end()
.end();

Now trying to retrieve these entries in the processor. Closest I got was trying to cast this. I've found similar examples using ArrayList, but I can't get them to work for this... in this sort of works, but it triggered an unchecked cast warning due to the generics of Map.Entry.

public void process(final Exchange ex) throws Exception
{     
   Map.Entry<A, B> entry = (Map.Entry<A, B>) ex.getIn().getBody(Map.Entry.class);
   (...)
}

Solution

My objective here was to avoid the warning associated with casting over an inherited class. I ended up making use of the simple keyword in the end. This way I could pass the map's value into the processor (thus avoiding the unchecked cast warning) and accessing the key through a header.

.from(FROM)
   .aggregate(...)

   .split(simple("${in.body.entrySet}"))
      .setHeader(KEY_VALUE_AS_HEADER, simple("${body.getKey}"))
      .setBody(simple("${body.getValue}"))
      .process(new ReadMapEntry())
      .to(TO)
   .end()
.end();
public void process(final Exchange ex) throws Exception
{     
   A value = ex.getIn().getBody(A.class);
   B key = ex.getIn().getHeader(KEY_VALUE_AS_HEADER, B.class);
   (...)
}
burki :

You could try to use a simple Bean and directly inject the Body with the correct type.

// simple POJO, does not implement Processor interface
public void readMap(@Body Map.Entry<A, B> mapEntry) {     
     // use mapEntry (message body) directly instead of extracting it from Exchange
     mapEntry.[whatever]
}

Then you call it in your route

.method(new ReadMapEntryBean()) // if Bean contains only 1 method

or

.method(new ReadMapEntryBean(), "readMap") // if there are other methods

The processor interface is quite old, clumsy and hard to test. POJOs are much easier to use and they work very well with Camel.

See Parameter Binding Annotations and Bean Integration from the Camel Docs for more details

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=417210&siteId=1