UniqueIdentifierType.java

  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. import java.sql.PreparedStatement;
  22. import java.sql.ResultSet;
  23. import java.sql.SQLException;
  24. import java.sql.Types;
  25. import java.util.UUID;

  26. import org.dbunit.dataset.datatype.AbstractDataType;
  27. import org.dbunit.dataset.datatype.TypeCastException;

  28. /**
  29.  * <code>UniqueIdentifierType</code> provides support for the "uniqueidentifier" column in Microsoft SQLServer
  30.  * databases. It users the {@link UUID}
  31.  *
  32.  * @Author Darryl L. Pierce <dpierce@redhat.com>
  33.  * @Since 02 February 2011
  34.  * @version $Revision$
  35.  */
  36. public class UniqueIdentifierType extends AbstractDataType {
  37.     static final String UNIQUE_IDENTIFIER_TYPE = "uniqueidentifier";

  38.     public UniqueIdentifierType() {
  39.         super(UNIQUE_IDENTIFIER_TYPE, Types.CHAR, UUID.class, false);
  40.     }

  41.     @Override
  42.     public Object typeCast(Object value) throws TypeCastException {
  43.         return value.toString();
  44.     }

  45.     @Override
  46.     public Object getSqlValue(int column, ResultSet resultSet) throws SQLException, TypeCastException {
  47.         String value = resultSet.getString(column);

  48.         try {
  49.             return value != null && value.length() > 0 ? UUID.fromString(value)
  50.                     : null;
  51.         } catch (IllegalArgumentException error) {
  52.             throw new TypeCastException("Invalid UUID: " + value, error);
  53.         }
  54.     }

  55.     @Override
  56.     public void setSqlValue(Object value, int column, PreparedStatement statement) throws SQLException,
  57.     TypeCastException {
  58.         if (value == null)
  59.         {
  60.             statement.setObject(column, null);
  61.         } else
  62.         {
  63.             statement.setObject(column, value.toString());
  64.         }
  65.     }
  66. }