View Javadoc

1   /*
2   Copyright (C) 2004 Grid Systems, S.A.
3   
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License, version 2, as
6   published by the Free Software Foundation.
7   
8   This program is distributed in the hope that it will be useful,
9   but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12  
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  */
17  package com.gridsystems.beanfilter;
18  
19  import java.util.Collection;
20  
21  /**
22   * Node that evaluates its internal node as if it is a boolean value.
23   * <p>
24   * This node allows the use of boolean fields in the expression, like:
25   * <p>
26   * <code>(field = True)  ---&gt;   (field)</code>
27   * <p>
28   * The evaluation result depends on the internal node value type:
29   * <ul>
30   *   <li>BOOLEAN: (value = True)
31   *   <li>NUMBER: (value <> 0)
32   *   <li>STRING: (value <> '')
33   *   <li>COLLECTION: (value not empty)
34   * </ul>
35   *
36   * @author Rodrigo Ruiz
37   * @version 1.0
38   */
39  public class BooleanNode extends EvalNode {
40    /**
41     * The value to evaluate as a boolean.
42     */
43    private EvalValue value;
44  
45    /**
46     * Creates a new instance.
47     *
48     * @param value  The value to evaluate as a boolean
49     */
50    public BooleanNode(EvalValue value) {
51      super(value.getLinePos(), value.getCharPos());
52      this.value = value;
53    }
54  
55    /**
56     * {@inheritDoc}
57     */
58    @Override public boolean eval(Object src) throws EvalException {
59      Object val = value.getValue(src);
60      if (val instanceof Boolean) {
61        return ((Boolean)val).booleanValue();
62      } else if (val instanceof Number) {
63        return ((Number)val).doubleValue() != 0.0;
64      } else if (val instanceof Collection) {
65        return ((Collection<?>)val).size() != 0;
66      } else if (val instanceof String) {
67        return ((String)val).length() != 0;
68      } else {
69        return false;
70      }
71    }
72  
73    /**
74     * {@inheritDoc}
75     */
76    @Override public String toString() {
77      return value.toString();
78    }
79  }