KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: DateTest.java,v 1.6 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 date functionality.
45  *
46  * @version $Id: DateTest.java,v 1.6 2007/01/07 06:14:51 bastafidli Exp $
47  * @author Miro Halas
48  * @code.reviewer Miro Halas
49  * @code.reviewed Initial revision
50  */

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

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

58    private DateTest(
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("DateTest");
76       suite.addTestSuite(DateTestInternal.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 DateTestInternal 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 date test.
111        *
112        * @param strTestName - name of the test
113        */

114       public DateTestInternal(
115          String JavaDoc strTestName
116       )
117       {
118          super(strTestName);
119       }
120       
121       /**
122        * Test the database support for Date objects. Date object ignores the time
123        * portion of the Java Date.
124        *
125        * This class inserts date into database, then retrieve it back using
126        * different java time and deletes it using cursor.
127        *
128        * Uses the already setup connection and transaction.
129        * No need to close the connection since base class is doing it for us.
130        *
131        * @throws Throwable - an error has occured during test
132        */

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