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 ognl.Ognl;
020 import ognl.OgnlContext;
021 import ognl.OgnlException;
022 import org.apache.camel.Exchange;
023 import org.apache.camel.ExpressionEvaluationException;
024 import org.apache.camel.ExpressionIllegalSyntaxException;
025 import org.apache.camel.impl.ExpressionSupport;
026
027 /**
028 * An <a href="http://www.ognl.org/">OGNL</a> {@link Expression}
029 *
030 * @version $Revision: 15191 $
031 */
032 public class OgnlExpression extends ExpressionSupport {
033
034 private final String expressionString;
035 private final Class<?> type;
036 private Object expression;
037
038 public OgnlExpression(OgnlLanguage language, String expressionString, Class<?> type) {
039 this.expressionString = expressionString;
040 this.type = type;
041 try {
042 this.expression = Ognl.parseExpression(expressionString);
043 } catch (OgnlException e) {
044 throw new ExpressionIllegalSyntaxException(expressionString, e);
045 }
046 }
047
048 public static OgnlExpression ognl(String expression) {
049 return new OgnlExpression(new OgnlLanguage(), expression, Object.class);
050 }
051
052 public <T> T evaluate(Exchange exchange, Class<T> tClass) {
053 // TODO we could use caching here but then we'd have possible
054 // concurrency issues so lets assume that the provider caches
055 OgnlContext oglContext = new OgnlContext();
056 try {
057 Object value = Ognl.getValue(expression, oglContext, new RootObject(exchange));
058 return exchange.getContext().getTypeConverter().convertTo(tClass, value);
059 } catch (OgnlException e) {
060 throw new ExpressionEvaluationException(this, exchange, e);
061 }
062 }
063
064 protected String assertionFailureMessage(Exchange exchange) {
065 return expressionString;
066 }
067
068 @Override
069 public String toString() {
070 return "OGNL[" + expressionString + "]";
071 }
072 }