1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.dbunit.ext.postgresql;
22
23 import java.lang.reflect.Constructor;
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 import java.sql.Connection;
27 import java.sql.PreparedStatement;
28 import java.sql.ResultSet;
29 import java.sql.SQLException;
30 import java.sql.Types;
31
32 import org.dbunit.dataset.datatype.AbstractDataType;
33 import org.dbunit.dataset.datatype.TypeCastException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37
38
39
40
41
42
43
44
45
46
47 public class GenericEnumType extends AbstractDataType {
48
49
50
51
52 private static final Logger logger = LoggerFactory.getLogger(GenericEnumType.class);
53
54 private final String sqlTypeName;
55
56
57
58
59
60 public GenericEnumType(String sqlTypeName)
61 {
62 super(sqlTypeName, Types.OTHER, String.class, false);
63
64 if (sqlTypeName == null) {
65 throw new NullPointerException(
66 "The parameter 'sqlTypeName' must not be null");
67 }
68 this.sqlTypeName = sqlTypeName;
69 }
70
71 public Object getSqlValue(int column, ResultSet resultSet) throws SQLException, TypeCastException
72 {
73 return resultSet.getString(column);
74 }
75
76 public void setSqlValue(Object enumObject, int column,
77 PreparedStatement statement) throws SQLException, TypeCastException
78 {
79 statement.setObject(column, getEnum(enumObject, statement.getConnection()));
80 }
81
82 public Object typeCast(Object arg0) throws TypeCastException
83 {
84 return arg0.toString();
85 }
86
87 private Object getEnum(Object value, Connection connection) throws TypeCastException {
88
89 logger.debug("getEnum(value={}, connection={}) - start", value, connection);
90
91 Object tempEnum = null;
92
93 try {
94 Class aPGObjectClass = super.loadClass("org.postgresql.util.PGobject", connection);
95 Constructor ct = aPGObjectClass.getConstructor(null);
96 tempEnum = ct.newInstance(null);
97
98 Method setTypeMethod = aPGObjectClass.getMethod("setType", new Class[]{String.class});
99 setTypeMethod.invoke(tempEnum, new Object[]{this.sqlTypeName});
100
101 Method setValueMethod = aPGObjectClass.getMethod("setValue", new Class[]{String.class});
102 setValueMethod.invoke(tempEnum, new Object[]{value.toString()});
103
104 } catch (ClassNotFoundException e) {
105 throw new TypeCastException(value, this, e);
106 } catch (InvocationTargetException e) {
107 throw new TypeCastException(value, this, e);
108 } catch (NoSuchMethodException e) {
109 throw new TypeCastException(value, this, e);
110 } catch (IllegalAccessException e) {
111 throw new TypeCastException(value, this, e);
112 } catch (InstantiationException e) {
113 throw new TypeCastException(value, this, e);
114 }
115
116 return tempEnum;
117 }
118
119 public String getSqlTypeName() {
120 return sqlTypeName;
121 }
122
123
124 }