关于问题:Apache camel returns multiple exceptions during a route
它表示我无法使用split方法获取字符串列表,所以我尝试了如下聚合方法:
public class lowestRates implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
String oldStr = oldExchange.getIn().getBody(String.class);
String newStr = newExchange.getIn().getBody(String.class);
Pattern p = Pattern.compile("(\\w+)\\s(\\d+)");
Matcher m1 = p.matcher(oldStr);
Matcher m2 = p.matcher(newStr);
String finalStr = "";
if(m1.group(2).equalsIgnoreCase(m2.group(2)))
finalStr = m1.group(1) + Integer.toString(Integer.parseInt(m1.group(2)) > Integer.parseInt(m2.group(2)) ? Integer.parseInt(m2.group(2)) : Integer.parseInt(m1.group(2)));
else
finalStr = oldStr + "\n" + newStr;
oldExchange.getIn().setBody(finalStr);
return oldExchange;
}
}
和新的主要代码:
from("file://files")
.split()
.tokenize("\n")
.aggregate(new lowestRates())
.body()
.completionTimeout(5000)
.to("file://files/result.txt")
但它给了我:
org.apache.camel.CamelExchangeException: Error occurred during aggregation. Exchange[][Message: Good1 450]. Caused by: [java.lang.NullPointerException - null]
现在的问题是如何编写正确的聚合方法,因为我在这里看不到任何错误:(。
答案 0 :(得分:1)
String oldStr = oldExchange.getIn().getBody(String.class);
String newStr = newExchange.getIn().getBody(String.class);
你需要在这里检查字符串是否为空.. 对于第一条消息,oldStr将为null。 恕我直言,你收到异常,然后尝试解析空字符串。 是的,请检查交换空值
if (oldExchange == null) {
return newExchange;
}
更新: 试试这样:
public class lowestRates implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
if (newExchange.getIn().getBody()!=null){
Pattern p = Pattern.compile("(\\w+)\\s(\\d+)");
String finalStr = "";
String oldStr = oldExchange.getIn().getBody(String.class);
String newStr = newExchange.getIn().getBody(String.class);
if (oldStr!=null&&newStr!=null){
Matcher m1 = p.matcher(oldStr);
Matcher m2 = p.matcher(newStr);
if(m1.group(2).equalsIgnoreCase(m2.group(2)))
finalStr = m1.group(1) + Integer.toString(Integer.parseInt(m1.group(2)) > Integer.parseInt(m2.group(2)) ? Integer.parseInt(m2.group(2)) : Integer.parseInt(m1.group(2)));
else
finalStr = oldStr + "\n" + newStr;
}
oldExchange.getIn().setBody(finalStr);
}
return oldExchange;
}
}
您还需要按如下方式修改聚合,
自:
Aggregate(new strategy()).body() //This is where things go wrong
要:
Aggregate(constant(true), new strategy()).completionFromBatchConsumer()