Reputation: 4513
Is there a construct in Apache Camel (in Java DSL) similar to Java switch-case?
For example:
from( incomingRoute )
.choice()
.when( simple( "${body.getType} == '" + TYPE.A.name() + "'" ) )
.to( A_Endpoint )
.when( simple( "${body.getType} == '" + TYPE.B.name() + "'" ) )
.to( B_Endpoint )
.when( simple( "${body.getType} == '" + TYPE.C.name() + "'" ) )
.to( C_Endpoint )
.otherwise()
.to( errorEndpoint );
Can be translated into something else more similar to switch? I mean that I do not want to use simple predicates, only value of type of body element. Or is my approach completely wrong? (That could reasonably be)
Upvotes: 4
Views: 4790
Reputation: 5369
I generally prefer using Java 8 lambdas in that particular scenario:
public void configure() throws Exception {
from( incomingRoute )
.choice()
.when( bodyTypeIs( TYPE.A ) )
.to( A_Endpoint )
.when( bodyTypeIs( TYPE.B ) )
.to( B_Endpoint )
.when( bodyTypeIs( TYPE.C ) )
.to( C_Endpoint )
.otherwise()
.to( errorEndpoint );
}
private Predicate bodyTypeIs(TYPE type) {
return e -> e.getIn().getBody(BodyType.class).getType() == type;
}
Also, using Camel's Predicate
s with Java 8 allows for some awesome fluent API building, like adding your own type of functional Predicate
:
@FunctionalInterface
public interface ComposablePredicate extends Predicate, java.util.function.Predicate<Exchange> {
@Override
default boolean matches(Exchange exchange) {
return test(exchange);
}
@Override
default ComposablePredicate and(java.util.function.Predicate<? super Exchange> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
@Override
default ComposablePredicate negate() {
return (t) -> !test(t);
}
@Override
default ComposablePredicate or(java.util.function.Predicate<? super Exchange> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
}
Which allows you to write stuff like:
public void configure() throws Exception {
from( incomingRoute )
.choice()
.when( bodyTypeIs( TYPE.A ) .or ( bodyTypeIs( TYPE.A1 ) ) )
.to( A_Endpoint )
.when( bodyTypeIs( TYPE.B ).negate() )
.to( NOT_B_Endpoint )
.when( bodyTypeIs( TYPE.C ) .and ( bodyNameIs( "name" ) ) )
.to( C_Endpoint )
.otherwise()
.to( errorEndpoint );
}
private ComposablePredicate bodyTypeIs(TYPE type) {
return e -> bodyFrom(e).getType() == type;
}
private BodyType bodyFrom(Exchange e) {
return e.getIn().getBody(BodyType.class);
}
private ComposablePredicate bodyNameIs(String name) {
return e -> bodyFrom(e).getName().equals(name);
}
Upvotes: 5