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.language.ognl; 018 019 import java.util.HashMap; 020 import java.util.Map; 021 022 import ognl.Ognl; 023 import ognl.OgnlContext; 024 import ognl.OgnlException; 025 026 import org.apache.camel.Exchange; 027 import org.apache.camel.impl.ExpressionSupport; 028 import org.apache.camel.language.ExpressionEvaluationException; 029 import org.apache.camel.language.IllegalSyntaxException; 030 031 /** 032 * @version $Revision: $ 033 */ 034 public class OgnlExpression extends ExpressionSupport<Exchange> { 035 036 private final String expressionString; 037 private final Class<?> type; 038 private Object expression; 039 040 public OgnlExpression(OgnlLanguage language, String expressionString, Class<?> type) { 041 this.expressionString = expressionString; 042 this.type = type; 043 try { 044 this.expression = Ognl.parseExpression(expressionString); 045 } catch (OgnlException e) { 046 throw new IllegalSyntaxException(language, expressionString); 047 } 048 } 049 050 public static OgnlExpression ognl(String expression) { 051 return new OgnlExpression(new OgnlLanguage(), expression, Object.class); 052 } 053 054 public Object evaluate(Exchange exchange) { 055 // TODO we could use caching here but then we'd have possible 056 // concurrency issues 057 // so lets assume that the provider caches 058 Map values = new HashMap(); 059 populateContext(values, exchange); 060 OgnlContext oglContext = new OgnlContext(); 061 try { 062 return Ognl.getValue(expression, oglContext, new RootObject(exchange)); 063 } catch (OgnlException e) { 064 throw new ExpressionEvaluationException(this, exchange, e); 065 } 066 } 067 068 protected void populateContext(Map map, Exchange exchange) { 069 map.put("exchange", exchange); 070 map.put("in", exchange.getIn()); 071 map.put("out", exchange.getOut()); 072 } 073 074 protected String assertionFailureMessage(Exchange exchange) { 075 return expressionString; 076 } 077 }