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.cel.ognl;
18  
19  import ognl.Ognl;
20  import ognl.OgnlException;
21  import org.springframework.util.Assert;
22  import org.springmodules.validation.util.condition.AbstractCondition;
23  import org.springmodules.validation.util.condition.Condition;
24  import org.springmodules.validation.util.lang.NestedIllegalArgumentException;
25  
26  /**
27   * A {@link Condition} that checks the given object based on a boolean OGNL expression.
28   *
29   * @author Uri Boness
30   */
31  public class OgnlCondition extends AbstractCondition {
32  
33      private String expression;
34  
35      private Object compiledExpression;
36  
37      /**
38       * Constructs a new OgnlCondition with given OGNL boolean expression.
39       *
40       * @param expression The given OGNL boolean expression.
41       */
42      public OgnlCondition(String expression) {
43          Assert.notNull(expression, "OGNL expression cannot be null");
44          this.expression = expression;
45          try {
46              compiledExpression = Ognl.parseExpression(expression);
47          } catch (OgnlException oe) {
48              throw new NestedIllegalArgumentException("Could not parse OGNL boolean expression '" + expression + "'", oe);
49          }
50      }
51  
52      /**
53       * @see AbstractCondition#doCheck(Object)
54       */
55      public boolean doCheck(Object object) {
56          try {
57              return ((Boolean) Ognl.getValue(compiledExpression, object, Boolean.class)).booleanValue();
58          } catch (OgnlException e) {
59              throw new IllegalArgumentException("Could not evaluate expression '" + expression +
60                  "' on given object '" + String.valueOf(object) + "'");
61          }
62      }
63  
64  }