View Javadoc
1   /*
2    *
3    * The DbUnit Database Testing Framework
4    * Copyright (C)2002-2004, DbUnit.org
5    *
6    * This library is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU Lesser General Public
8    * License as published by the Free Software Foundation; either
9    * version 2.1 of the License, or (at your option) any later version.
10   *
11   * This library is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   * Lesser General Public License for more details.
15   *
16   * You should have received a copy of the GNU Lesser General Public
17   * License along with this library; if not, write to the Free Software
18   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   *
20   */
21  
22  package org.dbunit.dataset.datatype;
23  
24  import java.math.BigInteger;
25  import java.sql.PreparedStatement;
26  import java.sql.ResultSet;
27  import java.sql.SQLException;
28  import java.sql.Timestamp;
29  import java.sql.Types;
30  import java.util.TimeZone;
31  import java.util.regex.Matcher;
32  import java.util.regex.Pattern;
33  
34  import org.dbunit.dataset.ITable;
35  import org.slf4j.Logger;
36  import org.slf4j.LoggerFactory;
37  
38  /**
39   * @author Manuel Laflamme
40   * @author Last changed by: $Author$
41   * @version $Revision$ $Date$
42   * @since 1.0 (Feb 19, 2002)
43   */
44  public class TimestampDataType extends AbstractDataType
45  {
46      private static final BigInteger ONE_BILLION = new BigInteger("1000000000");
47      private static final Pattern TIMEZONE_REGEX = Pattern.compile("(.*)(?:\\W([+-][0-2][0-9][0-5][0-9]))");
48  
49      /**
50       * Logger for this class
51       */
52      private static final Logger logger = LoggerFactory.getLogger(TimestampDataType.class);
53  
54      TimestampDataType()
55      {
56          super("TIMESTAMP", Types.TIMESTAMP, Timestamp.class, false);
57      }
58  
59      ////////////////////////////////////////////////////////////////////////////
60      // DataType class
61  
62      @Override
63      public Object typeCast(Object value) throws TypeCastException
64      {
65          logger.debug("typeCast(value={}) - start", value);
66  
67          if (value == null || value == ITable.NO_VALUE)
68          {
69              return null;
70          }
71  
72          if (value instanceof java.sql.Timestamp)
73          {
74              return value;
75          }
76  
77          if (value instanceof java.util.Date)
78          {
79              java.util.Date date = (java.util.Date) value;
80              return new java.sql.Timestamp(date.getTime());
81          }
82  
83          if (value instanceof Long)
84          {
85              Long date = (Long) value;
86              return new java.sql.Timestamp(date.longValue());
87          }
88  
89          if (value instanceof String)
90          {
91              String stringValue = value.toString();
92              String zoneValue = null;
93  
94              Matcher tzMatcher = TIMEZONE_REGEX.matcher(stringValue);
95              if (tzMatcher.matches() && tzMatcher.group(2) != null)
96              {
97                  stringValue = tzMatcher.group(1);
98                  zoneValue = tzMatcher.group(2);
99              }
100 
101             Timestamp ts = null;
102             if (stringValue.length() == 10)
103             {
104                 try
105                 {
106                     long time = java.sql.Date.valueOf(stringValue).getTime();
107                     ts = new java.sql.Timestamp(time);
108                 } catch (IllegalArgumentException e)
109                 {
110                     // Was not a java.sql.Date, let Timestamp handle this value
111                 }
112             }
113             if (ts == null)
114             {
115                 try
116                 {
117                     ts = java.sql.Timestamp.valueOf(stringValue);
118                 } catch (IllegalArgumentException e)
119                 {
120                     throw new TypeCastException(value, this, e);
121                 }
122             }
123 
124             // Apply zone if any
125             if (zoneValue != null)
126             {
127                 TimeZone localTZ = java.util.TimeZone.getDefault();
128                 BigInteger localTZOffset = BigInteger.valueOf(localTZ.getRawOffset());
129                 BigInteger time = BigInteger.valueOf(ts.getTime() / 1000 * 1000).add(localTZOffset)
130                         .multiply(ONE_BILLION).add(BigInteger.valueOf(ts.getNanos()));
131                 int hours = Integer.parseInt(zoneValue.substring(1, 3));
132                 int minutes = Integer.parseInt(zoneValue.substring(3, 5));
133                 BigInteger offsetAsSeconds = BigInteger.valueOf((hours * 3600) + (minutes * 60));
134                 BigInteger offsetAsNanos = offsetAsSeconds.multiply(BigInteger.valueOf(1000)).multiply(ONE_BILLION);
135                 if (zoneValue.charAt(0) == '+')
136                 {
137                     time = time.subtract(offsetAsNanos);
138                 } else
139                 {
140                     time = time.add(offsetAsNanos);
141                 }
142                 BigInteger[] components = time.divideAndRemainder(ONE_BILLION);
143                 ts = new Timestamp(components[0].longValue());
144                 ts.setNanos(components[1].intValue());
145             }
146 
147             return ts;
148         }
149 
150         throw new TypeCastException(value, this);
151     }
152 
153     @Override
154     public boolean isDateTime()
155     {
156         logger.debug("isDateTime() - start");
157 
158         return true;
159     }
160 
161     @Override
162     public Object getSqlValue(int column, ResultSet resultSet) throws SQLException, TypeCastException
163     {
164         if (logger.isDebugEnabled())
165         {
166             logger.debug("getSqlValue(column={}, resultSet={}) - start", new Integer(column), resultSet);
167         }
168 
169         Timestamp value = resultSet.getTimestamp(column);
170         if (value == null || resultSet.wasNull())
171         {
172             return null;
173         }
174         return value;
175     }
176 
177     @Override
178     public void setSqlValue(Object value, int column, PreparedStatement statement)
179             throws SQLException, TypeCastException
180     {
181         if (logger.isDebugEnabled())
182         {
183             logger.debug("setSqlValue(value={}, column={}, statement={}) - start",
184                     new Object[] {value, new Integer(column), statement});
185         }
186 
187         statement.setTimestamp(column, (java.sql.Timestamp) typeCast(value));
188     }
189 }