1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.dbunit.dataset.datatype;
22
23 import java.sql.PreparedStatement;
24 import java.sql.ResultSet;
25 import java.sql.SQLException;
26 import java.sql.Types;
27
28 import org.dbunit.dataset.ITable;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32
33
34
35
36
37 public class BooleanDataType extends AbstractDataType
38 {
39 private static final Logger logger =
40 LoggerFactory.getLogger(BooleanDataType.class);
41
42 BooleanDataType()
43 {
44 this("BOOLEAN", Types.BOOLEAN);
45 }
46
47
48
49
50 BooleanDataType(final String name, final int sqlType)
51 {
52 super(name, sqlType, Boolean.class, false);
53 }
54
55
56
57
58 @Override
59 public Object typeCast(final Object value) throws TypeCastException
60 {
61 logger.debug("typeCast(value={}) - start", value);
62
63 if (value == null || value == ITable.NO_VALUE)
64 {
65 return null;
66 }
67
68 if (value instanceof Boolean)
69 {
70 return value;
71 }
72
73 if (value instanceof Number)
74 {
75 final Number number = (Number) value;
76 if (number.intValue() == 0)
77 {
78 return Boolean.FALSE;
79 } else
80 {
81 return Boolean.TRUE;
82 }
83 }
84
85 if (value instanceof String)
86 {
87 final String string = (String) value;
88
89 if ("true".equalsIgnoreCase(string)
90 || "false".equalsIgnoreCase(string))
91 {
92 return Boolean.valueOf(string);
93 } else
94 {
95 return typeCast(DataType.INTEGER.typeCast(string));
96 }
97 }
98
99 throw new TypeCastException(value, this);
100 }
101
102 @Override
103 protected int compareNonNulls(final Object value1, final Object value2)
104 throws TypeCastException
105 {
106 logger.debug("compareNonNulls(value1={}, value2={}) - start", value1,
107 value2);
108
109 final Boolean value1bool = (Boolean) value1;
110 final Boolean value2bool = (Boolean) value2;
111
112 if (value1bool.equals(value2bool))
113 {
114 return 0;
115 }
116
117 if (!value1bool)
118 {
119 return -1;
120 }
121
122 return 1;
123 }
124
125 @Override
126 public Object getSqlValue(final int column, final ResultSet resultSet)
127 throws SQLException, TypeCastException
128 {
129 logger.debug("getSqlValue(column={}, resultSet={}) - start", column,
130 resultSet);
131 final boolean rawValue = resultSet.getBoolean(column);
132 final Boolean value = resultSet.wasNull() ? null : rawValue;
133 logger.debug("getSqlValue: column={}, value={}", column, value);
134 return value;
135 }
136
137 @Override
138 public void setSqlValue(final Object value, final int column,
139 final PreparedStatement statement)
140 throws SQLException, TypeCastException
141 {
142 logger.debug("setSqlValue(value={}, column={}, statement={}) - start",
143 value, column, statement);
144
145 final Boolean castValue = (Boolean) typeCast(value);
146 if (castValue == null)
147 {
148 statement.setNull(column, Types.BOOLEAN);
149 } else
150 {
151 statement.setBoolean(column, castValue);
152 }
153 }
154 }