View Javadoc

1   /*
2    * Copyright 2004-2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springmodules.validation.util.fel.parser;
18  
19  import ognl.Ognl;
20  import ognl.OgnlException;
21  import org.springmodules.validation.util.fel.FelEvaluationException;
22  import org.springmodules.validation.util.fel.FelParseException;
23  import org.springmodules.validation.util.fel.Function;
24  import org.springmodules.validation.util.fel.FunctionExpressionParser;
25  
26  /**
27   * A {@link FunctionExpressionParser} implementation that knows how to parse OGNL expressions and
28   * return the appropriate function.
29   *
30   * @author Uri Boness
31   */
32  public class OgnlFunctionExpressionParser implements FunctionExpressionParser {
33  
34      public Function parse(String expression) {
35          return new OgnlFunction(expression);
36      }
37  
38      /**
39       * A function that is associated with an OGNL expression and evaluates this expression on
40       * the given object.
41       */
42      protected class OgnlFunction implements Function {
43  
44          private String expressionAsString;
45  
46          private Object ognlExpression;
47  
48          public OgnlFunction(String expressionAsString) {
49              this.expressionAsString = expressionAsString;
50              try {
51                  this.ognlExpression = Ognl.parseExpression(expressionAsString);
52              } catch (OgnlException oe) {
53                  throw new FelParseException("Could not parse OGNL expression '" + expressionAsString + "'", oe);
54              }
55          }
56  
57          public Object evaluate(Object argument) {
58              try {
59                  return Ognl.getValue(ognlExpression, argument);
60              } catch (OgnlException oe) {
61                  throw new FelEvaluationException("Could not evaluate OGNL expression '" + expressionAsString +
62                      "' on argument '" + String.valueOf(argument), oe);
63              }
64          }
65      }
66  
67  }