KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > persist > db > driver > TimeTest


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: TimeTest.java,v 1.10 2007/01/07 06:14:51 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.persist.db.driver;
23
24 import java.sql.PreparedStatement JavaDoc;
25 import java.sql.ResultSet JavaDoc;
26 import java.sql.SQLException JavaDoc;
27 import java.text.DateFormat JavaDoc;
28 import java.util.Calendar JavaDoc;
29
30 import junit.extensions.TestSetup;
31 import junit.framework.Test;
32 import junit.framework.TestSuite;
33
34 import org.opensubsystems.core.error.OSSException;
35 import org.opensubsystems.core.persist.db.Database;
36 import org.opensubsystems.core.persist.db.DatabaseImpl;
37 import org.opensubsystems.core.persist.db.DatabaseTest;
38 import org.opensubsystems.core.persist.db.DatabaseTestSetup;
39 import org.opensubsystems.core.persist.db.DatabaseTestSuite;
40 import org.opensubsystems.core.util.DatabaseUtils;
41 import org.opensubsystems.core.util.DateUtils;
42
43 /**
44  * All tests related to time functionality.
45  *
46  * @version $Id: TimeTest.java,v 1.10 2007/01/07 06:14:51 bastafidli Exp $
47  * @author Miro Halas
48  * @code.reviewer Miro Halas
49  * @code.reviewed 1.8 2005/09/09 06:50:44 bastafidli
50  */

