KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > datasource > ids > test > TableIdGeneratorJdbcTestCase


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14  * implied.
15  *
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */

19
20 package org.apache.avalon.excalibur.datasource.ids.test;
21
22 import java.math.BigDecimal JavaDoc;
23 import java.sql.Connection JavaDoc;
24 import java.sql.ResultSet JavaDoc;
25 import java.sql.SQLException JavaDoc;
26 import java.sql.Statement JavaDoc;
27
28 import org.apache.avalon.excalibur.datasource.DataSourceComponent;
29 import org.apache.avalon.excalibur.datasource.ids.IdException;
30 import org.apache.avalon.excalibur.datasource.ids.IdGenerator;
31 import org.apache.avalon.excalibur.testcase.ExcaliburTestCase;
32 import org.apache.avalon.framework.component.ComponentSelector;
33
34 /**
35  * Test the TableIdGenerator Component.
36  *
37  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
38  */

39 public class TableIdGeneratorJdbcTestCase
40     extends ExcaliburTestCase
41 {
42     private ComponentSelector m_dbSelector;
43     private DataSourceComponent m_dataSource;
44
45     private ComponentSelector m_idGeneratorSelector;
46
47     /*---------------------------------------------------------------
48      * Constructors
49      *-------------------------------------------------------------*/

50     public TableIdGeneratorJdbcTestCase( String JavaDoc name )
51     {
52         super( name );
53     }
54
55     /*---------------------------------------------------------------
56      * TestCase Methods
57      *-------------------------------------------------------------*/

58     public void setUp() throws Exception JavaDoc
59     {
60         super.setUp();
61         // Get a reference to a data source
62
m_dbSelector = (ComponentSelector)manager.lookup( DataSourceComponent.ROLE + "Selector" );
63         m_dataSource = (DataSourceComponent)m_dbSelector.select( "test-db" );
64
65         // We need to initialize an ids table in the database for these tests.
66
try
67         {
68             Connection JavaDoc conn = m_dataSource.getConnection();
69             try
70             {
71                 Statement JavaDoc statement = conn.createStatement();
72
73                 // Try to drop the table. It may not exist and throw an exception.
74
getLogger().debug( "Attempting to drop old ids table" );
75                 try
76                 {
77                     statement.executeUpdate( "DROP TABLE ids" );
78                 }
79                 catch( SQLException JavaDoc e )
80                 {
81                     // The table was probably just not there. Ignore this.
82
}
83
84                 // Create the table that we will use in this test.
85
// Different depending on the db. Please add new statements as new databases are
86
// tested.
87
getLogger().debug( "Create new ids table" );
88                 statement.executeUpdate(
89                     "CREATE TABLE ids ( " +
90                     "table_name varchar(16) NOT NULL, " +
91                     "next_id DECIMAL(30) NOT NULL, " +
92                     "PRIMARY KEY (table_name))" );
93             }
94             finally
95             {
96                 conn.close();
97             }
98         }
99         catch( SQLException JavaDoc e )
100         {
101             getLogger().error( "Unable to initialize database for test.", e );
102             fail( "Unable to initialize database for test. " + e );
103         }
104
105         // Get a reference to an IdGenerator Selector.
106
// Individual IdGenerators are obtained in the tests.
107
m_idGeneratorSelector = (ComponentSelector)manager.lookup( IdGenerator.ROLE + "Selector" );
108
109     }
110
111     public void tearDown() throws Exception JavaDoc
112     {
113         // Free up the IdGenerator Selector
114
if( m_idGeneratorSelector != null )
115         {
116             manager.release( m_idGeneratorSelector );
117
118             m_dbSelector = null;
119         }
120
121         try
122         {
123             Connection JavaDoc conn = m_dataSource.getConnection();
124             try
125             {
126                 Statement JavaDoc statement = conn.createStatement();
127
128                 // Delete the table that we will use in this test.
129
getLogger().debug( "Drop ids table" );
130                 statement.executeUpdate( "DROP TABLE ids" );
131             }
132             finally
133             {
134                 conn.close();
135             }
136         }
137         catch( SQLException JavaDoc e )
138         {
139             getLogger().error( "Unable to cleanup database after test.", e );
140             // Want to continue
141
}
142
143         // Free up the data source
144
if( m_dbSelector != null )
145         {
146             if( m_dataSource != null )
147             {
148                 m_dbSelector.release( m_dataSource );
149
150                 m_dataSource = null;
151             }
152
153             manager.release( m_dbSelector );
154
155             m_dbSelector = null;
156         }
157
158         super.tearDown();
159     }
160
161     /*---------------------------------------------------------------
162      * Test Cases
163      *-------------------------------------------------------------*/

164     public void testNonExistingTableName() throws Exception JavaDoc
165     {
166         getLogger().info( "testNonExistingTableName" );
167
168         IdGenerator idGenerator =
169             (IdGenerator)m_idGeneratorSelector.select( "ids-testNonExistingTableName" );
170         try
171         {
172             try
173             {
174                 idGenerator.getNextIntegerId();
175                 fail( "Should not have gotten an id" );
176             }
177             catch( IdException e )
178             {
179                 // Got the expected error.
180
}
181         }
182         finally
183         {
184             m_idGeneratorSelector.release( idGenerator );
185         }
186     }
187
188     public void testSimpleRequestIdsSize1() throws Exception JavaDoc
189     {
190         getLogger().info( "testSimpleRequestIdsSize1" );
191
192         IdGenerator idGenerator =
193             (IdGenerator)m_idGeneratorSelector.select( "ids-testSimpleRequestIdsSize1" );
194         try
195         {
196             int testCount = 100;
197
198             // Initialize the counter in the database.
199
initializeNextLongId( "test", 1 );
200
201             for( int i = 1; i <= testCount; i++ )
202             {
203                 int id = idGenerator.getNextIntegerId();
204                 assertEquals( "The returned id was not what was expected.", i, id );
205             }
206
207             assertEquals( "The next_id column in the database did not have the expected value.",
208                           testCount + 1, peekNextLongId( "test" ) );
209         }
210         finally
211         {
212             m_idGeneratorSelector.release( idGenerator );
213         }
214     }
215
216     public void testSimpleRequestIdsSize10() throws Exception JavaDoc
217     {
218         getLogger().info( "testSimpleRequestIdsSize10" );
219
220         IdGenerator idGenerator =
221             (IdGenerator)m_idGeneratorSelector.select( "ids-testSimpleRequestIdsSize10" );
222         try
223         {
224             int testCount = 100;
225
226             // Initialize the counter in the database.
227
initializeNextLongId( "test", 1 );
228
229             for( int i = 1; i <= testCount; i++ )
230             {
231                 int id = idGenerator.getNextIntegerId();
232                 assertEquals( "The returned id was not what was expected.", i, id );
233             }
234
235             assertEquals( "The next_id column in the database did not have the expected value.",
236                           testCount + 1, peekNextLongId( "test" ) );
237         }
238         finally
239         {
240             m_idGeneratorSelector.release( idGenerator );
241         }
242     }
243
244     public void testSimpleRequestIdsSize100() throws Exception JavaDoc
245     {
246         getLogger().info( "testSimpleRequestIdsSize100" );
247
248         IdGenerator idGenerator =
249             (IdGenerator)m_idGeneratorSelector.select( "ids-testSimpleRequestIdsSize100" );
250         try
251         {
252             int testCount = 100;
253
254             // Initialize the counter in the database.
255
initializeNextLongId( "test", 1 );
256
257             for( int i = 1; i <= testCount; i++ )
258             {
259                 int id = idGenerator.getNextIntegerId();
260                 assertEquals( "The returned id was not what was expected.", i, id );
261             }
262
263             assertEquals( "The next_id column in the database did not have the expected value.",
264                           testCount + 1, peekNextLongId( "test" ) );
265         }
266         finally
267         {
268             m_idGeneratorSelector.release( idGenerator );
269         }
270     }
271
272     public void testBigDecimalRequestIdsSize10() throws Exception JavaDoc
273     {
274         getLogger().info( "testBigDecimalRequestIdsSize10" );
275
276         if( isBigDecimalImplemented() )
277         {
278             IdGenerator idGenerator =
279                 (IdGenerator)m_idGeneratorSelector.select( "ids-testBigDecimalRequestIdsSize10" );
280             try
281             {
282                 int testCount = 100;
283                 BigDecimal JavaDoc initial = new BigDecimal JavaDoc( Long.MAX_VALUE + "00" );
284
285                 // Initialize the counter in the database.
286
initializeNextBigDecimalId( "test", initial );
287
288                 for( int i = 0; i < testCount; i++ )
289                 {
290                     BigDecimal JavaDoc id = idGenerator.getNextBigDecimalId();
291                     assertEquals( "The returned id was not what was expected.",
292                                   initial.add( new BigDecimal JavaDoc( i ) ), id );
293                 }
294
295                 assertEquals( "The next_id column in the database did not have the expected value.",
296                               initial.add( new BigDecimal JavaDoc( testCount ) ), peekNextBigDecimalId( "test" ) );
297             }
298             finally
299             {
300                 m_idGeneratorSelector.release( idGenerator );
301             }
302         }
303         else
304         {
305             getLogger().warn( "Test Skipped because BigDecimals are not implemented in current driver." );
306         }
307     }
308
309     public void testMaxByteIds() throws Exception JavaDoc
310     {
311         getLogger().info( "testMaxByteIds" );
312
313         IdGenerator idGenerator = (IdGenerator)m_idGeneratorSelector.select( "ids-testMaxByteIds" );
314         try
315         {
316             int testCount = 100;
317             long max = Byte.MAX_VALUE;
318             long initial = max - testCount;
319
320             // Initialize the counter in the database.
321
initializeNextLongId( "test", initial );
322
323             for( int i = 0; i <= testCount; i++ )
324             {
325                 byte id = idGenerator.getNextByteId();
326                 assertEquals( "The returned id was not what was expected.", i + initial, id );
327             }
328
329             // Next one should throw an exception
330
try
331             {
332                 byte id = idGenerator.getNextByteId();
333                 fail( "Should not have gotten an id: " + id );
334             }
335             catch( IdException e )
336             {
337                 // Good. Got the exception.
338
}
339         }
340         finally
341         {
342             m_idGeneratorSelector.release( idGenerator );
343         }
344     }
345
346     public void testMaxShortIds() throws Exception JavaDoc
347     {
348         getLogger().info( "testMaxShortIds" );
349
350         IdGenerator idGenerator = (IdGenerator)m_idGeneratorSelector.select( "ids-testMaxShortIds" );
351         try
352         {
353             int testCount = 100;
354             long max = Short.MAX_VALUE;
355             long initial = max - testCount;
356
357             // Initialize the counter in the database.
358
initializeNextLongId( "test", initial );
359
360             for( int i = 0; i <= testCount; i++ )
361             {
362                 short id = idGenerator.getNextShortId();
363                 assertEquals( "The returned id was not what was expected.", i + initial, id );
364             }
365
366             // Next one should throw an exception
367
try
368             {
369                 short id = idGenerator.getNextShortId();
370                 fail( "Should not have gotten an id: " + id );
371             }
372             catch( IdException e )
373             {
374                 // Good. Got the exception.
375
}
376         }
377         finally
378         {
379             m_idGeneratorSelector.release( idGenerator );
380         }
381     }
382
383     public void testMaxIntegerIds() throws Exception JavaDoc
384     {
385         getLogger().info( "testMaxIntegerIds" );
386
387         IdGenerator idGenerator = (IdGenerator)m_idGeneratorSelector.select( "ids-testMaxIntegerIds" );
388         try
389         {
390             int testCount = 100;
391             long max = Integer.MAX_VALUE;
392             long initial = max - testCount;
393
394             // Initialize the counter in the database.
395
initializeNextLongId( "test", initial );
396
397             for( int i = 0; i <= testCount; i++ )
398             {
399                 int id = idGenerator.getNextIntegerId();
400                 assertEquals( "The returned id was not what was expected.", i + initial, id );
401             }
402
403             // Next one should throw an exception
404
try
405             {
406                 int id = idGenerator.getNextIntegerId();
407                 fail( "Should not have gotten an id: " + id );
408             }
409             catch( IdException e )
410             {
411                 // Good. Got the exception.
412
}
413         }
414         finally
415         {
416             m_idGeneratorSelector.release( idGenerator );
417         }
418     }
419
420     public void testMaxLongIds() throws Exception JavaDoc
421     {
422         getLogger().info( "testMaxLongIds" );
423
424         IdGenerator idGenerator = (IdGenerator)m_idGeneratorSelector.select( "ids-testMaxLongIds" );
425         try
426         {
427             int testCount = 100;
428             long max = Long.MAX_VALUE;
429             long initial = max - testCount;
430
431             // Initialize the counter in the database.
432
initializeNextLongId( "test", initial );
433
434             for( int i = 0; i <= testCount; i++ )
435             {
436                 long id = idGenerator.getNextLongId();
437                 assertEquals( "The returned id was not what was expected.", i + initial, id );
438             }
439
440             // Next one should throw an exception
441
try
442             {
443                 long id = idGenerator.getNextLongId();
444                 fail( "Should not have gotten an id: " + id );
445             }
446             catch( IdException e )
447             {
448                 // Good. Got the exception.
449
}
450         }
451         finally
452         {
453             m_idGeneratorSelector.release( idGenerator );
454         }
455     }
456
457     /*---------------------------------------------------------------
458      * Utilitity Methods
459      *-------------------------------------------------------------*/

460     /**
461      * Tests to see whether or not the current DataSource supports BigDecimal
462      */

463     private boolean isBigDecimalImplemented()
464     {
465         String JavaDoc tableName = "foorbar_table";
466
467         // Add a row that can be selected.
468
initializeNextLongId( tableName, 1 );
469
470         try
471         {
472             Connection JavaDoc conn = m_dataSource.getConnection();
473             try
474             {
475                 Statement JavaDoc statement = conn.createStatement();
476
477                 ResultSet JavaDoc rs = statement.executeQuery( "SELECT next_id FROM ids " +
478                                                        "WHERE table_name = '" + tableName + "'" );
479                 if( rs.next() )
480                 {
481                     rs.getBigDecimal( 1 );
482                 }
483                 else
484                 {
485                     fail( tableName + " row not in ids table." );
486                     return false; // for compiler
487
}
488             }
489             finally
490             {
491                 conn.close();
492             }
493
494             // Implemented
495
return true;
496         }
497         catch( SQLException JavaDoc e )
498         {
499             if( e.toString().toLowerCase().indexOf( "implemented" ) > 0 )
500             {
501                 // Not implemented
502
return false;
503             }
504             getLogEnabledLogger().error( "Unable to test for BigDecimal support.", e );
505             fail( "Unable to test for BigDecimal support. " + e );
506             return false; // for compiler
507
}
508     }
509
510     private void initializeNextBigDecimalId( String JavaDoc tableName, BigDecimal JavaDoc nextId )
511     {
512         try
513         {
514             Connection JavaDoc conn = m_dataSource.getConnection();
515             try
516             {
517                 Statement JavaDoc statement = conn.createStatement();
518
519                 // Need to quote the BigDecimal as it is larger than normal numbers can be.
520
// Was causing problems with MySQL
521
statement.executeUpdate( "INSERT INTO ids (table_name, next_id) VALUES ('" +
522                                          tableName + "', '" + nextId.toString() + "')" );
523             }
524             finally
525             {
526                 conn.close();
527             }
528         }
529         catch( SQLException JavaDoc e )
530         {
531             getLogger().error( "Unable to initialize next_id.", e );
532             fail( "Unable to initialize next_id. " + e );
533         }
534     }
535
536     private void initializeNextLongId( String JavaDoc tableName, long nextId )
537     {
538         try
539         {
540             Connection JavaDoc conn = m_dataSource.getConnection();
541             try
542             {
543                 Statement JavaDoc statement = conn.createStatement();
544
545                 statement.executeUpdate( "INSERT INTO ids (table_name, next_id) VALUES ('" +
546                                          tableName + "', " + nextId + ")" );
547             }
548             finally
549             {
550                 conn.close();
551             }
552         }
553         catch( SQLException JavaDoc e )
554         {
555             getLogger().error( "Unable to initialize next_id.", e );
556             fail( "Unable to initialize next_id. " + e );
557         }
558     }
559
560     private BigDecimal JavaDoc peekNextBigDecimalId( String JavaDoc tableName )
561     {
562         try
563         {
564             Connection JavaDoc conn = m_dataSource.getConnection();
565             try
566             {
567                 Statement JavaDoc statement = conn.createStatement();
568
569                 ResultSet JavaDoc rs = statement.executeQuery( "SELECT next_id FROM ids " +
570                                                        "WHERE table_name = '" + tableName + "'" );
571                 if( rs.next() )
572                 {
573                     return rs.getBigDecimal( 1 );
574                 }
575                 else
576                 {
577                     fail( tableName + " row not in ids table." );
578                     return null; // for compiler
579
}
580             }
581             finally
582             {
583                 conn.close();
584             }
585         }
586         catch( SQLException JavaDoc e )
587         {
588             getLogger().error( "Unable to peek next_id.", e );
589             fail( "Unable to peek next_id. " + e );
590             return null; // for compiler
591
}
592     }
593
594     private long peekNextLongId( String JavaDoc tableName )
595     {
596         try
597         {
598             Connection JavaDoc conn = m_dataSource.getConnection();
599             try
600             {
601                 Statement JavaDoc statement = conn.createStatement();
602
603                 ResultSet JavaDoc rs = statement.executeQuery( "SELECT next_id FROM ids " +
604                                                        "WHERE table_name = '" + tableName + "'" );
605                 if( rs.next() )
606                 {
607                     return rs.getLong( 1 );
608                 }
609                 else
610                 {
611                     fail( tableName + " row not in ids table." );
612                     return -1; // for compiler
613
}
614             }
615             finally
616             {
617                 conn.close();
618             }
619         }
620         catch( SQLException JavaDoc e )
621         {
622             getLogger().error( "Unable to peek next_id.", e );
623             fail( "Unable to peek next_id. " + e );
624             return -1; // for compiler
625
}
626     }
627 }
628
629
Popular Tags