001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.camel.builder; 018 019 import org.apache.camel.BinaryPredicate; 020 import org.apache.camel.Exchange; 021 import org.apache.camel.Expression; 022 import org.apache.camel.Predicate; 023 024 import static org.apache.camel.util.ObjectHelper.notNull; 025 026 /** 027 * A useful base class for {@link Predicate} implementations 028 * 029 * @version 030 */ 031 public abstract class BinaryPredicateSupport implements BinaryPredicate { 032 033 private final Expression left; 034 private final Expression right; 035 036 protected BinaryPredicateSupport(Expression left, Expression right) { 037 notNull(left, "left"); 038 notNull(right, "right"); 039 040 this.left = left; 041 this.right = right; 042 } 043 044 @Override 045 public String toString() { 046 return left + " " + getOperationText() + " " + right; 047 } 048 049 public boolean matches(Exchange exchange) { 050 return matchesReturningFailureMessage(exchange) == null; 051 } 052 053 public String matchesReturningFailureMessage(Exchange exchange) { 054 // we must not store any state, so we can be thread safe 055 // and thus we offer this method which returns a failure message if 056 // we did not match 057 String answer = null; 058 059 // must be thread safe and store result in local objects 060 Object leftValue = left.evaluate(exchange, Object.class); 061 Object rightValue = right.evaluate(exchange, Object.class); 062 if (!matches(exchange, leftValue, rightValue)) { 063 answer = leftValue + " " + getOperator() + " " + rightValue; 064 } 065 066 return answer; 067 } 068 069 protected abstract boolean matches(Exchange exchange, Object leftValue, Object rightValue); 070 071 protected abstract String getOperationText(); 072 073 public Expression getLeft() { 074 return left; 075 } 076 077 public Expression getRight() { 078 return right; 079 } 080 081 public String getOperator() { 082 return getOperationText(); 083 } 084 085 }