KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > datatypes > BooleanDataType


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.datatypes;
11 import org.mmbase.bridge.*;
12 /**
13  * The DataType associated with a boolean value.
14  *
15  * @author Pierre van Rooden
16  * @version $Id: BooleanDataType.java,v 1.10 2006/07/17 07:19:15 pierre Exp $
17  * @since MMBase-1.8
18  */

19 public class BooleanDataType extends BasicDataType {
20
21     private static final long serialVersionUID = 1L; // increase this if object serialization changes (which we shouldn't do!)
22

23     /**
24      * Constructor for a boolean datatype (either a primitive boolean type or the Boolean class).
25      *
26      * @param name the name of the data type
27      * @param primitive indicate if a primitive type should be used
28      */

29     public BooleanDataType(String JavaDoc name, boolean primitive) {
30         super(name, primitive ? Boolean.TYPE : Boolean JavaDoc.class);
31     }
32
33     /**
34      * Cast a bit more conservatively, because Casting aggressively casts everything to boolean,
35      * which would make nearly every value valid.
36      */

37     protected final Object JavaDoc cast(Object JavaDoc value, Cloud cloud, Node node, Field field) throws CastException {
38         Object JavaDoc preCast = preCast(value, cloud, node, field);
39         if (preCast == null) return null;
40         if (value instanceof Boolean JavaDoc) return value;
41         if (value instanceof String JavaDoc) {
42             String JavaDoc s = ((String JavaDoc)value).toLowerCase();
43             if ("".equals(value)) return null;
44             if ("true".equals(s)) return Boolean.TRUE;
45             if ("false".equals(s)) return Boolean.FALSE;
46             if ("1".equals(s)) return Boolean.TRUE;
47             if ("0".equals(s)) return Boolean.FALSE;
48             throw new CastException("'" + value + "' of type " + value.getClass().getName() + " cannot be cast to boolean");
49         }
50         if (value instanceof Number JavaDoc) {
51             double d = ((Number JavaDoc) value).doubleValue();
52             if (d == 1.0) return Boolean.TRUE;
53             if (d == 0.0) return Boolean.FALSE;
54             throw new CastException("The number '" + value + "' cannot be cast to boolean (boolean is 0 or 1)");
55         }
56         throw new CastException("'" + value + "' cannot be cast to boolean (boolean is 0 or 1)");
57
58     }
59 }
60
Popular Tags