View Javadoc
1   /*
2    * Copyright (C) 2011, Red Hat, Inc.
3    * Written by Darryl L. Pierce <dpierce@redhat.com>.
4    *
5    * This library is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU Lesser General Public
7    * License as published by the Free Software Foundation; either
8    * version 2.1 of the License, or (at your option) any later version.
9    *
10   * This library is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   * Lesser General Public License for more details.
14   *
15   * You should have received a copy of the GNU Lesser General Public
16   * License along with this library; if not, write to the Free Software
17   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   *
19   */
20  package org.dbunit.ext.mssql;
21  
22  import java.sql.PreparedStatement;
23  import java.sql.ResultSet;
24  import java.sql.SQLException;
25  import java.sql.Types;
26  import java.util.UUID;
27  
28  import org.dbunit.dataset.datatype.AbstractDataType;
29  import org.dbunit.dataset.datatype.TypeCastException;
30  
31  /**
32   * <code>UniqueIdentifierType</code> provides support for the "uniqueidentifier" column in Microsoft SQLServer
33   * databases. It users the {@link UUID}
34   *
35   * @Author Darryl L. Pierce <dpierce@redhat.com>
36   * @Since 02 February 2011
37   * @version $Revision$
38   */
39  public class UniqueIdentifierType extends AbstractDataType {
40      static final String UNIQUE_IDENTIFIER_TYPE = "uniqueidentifier";
41  
42      public UniqueIdentifierType() {
43          super(UNIQUE_IDENTIFIER_TYPE, Types.CHAR, UUID.class, false);
44      }
45  
46      @Override
47      public Object typeCast(Object value) throws TypeCastException {
48          return value.toString();
49      }
50  
51      @Override
52      public Object getSqlValue(int column, ResultSet resultSet) throws SQLException, TypeCastException {
53          String value = resultSet.getString(column);
54  
55          try {
56              return value != null && value.length() > 0 ? UUID.fromString(value)
57                      : null;
58          } catch (NumberFormatException error) {
59              throw new TypeCastException("Invalid UUID: " + value, error);
60          }
61      }
62  
63      @Override
64      public void setSqlValue(Object value, int column, PreparedStatement statement) throws SQLException,
65      TypeCastException {
66          if (value == null)
67          {
68              statement.setObject(column, null);
69          } else
70          {
71              statement.setObject(column, value.toString());
72          }
73      }
74  }