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 org.springframework.beans.BeanWrapperImpl;
20  import org.springmodules.validation.util.fel.FelEvaluationException;
21  import org.springmodules.validation.util.fel.Function;
22  import org.springmodules.validation.util.fel.FunctionExpressionParser;
23  
24  /**
25   * A {@link FunctionExpressionParser} implementation that knows how to parse BeanWrapper-like property paths and
26   * returns a function that extracts the appropriate property value from the given object (bean).
27   *
28   * @author Uri Boness
29   */
30  public class PropertyPathFunctionExpressionParser implements FunctionExpressionParser {
31  
32      public Function parse(String expression) {
33          return new PropertyPathFunction(expression);
34      }
35  
36      /**
37       * A function that is associated with a property path. On evaluation, the appropriate property value is
38       * extracted from the given object (bean).
39       */
40      protected class PropertyPathFunction implements Function {
41  
42          private String propertyPath;
43  
44          public PropertyPathFunction(String propertyPath) {
45              this.propertyPath = propertyPath;
46          }
47  
48          public Object evaluate(Object argument) {
49              try {
50                  return new BeanWrapperImpl(argument).getPropertyValue(propertyPath);
51              } catch (Throwable t) {
52                  throw new FelEvaluationException("Could not evaluate path '" + propertyPath +
53                      "' on bean '" + String.valueOf(argument) + "'", t);
54              }
55          }
56      }
57  
58  }