2016-01-05 143 views
-1

關於這個問題:Apache camel returns multiple exceptions during a route阿帕奇駱駝總給人例外

其表示,這就是我一直聚合方法如下我不能與分裂法的字符串列表:

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

'String oldStr = oldExchange.getIn()。getBody(String.class);'oldStr對於第一條消息將爲null。 –

+0

你是指串還是交換?你也可以提出一個解決辦法嗎? – lkn2993

+0

請看我的例子。我認爲你可以做得更好:) –

回答

1
String oldStr = oldExchange.getIn().getBody(String.class); 
String newStr = newExchange.getIn().getBody(String.class); 

這裏需要檢查空字符串.. oldStr將是空的第一個消息。 恕我直言,你會收到異常,然後試圖解析空字符串。 是的,對於空

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() 
+0

不幸的是,它的錯誤答案,因爲聚合或拆分方法有問題,oldexchange總是空。 – lkn2993

+0

實際上,新答案是正確的,如果評論導致誤解,不好意思。 – lkn2993