Apache Camel:在when()中使用复合条件



我正在使用Apache Camel DSL路由,并想检查主体是否不是null和主体不包含子字符串,如authenticate failed。在java中像这样:

if(body != null && !body.contains("authenticate failed")) {
//Do something.

}

Apache Camel DSL:

.choice()
.when(body().contains("authenticate failed"))
.log("after choice body().contains('authenticate failed') body: ${body}")
.when(body().isNotNull()) //Here I want to add the addiontional condition to this when `body not contains authenticate failed`. 

我怎么能写出这样一个条件呢?谓词对象的过程方法和写在我的情况下?

您可以使用PredicateBuilder创建漂亮的复合谓词。下面是如何使用PredicateBuilder进行简单的Body is not null或empty检查的示例。

package com.example;
import org.apache.camel.Predicate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.PredicateBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class ExampleTests extends CamelTestSupport {

@Test
public void testValidBody() throws Exception {
MockEndpoint resultMockEndpoint = getMockEndpoint("mock:notNull");
resultMockEndpoint.expectedMessageCount(1);
template.sendBody("direct:predicateExample", "Hello world!");
resultMockEndpoint.assertIsSatisfied();
}
@Test
public void testEmptyBody() throws Exception {

MockEndpoint resultMockEndpoint = getMockEndpoint("mock:nullOrEmpty");
resultMockEndpoint.expectedMessageCount(1);
template.sendBody("direct:predicateExample", null);
resultMockEndpoint.assertIsSatisfied();
}
@Test
public void testNullBody() throws Exception {
MockEndpoint resultMockEndpoint = getMockEndpoint("mock:nullOrEmpty");
resultMockEndpoint.expectedMessageCount(1);
template.sendBody("direct:predicateExample", null);
resultMockEndpoint.assertIsSatisfied();
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {

Predicate bodyNotNullOrEmpty = PredicateBuilder.and(
body().isNotNull(), 
body().isNotEqualTo("")
);
from("direct:predicateExample")
.routeId("predicateExample")
.choice().when(bodyNotNullOrEmpty)
.log("Received body: ${body}")
.to("mock:notNull")
.otherwise()
.log("Body was null or empty!")
.to("mock:nullOrEmpty")
.end()
.log("done");
}
};
}
}

Not和Or可以将谓词列表作为参数,甚至可以将其他组合谓词作为参数,从而允许创建一些相当复杂的组合谓词。然而,当使用PredicateBuilder开始变得过于冗长时,最好使用processor或bean来抽象一些复杂性。

最新更新