01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10: package org.mmbase.datatypes;
11:
12: import org.mmbase.bridge.*;
13:
14: /**
15: * The DataType associated with a boolean value.
16: *
17: * @author Pierre van Rooden
18: * @version $Id: BooleanDataType.java,v 1.13 2007/08/28 10:06:05 michiel Exp $
19: * @since MMBase-1.8
20: */
21: public class BooleanDataType extends BasicDataType<Boolean> {
22:
23: private static final long serialVersionUID = 1L; // increase this if object serialization changes (which we shouldn't do!)
24:
25: /**
26: * Constructor for a boolean datatype (either a primitive boolean type or the Boolean class).
27: *
28: * @param name the name of the data type
29: * @param primitive indicate if a primitive type should be used
30: */
31: public BooleanDataType(String name, boolean primitive) {
32: super (name, primitive ? Boolean.TYPE : Boolean.class);
33: }
34:
35: protected <D> D preCast(D value, Cloud cloud, Node node, Field field) {
36: if (value == null)
37: return null;
38: if (value instanceof String) {
39: if ("".equals(value))
40: return null;
41: if ("-1".equals(value))
42: return null;
43: } else if (value instanceof Number) {
44: double d = ((Number) value).doubleValue();
45: if (d == -1.0)
46: return null;
47: }
48: return super .preCast(value, cloud, node, field);
49: }
50:
51: /**
52: * Cast a bit more conservatively, because Casting aggressively casts everything to boolean,
53: * which would make nearly every value valid.
54: */
55: protected final Boolean cast(Object value, Cloud cloud, Node node,
56: Field field) throws CastException {
57: Object preCast = preCast(value, cloud, node, field);
58: if (preCast == null)
59: return null;
60: if (value instanceof Boolean)
61: return (Boolean) value;
62: if (value instanceof String) {
63: String s = ((String) value).toLowerCase();
64: if ("".equals(value))
65: return null;
66: if ("true".equals(s))
67: return Boolean.TRUE;
68: if ("false".equals(s))
69: return Boolean.FALSE;
70: if ("1".equals(s))
71: return Boolean.TRUE;
72: if ("0".equals(s))
73: return Boolean.FALSE;
74: throw new CastException("'" + value + "' of type "
75: + value.getClass().getName()
76: + " cannot be cast to boolean");
77: }
78: if (value instanceof Number) {
79: double d = ((Number) value).doubleValue();
80: if (d == 1.0)
81: return Boolean.TRUE;
82: if (d == 0.0)
83: return Boolean.FALSE;
84: throw new CastException("The number '" + value
85: + "' cannot be cast to boolean (boolean is 0 or 1)");
86: }
87: throw new CastException("'" + value
88: + "' cannot be cast to boolean (boolean is 0 or 1)");
89: }
90: }
|