51 public final class TimeTest
52 {
53    // Constructors /////////////////////////////////////////////////////////////
54

55    /**
56     * Private constructor since this class cannot be instantiated
57     */

58    private TimeTest(
59    )
60    {
61       // Do nothing
62
}
63    
64    // Public methods ///////////////////////////////////////////////////////////
65

66    /**
67     * Create the suite for this test since this is the only way how to create
68     * test setup which can initialize and shutdown the database for us
69     *
70     * @return Test - suite of tests to run for this database
71     */

72    public static Test suite(
73    )
74    {
75       TestSuite suite = new DatabaseTestSuite("TimeTest");
76       suite.addTestSuite(TimeTestInternal.class);
77       TestSetup wrapper = new DatabaseTestSetup(suite);
78
79       return wrapper;
80    }
81
82    /**
83     * Internal class which can be included in other test suites directly without
84     * including the above suite. This allows us to group multiple tests
85     * together and the execute the DatabaseTestSetup only once
86     */

87    public static class TimeTestInternal extends DatabaseTest
88    {
89       /**
90        * Static initializer
91        */

92       static
93       {
94          // This test use special database schema so make the database aware of it
95
Database dbDatabase;
96    
97          try
98          {
99             dbDatabase = DatabaseImpl.getInstance();
100             // Add schema database tests needs to the database
101
dbDatabase.add(DatabaseTestSchema.class);
102          }
103          catch (OSSException bfeExc)
104          {
105             throw new RuntimeException JavaDoc("Unexpected exception.", bfeExc);
106          }
107       }
108    
109       /**
110        * Create new time test.
111        *
112        * @param strTestName - name of the test
113        */

114       public TimeTestInternal(
115          String JavaDoc strTestName
116       )
117       {
118          super(strTestName);
119       }
120       
121       /**
122        * Test the database support for Time objects. Time object ignores the date
123        * portion of the Java Date. The java.sql.Time requires the date portion
124        * of the Time to be set to January 1, 1970 but it doesn't enforces it
125        * when using the long contructor therefore allowing us to create time
126        * values greater then 24 hours.
127        *
128        * This class inserts time into database, then retrieve it back using
129        * different java date and deletes it using cursor.
130        *
131        * Uses the already setup connection and transaction.
132        * No need to close the connection since base class is doing it for us.
133        *
134        * @throws Throwable - an error has occured during test
135        */

136       public void testBasicTimeSupport(
137       ) throws Throwable JavaDoc
138       {
139          final String JavaDoc INSERT_TIME = "insert into TIME_TEST(TIME_TEST) values (?)";
140          // See OracleTests class why we need to select tablename.*
141
final String JavaDoc SELECT_TIME = "select TIME_TEST.* from TIME_TEST where TIME_TEST = ?";
142          final String JavaDoc DELETE_TIME = "delete from TIME_TEST where TIME_TEST = ?";
143           
144          Calendar JavaDoc calGenerate = Calendar.getInstance();
145          java.sql.Time JavaDoc insertTime;
146          PreparedStatement JavaDoc insertStatement;
147          int iUpdateCount;
148          
149          // Set date to a test date
150
calGenerate.set(1995, 9, 15, 1, 2, 3);
151          insertTime = new java.sql.Time JavaDoc(calGenerate.getTimeInMillis());
152          
153          m_transaction.begin();
154    
155          try
156          {
157             insertStatement = m_connection.prepareStatement(INSERT_TIME);
158             insertStatement.setTime(1, insertTime);
159    
160             iUpdateCount = DatabaseUtils.executeUpdateAndClose(insertStatement);
161    
162             m_transaction.commit();
163          }
164          catch (Throwable JavaDoc throwable)
165          {
166             m_transaction.rollback();
167             throw throwable;
168          }
169          
170          assertEquals("Exactly one record with time data shoud have been inserted.",
171                              iUpdateCount, 1);
172          
173          // Now select it back to be sure it is there
174
PreparedStatement JavaDoc selectStatement = null;
175          PreparedStatement JavaDoc deleteStatement = null;
176          ResultSet JavaDoc results = null;
177          java.sql.Time JavaDoc retrievedTime;
178          boolean bHasMoreThanOne;
179          int iDeletedCount = 0;
180    
181          m_transaction.begin();
182    
183          try
184          {
185             java.sql.Time JavaDoc selectTime;
186             boolean bUpdatableResultSet = true;
187             
188             try
189             {
190                selectStatement = m_connection.prepareStatement(
191                                     SELECT_TIME,
192                                     ResultSet.TYPE_SCROLL_SENSITIVE,
193                                     ResultSet.CONCUR_UPDATABLE);
194             }
195             catch (SQLException JavaDoc sqleExc)
196             {
197                // Maybe it doesn't support updatable results set (e.g HSQLDB)
198
// so try to work around it
199
bUpdatableResultSet = false;
200                selectStatement = m_connection.prepareStatement(SELECT_TIME);
201                // DOn't catch any exception here, if this doesn't work, something
202
// is really wrong
203
}
204    
205             // Set different date, since when we are dealing with just time it
206
// shouldn't matter
207
calGenerate.set(1975, 10, 16, 1, 2, 3);
208             selectTime = new java.sql.Time JavaDoc(calGenerate.getTimeInMillis());
209             selectStatement.setTime(1, selectTime);
210             results = selectStatement.executeQuery();
211             
212             // Get the time from the database
213
assertTrue("The inserted time not found in the database since most" +
214                        " likely because java.sql.Time and driver implementation" +
215                        " doesn't enforce date portion to be set to January 1, 1970" +
216                        " when using constructor(long).", results.next());
217             retrievedTime = results.getTime(1);
218             // Delete the inserted row
219
if (bUpdatableResultSet)
220             {
221                // This is the optimal way to do it, but not every database supports
222
// updatable ResultSet (e.g. HSQLDB, ResultSetUnitTest tests for this)
223
// so provide an alternative
224
try
225                {
226                   results.deleteRow();
227                   iDeletedCount = 1;
228                }
229                catch (SQLException JavaDoc sqleExc)
230                {
231                   // Maybe it doesn't support updatable results set (e.g Firebird)
232
// so try to work around it
233
bUpdatableResultSet = false;
234                }
235             }
236             if (!bUpdatableResultSet)
237             {
238                deleteStatement = m_connection.prepareStatement(DELETE_TIME);
239                deleteStatement.setTime(1, insertTime);
240                iDeletedCount = DatabaseUtils.executeUpdateAndClose(deleteStatement);
241             }
242             // Get the assert check without throwing exception so we can correctly
243
// cleanup
244
bHasMoreThanOne = results.next();
245             m_transaction.commit();
246          }
247          catch (Throwable JavaDoc throwable)
248          {
249             m_transaction.rollback();
250             throw throwable;
251          }
252          finally
253          {
254             DatabaseUtils.closeResultSetAndStatement(results, selectStatement);
255             
256             m_transaction.begin();
257             try
258             {
259                deleteStatement = m_connection.prepareStatement(
260                         "delete from TIME_TEST");
261                deleteStatement.execute();
262                m_transaction.commit();
263             }
264             catch (Exception JavaDoc eExc)
265             {
266                m_transaction.rollback();
267                throw eExc;
268             }
269             finally
270             {
271                DatabaseUtils.closeStatement(deleteStatement);
272             }
273          }
274          
275          assertFalse("There should be only one inserted time in the database.",
276                      bHasMoreThanOne);
277       
278          assertEquals("Exactly one record with time data shoud have been deleted.",
279                       iDeletedCount, 1);
280    
281          // And now test the date
282
assertNotNull("The inserted time shouldn't be retrieved as null from the database",
283                        retrievedTime);
284          // Ignore milliseconds when comparing dates
285
assertTrue("The time retrieved from database "
286                     + DateFormat.getDateTimeInstance().format(retrievedTime)
287                     + " is not the same as the inserted one "
288                     + DateFormat.getDateTimeInstance().format(insertTime),
289                     DateUtils.timeEquals(retrievedTime, insertTime, true));
290       }
291    }
292 }
293
Popular Tags