Apache camel getbody as custom class

2020-07-26 11:15发布

问题:

The question is rather simple, perhaps because I'm a little confused in the process. What I'm trying to do is shown in the code example:

cc.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("file://files?noop=true")
                    .split()
                    .tokenize("\n")
                    .split()
                    .method(SplitToken.class, "hashTokens")

and:

class SplitToken {
@SuppressWarnings("unchecked")
public static List<HashMap<String, Integer>> hashTokens(final Exchange exchange) {
    List<String> oldstr = exchange.getIn().getBody(List<String>);
    //Create a key value hashmap from accumulated string list
    }
}

but returns error:

expression required.

Any ideas about how we can achieve getbody with desired class in general? (Since the first split method returns a string list but I can't retrieve it in second split, or can I?)

回答1:

As far as I remember you cannot get generic list with getBody. This might work:

List<String> oldstr = (List<String>)exchange.getIn().getBody(List.class);

or even better you can make camel extract body for you with @Body annotation:

public static List<HashMap<String, Integer>> hashTokens(final Exchange exchange, @Body List<String> oldStr) {
    //Create a key value hashmap from accumulated string list
    return new ArrayList<>();
}


回答2:

Regarding your last question check out sub-section "Using POJOs as AggregationStrategy"/ "Different body types", from http://camel.apache.org/aggregator2.html

You could try sth like:

.pollEnrich("seda:foo", 1000, AggregationStrategies.beanAllowNull(MyUserAppender.class, "addUsers"))

public static final class MyUserAppender {

public List addUsers(List<String> names, User user) {
    if (names == null) {
        names = new ArrayList();
    }
    names.add(user.getName());
    return names;
}