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 */ 017package org.apache.camel.util; 018 019import org.apache.camel.CamelContext; 020import org.apache.camel.CamelContextAware; 021import org.apache.camel.Exchange; 022import org.apache.camel.Expression; 023import org.apache.camel.Predicate; 024 025/** 026 * To adapt {@link org.apache.camel.Expression} as a {@link Predicate} 027 */ 028public final class ExpressionToPredicateAdapter implements Predicate, CamelContextAware { 029 private final Expression expression; 030 031 public ExpressionToPredicateAdapter(Expression expression) { 032 this.expression = expression; 033 } 034 035 public boolean matches(Exchange exchange) { 036 if (expression instanceof Predicate) { 037 return ((Predicate) expression).matches(exchange); 038 } else { 039 Object value = expression.evaluate(exchange, Object.class); 040 return ObjectHelper.evaluateValuePredicate(value); 041 } 042 } 043 044 @Override 045 public String toString() { 046 return expression.toString(); 047 } 048 049 /** 050 * Converts the given expression into an {@link Predicate} 051 */ 052 public static Predicate toPredicate(final Expression expression) { 053 return new ExpressionToPredicateAdapter(expression); 054 } 055 056 @Override 057 public void setCamelContext(CamelContext camelContext) { 058 if (expression instanceof CamelContextAware) { 059 ((CamelContextAware) expression).setCamelContext(camelContext); 060 } 061 } 062 063 @Override 064 public CamelContext getCamelContext() { 065 if (expression instanceof CamelContextAware) { 066 return ((CamelContextAware) expression).getCamelContext(); 067 } else { 068 return null; 069 } 070 } 071}