KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > functionTests > util > DerbyJUnitTest


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

21
22 /**
23  * <p>
24  * This class factors out utility methods (including assertion machinery)
25  * for re-use by Derby JUnit tests. JUnit tests should extend this class.
26  * </p>
27  *
28  * @author Rick
29  */

30
31 package org.apache.derbyTesting.functionTests.util;
32
33 import java.io.*;
34 import java.math.*;
35 import java.sql.*;
36 import java.util.*;
37
38 import junit.framework.*;
39
40 import org.apache.derby.tools.ij;
41
42 public class DerbyJUnitTest extends TestCase
43 {
44     /////////////////////////////////////////////////////////////
45
//
46
// CONSTANTS
47
//
48
/////////////////////////////////////////////////////////////
49

50     /** If you set this startup property to true, you will get chatty output. */
51     public static final String JavaDoc DEBUG_FLAG = "drb.tests.debug";
52     
53     public static final int SUCCESS_EXIT = 0;
54     public static final int FAILURE_EXIT = 1;
55
56     public static final String JavaDoc DEFAULT_USER_NAME = "APP";
57     public static final String JavaDoc DEFAULT_PASSWORD = "APP";
58     public static final String JavaDoc DEFAULT_DATABASE_NAME = "wombat";
59
60     // because java.sql.Types.BOOLEAN doesn't exist in jdbc 2.0
61
protected static final int JDBC_BOOLEAN = 16;
62     
63     //
64
// For dropping schema objects
65
//
66
private static final String JavaDoc TABLE = "table";
67     private static final String JavaDoc FUNCTION = "function";
68     private static final String JavaDoc PROCEDURE = "procedure";
69     
70     //
71
// These are properties for the Derby connection URL.
72
//
73
private static final String JavaDoc SERVER_URL = "jdbc:derby://localhost:1527/";
74     private static final String JavaDoc CREATE_PROPERTY = "create=true";
75
76     //
77
// Indexes into the array of client-specific strings. E.g., DB2JCC_CLIENT,
78
// DERBY_CLIENT, and EMBEDDED_CLIENT.
79
//
80
public static final int DATABASE_URL = 0;
81     public static final int DRIVER_NAME = DATABASE_URL + 1;
82     public static final int FRAMEWORK_NAME = DRIVER_NAME + 1;
83
84     // indexed by DATABASE_URL and DRIVER_NAME
85
private static final String JavaDoc[] DB2JCC_CLIENT =
86     {
87         "jdbc:derby:net://localhost:1527/",
88         "com.ibm.db2.jcc.DB2Driver",
89         "DerbyNet"
90     };
91     private static final String JavaDoc[] DERBY_CLIENT =
92     {
93         "jdbc:derby://localhost:1527/",
94         "org.apache.derby.jdbc.ClientDriver",
95         "DerbyNetClient"
96     };
97     private static final String JavaDoc[] EMBEDDED_CLIENT =
98     {
99         "jdbc:derby:",
100         "org.apache.derby.jdbc.EmbeddedDriver",
101         "embedded"
102     };
103
104     public static final String JavaDoc[][] LEGAL_CLIENTS =
105     {
106         DB2JCC_CLIENT,
107         DERBY_CLIENT,
108         EMBEDDED_CLIENT
109     };
110     
111     /////////////////////////////////////////////////////////////
112
//
113
// STATE
114
//
115
/////////////////////////////////////////////////////////////
116

117     private static boolean _debug; // if true, we print chatty diagnostics
118

119     private static PrintStream _outputStream = System.out; // where to print debug output
120

121     private static String JavaDoc _databaseName; // sandbox for tests
122
private static String JavaDoc[] _defaultClientSettings; // one of the clients in
123
// LEGAL_CLIENTS
124
private static boolean _initializedForTestHarness;
125
126     /////////////////////////////////////////////////////////////
127
//
128
// CONSTRUCTOR
129
//
130
/////////////////////////////////////////////////////////////
131

132     /**
133      * <p>
134      * Vacuous constructor for JUnit machinery.
135      * </p>
136      */

137     public DerbyJUnitTest() {}
138
139     /////////////////////////////////////////////////////////////
140
//
141
// PUBLIC BEHAVIOR
142
//
143
/////////////////////////////////////////////////////////////
144

145     /**
146      * <p>
147      * Run under the old harness.
148      * </p>
149      */

150     public static void runUnderOldHarness( String JavaDoc[] args, Test suite )
151         throws Exception JavaDoc
152     {
153         int exitStatus = FAILURE_EXIT;
154
155         initializeForOldHarness( args );
156
157         TestResult result = junit.textui.TestRunner.run( suite );
158             
159         exitStatus = result.errorCount() + result.failureCount();
160
161         Runtime.getRuntime().exit( exitStatus );
162     }
163
164     /**
165      * <p>
166      * Initialize a test suite to run under the old test harness.
167      * </p>
168      */

169     public static void initializeForOldHarness( String JavaDoc[] args )
170         throws Exception JavaDoc
171     {
172         if ( _initializedForTestHarness ) { return; }
173         
174         parseDebug();
175         setDatabaseName( DEFAULT_DATABASE_NAME );
176         findClientFromProperties();
177         
178         // create database
179
ij.getPropertyArg( args );
180         Connection conn = ij.startJBMS();
181
182         _initializedForTestHarness = true;
183     }
184
185     /**
186      * <p>
187      * Return true if we're using the embedded driver.
188      * </p>
189      */

190     public boolean usingEmbeddedClient() { return ( _defaultClientSettings == EMBEDDED_CLIENT ); }
191
192     /**
193      * <p>
194      * Return true if we're using the derby client
195      * </p>
196      */

197     public boolean usingDerbyClient() { return ( _defaultClientSettings == DERBY_CLIENT ); }
198
199     /**
200      * <p>
201      * Return true if we're using the db2 client
202      * </p>
203      */

204     public boolean usingDB2Client() { return ( _defaultClientSettings == DB2JCC_CLIENT ); }
205
206     /**
207      * <p>
208      * Get the client we're using.
209      * </p>
210      */

211     public static String JavaDoc[] getClientSettings() { return _defaultClientSettings; }
212
213     /**
214      * <p>
215      * Set the client we're going to use.
216      * </p>
217      */

218     public static void setClient( String JavaDoc[] client ) { _defaultClientSettings = client; }
219
220     /**
221      * <p>
222      * Set the database name.
223      * </p>
224      */

225     public static void setDatabaseName( String JavaDoc databaseName ) { _databaseName = databaseName; }
226     
227     /**
228      * <p>
229      * Force the debugging state. Useful for debugging under the test harness.
230      * </p>
231      */

232     public static void setDebug( boolean value ) { _debug = value; }
233
234     /**
235      * <p>
236      * Look for the system property which tells us whether to run
237      * chattily.
238      * </p>
239      */

240     public static boolean parseDebug()
241     {
242         _debug = Boolean.getBoolean( DEBUG_FLAG );
243         
244         return true;
245     }
246         
247     /**
248      * <p>
249      * Debug code to print chatty informational messages.
250      * </p>
251      */

252     public static void println( String JavaDoc text )
253     {
254         if ( _debug ) { alarm( text ); }
255     }
256
257     /**
258      * <p>
259      * Print a message regardless of whether we are running in debug mode.
260      * </p>
261      */

262     public static void alarm( String JavaDoc text )
263     {
264         _outputStream.println( text );
265         _outputStream.flush();
266     }
267
268     /**
269      * <p>
270      * Print out a stack trace.
271      * </p>
272      */

273     public static void printStackTrace( Throwable JavaDoc t )
274     {
275         while ( t != null )
276         {
277             t.printStackTrace( _outputStream );
278
279             if ( t instanceof SQLException ) { t = ((SQLException) t).getNextException(); }
280             else { break; }
281         }
282     }
283
284     /**
285      * <p>
286      * Determine the client to use based on system properties.
287      * </p>
288      */

289     public static void findClientFromProperties()
290         throws Exception JavaDoc
291     {
292         Properties systemProps = System.getProperties();
293         String JavaDoc frameworkName = systemProps.getProperty
294             ( "framework", EMBEDDED_CLIENT[ FRAMEWORK_NAME ] );
295         int count = LEGAL_CLIENTS.length;
296
297         for ( int i = 0; i < count; i++ )
298         {
299             String JavaDoc[] candidate = LEGAL_CLIENTS[ i ];
300
301             if ( candidate[ FRAMEWORK_NAME ].equals( frameworkName ) )
302             {
303                 _defaultClientSettings = candidate;
304                 return;
305             }
306         }
307
308         throw new Exception JavaDoc( "Unrecognized framework: " + frameworkName );
309     }
310
311     /**
312      * <p>
313      * Return a meaningful exit status so that calling scripts can take
314      * evasive action.
315      * </p>
316      */

317     public void exit( int exitStatus )
318     {
319         Runtime.getRuntime().exit( exitStatus );
320     }
321
322     /////////////////////////////////////////////////////////////
323
//
324
// CONNECTION MANAGEMENT
325
//
326
/////////////////////////////////////////////////////////////
327

328     /**
329      * <p>
330      * Load a client driver, given its particulars.
331      * </p>
332      */

333     protected static boolean faultInDriver( String JavaDoc[] clientSettings )
334     {
335         String JavaDoc currentClientName = clientSettings[ DRIVER_NAME ];
336         
337         try {
338             Class.forName( currentClientName );
339
340             return true;
341         }
342         catch (Exception JavaDoc e)
343         {
344             println( "Could not find " + currentClientName );
345             return false;
346         }
347     }
348
349     /**
350      * <p>
351      * Get a connection to a database, using the default client.
352      * </p>
353      */

354     protected static Connection getConnection()
355         throws Exception JavaDoc
356     {
357         return getConnection( _defaultClientSettings, _databaseName, new Properties() );
358     }
359     /**
360      * <p>
361      * Get a connection to a database, using the specified client.
362      * </p>
363      */

364     protected static Connection getConnection
365     (
366         String JavaDoc[] clientSettings,
367         String JavaDoc databaseName,
368         Properties properties
369     )
370         throws Exception JavaDoc
371     {
372         faultInDriver( clientSettings );
373
374         properties.put( "user", DEFAULT_USER_NAME );
375         properties.put( "password", DEFAULT_PASSWORD );
376         properties.put( "retreiveMessagesFromServerOnGetMessage", "true" );
377
378         Connection conn = DriverManager.getConnection
379             ( makeDatabaseURL( clientSettings, databaseName ), properties );
380
381         println( "Connection is a " + conn.getClass().getName() );
382         
383         return conn;
384     }
385
386     /**
387      * <p>
388      * Cobble together a connection URL.
389      * </p>
390      */

391     private static String JavaDoc makeDatabaseURL( String JavaDoc[] clientSettings, String JavaDoc databaseName )
392     {
393         return clientSettings[ DATABASE_URL ] + databaseName;
394     }
395
396     /**
397      * <p>
398      * Create an empty database.
399      * </p>
400      */

401     protected void createDB( String JavaDoc databaseName )
402         throws Exception JavaDoc
403     {
404         String JavaDoc[] clientSettings = getClientSettings();
405         String JavaDoc dbURL = makeDatabaseURL( clientSettings, databaseName );
406
407         dbURL = dbURL + ';' + CREATE_PROPERTY;
408
409         Properties properties = new Properties();
410
411         properties.put( "user", DEFAULT_USER_NAME );
412         properties.put( "password", DEFAULT_PASSWORD );
413
414         faultInDriver( clientSettings );
415
416         Connection conn = DriverManager.getConnection( dbURL, properties );
417
418         conn.close();
419     }
420
421     ///////////////
422
//
423
// SQL MINIONS
424
//
425
///////////////
426

427     /**
428      * <p>
429      * Execute DDL statement.
430      * </p>
431      */

432     protected static void executeDDL( Connection conn, String JavaDoc text )
433         throws SQLException
434     {
435         PreparedStatement ps = null;
436
437         try {
438             ps = prepare( conn, text );
439
440             ps.execute();
441         }
442         finally { close( ps ); }
443     }
444     
445     /**
446      * <p>
447      * Execute a SQL statement, given by the text argument. This thin
448      * wrapper around the JDBC machinery logs the statement text when
449      * running in debug mode.
450      * </p>
451      */

452     protected static void execute( Connection conn, String JavaDoc text )
453         throws SQLException
454     {
455         PreparedStatement ps = prepare( conn, text );
456
457         ps.execute();
458         close( ps );
459     }
460
461     /**
462      * <p>
463      * Prepare a SQL statement, given by the text argument. This thin
464      * wrapper around the JDBC machinery logs the statement text when
465      * running in debug mode.
466      * </p>
467      */

468     protected static PreparedStatement prepare( Connection conn, String JavaDoc text )
469         throws SQLException
470     {
471         println( "Preparing: " + text );
472
473         return conn.prepareStatement( text );
474     }
475
476     /**
477      * <p>
478      * Prepare a SQL call statement, given by the text argument. This thin
479      * wrapper around the JDBC machinery logs the statement text when
480      * running in debug mode.
481      * </p>
482      */

483     protected static CallableStatement prepareCall( Connection conn, String JavaDoc text )
484         throws SQLException
485     {
486         println( "Preparing procedure call: '" + text + "'" );
487
488         CallableStatement cs = conn.prepareCall( text );
489
490         return cs;
491     }
492
493     /**
494      * <p>
495      * Scour out all the rows from a table.
496      * </p>
497      */

498     protected static void truncateTable( Connection conn, String JavaDoc name )
499         throws SQLException
500     {
501         PreparedStatement ps = prepare( conn, "delete from " + name );
502
503         ps.execute();
504     }
505
506     /**
507      * <p>
508      * Drop a table regardless of whether it exists. If the table does not
509      * exist, don't log an error unless
510      * running in debug mode. This method is to be used for reinitializing
511      * a schema in case a previous test run failed to clean up after itself.
512      * Do not use this method if you need to verify that the table really exists.
513      * </p>
514      */

515     protected static void dropTable( Connection conn, String JavaDoc name )
516     {
517         dropSchemaObject( conn, TABLE, name );
518     }
519
520     /**
521      * <p>
522      * Drop a function regardless of whether it exists. If the function does not
523      * exist, don't log an error unless
524      * running in debug mode. This method is to be used for reinitializing
525      * a schema in case a previous test run failed to clean up after itself.
526      * Do not use this method if you need to verify that the function really exists.
527      * </p>
528      */

529     protected static void dropFunction( Connection conn, String JavaDoc name )
530     {
531         dropSchemaObject( conn, FUNCTION, name );
532     }
533
534     /**
535      * <p>
536      * Drop a procedure regardless of whether it exists. If the procedure does
537      * not exist, don't log an error unless
538      * running in debug mode. This method is to be used for reinitializing
539      * a schema in case a previous test run failed to clean up after itself.
540      * Do not use this method if you need to verify that the procedure really exists.
541      * </p>
542      */

543     protected static void dropProcedure( Connection conn, String JavaDoc name )
544     {
545         dropSchemaObject( conn, PROCEDURE, name );
546     }
547
548     /**
549      * <p>
550      * Drop a schema object regardless of whether it exists. If the object does
551      * not exist, don't log an error unless
552      * running in debug mode. This method is to be used for reinitializing
553      * a schema in case a previous test run failed to clean up after itself.
554      * Do not use this method if you need to verify that the object really exists.
555      * </p>
556      */

557     protected static void dropSchemaObject( Connection conn, String JavaDoc genus, String JavaDoc objectName )
558     {
559         PreparedStatement ps = null;
560         
561         try {
562             ps = prepare( conn, "drop " + genus + " " + objectName );
563
564             ps.execute();
565         }
566         catch (SQLException e)
567         {
568             if ( _debug ) { printStackTrace( e ); }
569         }
570
571         close( ps );
572     }
573
574     /**
575      * <p>
576      * Close a ResultSet. This method factors out the check for whether
577      * the ResultSet was created in the first place. This tidies up the
578      * caller's cleanup logic. If an error occurs, print it. Because this
579      * method swallows the exception after printing it, do not call this
580      * method if you want your test to halt on error.
581      * </p>
582      */

583     protected static void close( ResultSet rs )
584     {
585         try {
586             if ( rs != null ) { rs.close(); }
587         }
588         catch (SQLException e) { printStackTrace( e ); }
589     }
590
591     /**
592      * <p>
593      * Close a Statement. This method factors out the check for whether
594      * the Statement was created in the first place. This tidies up the
595      * caller's cleanup logic. If an error occurs, print it. Because this
596      * method swallows the exception after printing it, do not call this
597      * method if you want your test to halt on error.
598      * </p>
599      */

600     protected static void close( Statement statement )
601     {
602         try {
603             if ( statement != null ) { statement.close(); }
604         }
605         catch (SQLException e) { printStackTrace( e ); }
606     }
607
608     /**
609      * <p>
610      * Close a Connection. This method factors out the check for whether
611      * the Connection was created in the first place. This tidies up the
612      * caller's cleanup logic. If an error occurs, print it. Because this
613      * method swallows the exception after printing it, do not call this
614      * method if you want your test to halt on error.
615      * </p>
616      */

617     protected static void close( Connection conn )
618     {
619         try {
620             if ( conn != null ) { conn.close(); }
621         }
622         catch (SQLException e) { printStackTrace( e ); }
623     }
624
625     /**
626      * <p>
627      * Read a column from a ResultSet given its column name and expected jdbc
628      * type. This method is useful if you are want to verify the getXXX() logic
629      * most naturally fitting the declared SQL type.
630      * </p>
631      */

632     protected Object JavaDoc getColumn( ResultSet rs, String JavaDoc columnName, int jdbcType )
633         throws Exception JavaDoc
634     {
635         Object JavaDoc retval = null;
636
637         switch( jdbcType )
638         {
639             case JDBC_BOOLEAN:
640                 retval = new Boolean JavaDoc( rs.getBoolean( columnName ) );
641                 break;
642                 
643             case Types.BIGINT:
644                 retval = new Long JavaDoc( rs.getLong( columnName ) );
645                 break;
646                 
647             case Types.BLOB:
648                 retval = rs.getBlob( columnName );
649                 break;
650                 
651             case Types.CHAR:
652             case Types.LONGVARCHAR:
653             case Types.VARCHAR:
654                 retval = rs.getString( columnName );
655                 break;
656                 
657             case Types.BINARY:
658             case Types.LONGVARBINARY:
659             case Types.VARBINARY:
660                 retval = rs.getBytes( columnName );
661                 break;
662                 
663             case Types.CLOB:
664                 retval = rs.getClob( columnName );
665                 break;
666                 
667             case Types.DATE:
668                 retval = rs.getDate( columnName );
669                 break;
670                 
671             case Types.DECIMAL:
672             case Types.NUMERIC:
673                 retval = rs.getBigDecimal( columnName );
674                 break;
675                 
676             case Types.DOUBLE:
677                 retval = new Double JavaDoc( rs.getDouble( columnName ) );
678                 break;
679                 
680             case Types.REAL:
681                 retval = new Float JavaDoc( rs.getFloat( columnName ) );
682                 break;
683                 
684             case Types.INTEGER:
685                 retval = new Integer JavaDoc( rs.getInt( columnName ) );
686                 break;
687                 
688             case Types.SMALLINT:
689                 retval = new Short JavaDoc( rs.getShort( columnName ) );
690                 break;
691                 
692             case Types.TIME:
693                 retval = rs.getTime( columnName );
694                 break;
695                 
696             case Types.TIMESTAMP:
697                 retval = rs.getTimestamp( columnName );
698                 break;
699                 
700             default:
701                 fail( "Unknown jdbc type " + jdbcType + " used to retrieve column: " + columnName );
702                 break;
703         }
704
705         if ( rs.wasNull() ) { retval = null; }
706
707         return retval;
708     }
709
710     /**
711      * <p>
712      * Read a column from a ResultSet given its column position
713      * and an expected Java type. This method is useful when
714      * comparing ResultSets against expected values.
715      * </p>
716      *
717      * @param rs The ResultSet to read.
718      * @param param The column number (1-based)
719      * @param value An object whose type is what we expect the column to be.
720      */

721     protected Object JavaDoc getColumn( ResultSet rs, int param, Object JavaDoc value )
722         throws Exception JavaDoc
723     {
724         Object JavaDoc retval;
725         
726         if ( value == null )
727         {
728             retval = rs.getObject( param );
729         }
730         else if ( value instanceof Boolean JavaDoc ) { retval = new Boolean JavaDoc( rs.getBoolean( param ) ); }
731         else if ( value instanceof Byte JavaDoc ) { retval = new Byte JavaDoc( rs.getByte( param ) ); }
732         else if ( value instanceof Short JavaDoc ) { retval = new Short JavaDoc( rs.getShort( param ) ); }
733         else if ( value instanceof Integer JavaDoc ) { retval = new Integer JavaDoc( rs.getInt( param ) ); }
734         else if ( value instanceof Long JavaDoc ) { retval = new Long JavaDoc( rs.getLong( param ) ); }
735         else if ( value instanceof Float JavaDoc ) { retval = new Float JavaDoc( rs.getFloat( param ) ); }
736         else if ( value instanceof Double JavaDoc ) { retval = new Double JavaDoc( rs.getDouble( param ) ); }
737         else if ( value instanceof String JavaDoc ) { retval = rs.getString( param ); }
738         else if ( value instanceof BigDecimal ) { retval = rs.getBigDecimal( param ); }
739         else { retval = rs.getObject( param ); }
740
741         if ( rs.wasNull() ) { retval = null; }
742
743         return retval;
744     }
745     
746     /**
747      * <p>
748      * Read an output argument from a CallableStatement given its 1-based
749      * argument position and expected jdbc type. This is useful for
750      * exercising the getXXX() methods most natural to a declared SQL type.
751      * </p>
752      */

753     protected Object JavaDoc getOutArg( CallableStatement cs, int arg, int jdbcType )
754         throws Exception JavaDoc
755     {
756         Object JavaDoc retval = null;
757
758         switch( jdbcType )
759         {
760             case JDBC_BOOLEAN:
761                 retval = new Boolean JavaDoc( cs.getBoolean( arg ) );
762                 break;
763                 
764             case Types.BIGINT:
765                 retval = new Long JavaDoc( cs.getLong( arg ) );
766                 break;
767                 
768             case Types.BLOB:
769                 retval = cs.getBlob( arg );
770                 break;
771                 
772             case Types.CHAR:
773             case Types.LONGVARCHAR:
774             case Types.VARCHAR:
775                 retval = cs.getString( arg );
776                 break;
777                 
778             case Types.BINARY:
779             case Types.LONGVARBINARY:
780             case Types.VARBINARY:
781                 retval = cs.getBytes( arg );
782                 break;
783                 
784             case Types.CLOB:
785                 retval = cs.getClob( arg );
786                 break;
787                 
788             case Types.DATE:
789                 retval = cs.getDate( arg );
790                 break;
791                 
792             case Types.DECIMAL:
793             case Types.NUMERIC:
794                 retval = cs.getBigDecimal( arg );
795                 break;
796                 
797             case Types.DOUBLE:
798                 retval = new Double JavaDoc( cs.getDouble( arg ) );
799                 break;
800                 
801             case Types.REAL:
802                 retval = new Float JavaDoc( cs.getFloat( arg ) );
803                 break;
804                 
805             case Types.INTEGER:
806                 retval = new Integer JavaDoc( cs.getInt( arg ) );
807                 break;
808                 
809             case Types.SMALLINT:
810                 retval = new Short JavaDoc( cs.getShort( arg ) );
811                 break;
812                 
813             case Types.TIME:
814                 retval = cs.getTime( arg );
815                 break;
816                 
817             case Types.TIMESTAMP:
818                 retval = cs.getTimestamp( arg );
819                 break;
820                 
821             default:
822                 fail( "Unknown jdbc type " + jdbcType + " used to retrieve column: " + arg );
823                 break;
824         }
825
826         if ( cs.wasNull() ) { retval = null; }
827
828         return retval;
829     }
830
831     /**
832      * <p>
833      * Stuff a PreparedStatement parameter given its 1-based parameter position
834      * and expected jdbc type. This method is useful for testing the setXXX()
835      * methods most natural for a declared SQL type.
836      * </p>
837      */

838     protected void setParameter( PreparedStatement ps, int param, int jdbcType, Object JavaDoc value )
839         throws Exception JavaDoc
840     {
841         if ( value == null )
842         {
843             ps.setNull( param, jdbcType );
844
845             return;
846         }
847
848         switch( jdbcType )
849         {
850             case JDBC_BOOLEAN:
851                 ps.setBoolean( param, ((Boolean JavaDoc) value ).booleanValue() );
852                 break;
853                 
854             case Types.BIGINT:
855                 ps.setLong( param, ((Long JavaDoc) value ).longValue() );
856                 break;
857                 
858             case Types.BLOB:
859                 ps.setBlob( param, ((Blob) value ) );
860                 break;
861                 
862             case Types.CHAR:
863             case Types.LONGVARCHAR:
864             case Types.VARCHAR:
865                 ps.setString( param, ((String JavaDoc) value ) );
866                 break;
867                 
868             case Types.BINARY:
869             case Types.LONGVARBINARY:
870             case Types.VARBINARY:
871                 ps.setBytes( param, (byte[]) value );
872                 break;
873                 
874             case Types.CLOB:
875                 ps.setClob( param, ((Clob) value ) );
876                 break;
877                 
878             case Types.DATE:
879                 ps.setDate( param, ((java.sql.Date JavaDoc) value ) );
880                 break;
881                 
882             case Types.DECIMAL:
883             case Types.NUMERIC:
884                 ps.setBigDecimal( param, ((BigDecimal) value ) );
885                 break;
886                 
887             case Types.DOUBLE:
888                 ps.setDouble( param, ((Double JavaDoc) value ).doubleValue() );
889                 break;
890                 
891             case Types.REAL:
892                 ps.setFloat( param, ((Float JavaDoc) value ).floatValue() );
893                 break;
894                 
895             case Types.INTEGER:
896                 ps.setInt( param, ((Integer JavaDoc) value ).intValue() );
897                 break;
898                 
899             case Types.SMALLINT:
900                 ps.setShort( param, ((Short JavaDoc) value ).shortValue() );
901                 break;
902                 
903             case Types.TIME:
904                 ps.setTime( param, (Time) value );
905                 break;
906                 
907             case Types.TIMESTAMP:
908                 ps.setTimestamp( param, (Timestamp) value );
909                 break;
910                 
911             default:
912                 fail( "Unknown jdbc type: " + jdbcType );
913                 break;
914         }
915
916     }
917     
918     /**
919      * <p>
920      * Stuff a PreparedStatement parameter given its 1-based parameter position.
921      * The appropriate setXXX() method is determined by the Java type of the
922      * value being stuffed. This method is useful for testing setXXX() methods
923      * other than the most natural fit for the declared SQL type.
924      * </p>
925      */

926     protected void setParameter( PreparedStatement ps, int param, Object JavaDoc value )
927         throws Exception JavaDoc
928     {
929         if ( value == null )
930         {
931             ps.setObject( param, null );
932
933             return;
934         }
935
936         if ( value instanceof Boolean JavaDoc ) { ps.setBoolean( param, ((Boolean JavaDoc) value).booleanValue() ); }
937         else if ( value instanceof Byte JavaDoc ) { ps.setByte( param, ((Byte JavaDoc) value).byteValue() ); }
938         else if ( value instanceof Short JavaDoc ) { ps.setShort( param, ((Short JavaDoc) value).shortValue() ); }
939         else if ( value instanceof Integer JavaDoc ) { ps.setInt( param, ((Integer JavaDoc) value).intValue() ); }
940         else if ( value instanceof Long JavaDoc ) { ps.setLong( param, ((Long JavaDoc) value).longValue() ); }
941         else if ( value instanceof Float JavaDoc ) { ps.setFloat( param, ((Float JavaDoc) value).floatValue() ); }
942         else if ( value instanceof Double JavaDoc ) { ps.setDouble( param, ((Double JavaDoc) value).doubleValue() ); }
943         else if ( value instanceof String JavaDoc ) { ps.setString( param, ((String JavaDoc) value) ); }
944         else { ps.setObject( param, value ); }
945     }
946     
947
948     ////////////////////
949
//
950
// QUERY GENERATION
951
//
952
////////////////////
953

954     /**
955      * <p>
956      * Single quote a string. This is a helper routine for use in generating
957      * SQL text.
958      * </p>
959      */

960     protected String JavaDoc singleQuote( String JavaDoc text )
961     {
962         return "'" + text + "'";
963     }
964
965     /////////////////////////////////////////////////////////////
966
//
967
// EXTRA ASSERTIONS
968
//
969
/////////////////////////////////////////////////////////////
970

971     /**
972      * <p>
973      * Assert the values of a whole row.
974      * </p>
975      */

976     public void assertRow
977         ( ResultSet rs, Object JavaDoc[] expectedRow )
978         throws Exception JavaDoc
979     {
980         int count = expectedRow.length;
981
982         for ( int i = 0; i < count; i++ )
983         {
984             int columnNumber = i + 1;
985             Object JavaDoc expected = expectedRow[ i ];
986             Object JavaDoc actual = getColumn( rs, columnNumber, expected );
987
988             compareObjects( "Column number " + columnNumber, expected, actual );
989         }
990     }
991
992
993     /**
994      * <p>
995      * Assert a scalar result from a query.
996      * </p>
997      */

998     public void assertScalar
999         ( Connection conn, String JavaDoc queryText, Object JavaDoc expectedResult )
1000        throws Exception JavaDoc
1001    {
1002        PreparedStatement ps = prepare( conn, queryText );
1003        ResultSet rs = ps.executeQuery();
1004
1005        rs.next();
1006
1007        assertColumnEquals( queryText, rs, 1, expectedResult );
1008
1009        close( rs );
1010        close( ps );
1011    }
1012
1013    /**
1014     * <p>
1015     * Assert the values in a ResultSet for a given column across all rows.
1016     * </p>
1017     */

1018    public void assertColumnEquals
1019        ( ResultSet rs, int columnNumber, Object JavaDoc[] expectedValues )
1020        throws Exception JavaDoc
1021    {
1022        int count = expectedValues.length;
1023
1024        for ( int i = 0; i < count; i++ )
1025        {
1026            rs.next();
1027            assertColumnEquals( Integer.toString( i ), rs, columnNumber, expectedValues[ i ] );
1028        }
1029    }
1030
1031    /**
1032     * <p>
1033     * Assert a column's value.
1034     * </p>
1035     */

1036    public void assertColumnEquals
1037        ( String JavaDoc message, ResultSet rs, int columnNumber, Object JavaDoc expectedValue )
1038        throws Exception JavaDoc
1039    {
1040        Object JavaDoc actualValue = getColumn( rs, columnNumber, expectedValue );
1041
1042        compareObjects( message, expectedValue, actualValue );
1043    }
1044
1045    /**
1046     * <p>
1047     * Assert two objects are equal, allowing nulls to be equal.
1048     * </p>
1049     */

1050    public void compareObjects( String JavaDoc message, Object JavaDoc left, Object JavaDoc right )
1051        throws Exception JavaDoc
1052    {
1053        message = message + "\n\t expected = " + left + "\n\t actual = " + right;
1054        
1055        if ( left == null )
1056        {
1057            assertNull( message, right );
1058        }
1059        else
1060        {
1061            assertNotNull( message, right );
1062
1063            if ( left instanceof byte[] ) { compareBytes( message, left, right ); }
1064            else if ( left instanceof java.util.Date JavaDoc ) { compareDates( message, left, right ); }
1065            else { assertTrue( message, left.equals( right ) ); }
1066        }
1067    }
1068
1069    /**
1070     * <p>
1071     * Assert two byte arrays are equal, allowing nulls to be equal.
1072     * </p>
1073     */

1074    public void compareBytes( String JavaDoc message, Object JavaDoc left, Object JavaDoc right )
1075        throws Exception JavaDoc
1076    {
1077        if ( left == null ) { assertNull( message, right ); }
1078        else { assertNotNull( right ); }
1079
1080        if ( !(left instanceof byte[] ) ) { fail( message ); }
1081        if ( !(right instanceof byte[] ) ) { fail( message ); }
1082
1083        byte[] leftBytes = (byte[]) left;
1084        byte[] rightBytes = (byte[]) right;
1085        int count = leftBytes.length;
1086
1087        assertEquals( message, count, rightBytes.length );
1088        
1089        for ( int i = 0; i < count; i++ )
1090        {
1091            assertEquals( message + "[ " + i + " ]", leftBytes[ i ], rightBytes[ i ] );
1092        }
1093    }
1094
1095    /**
1096     * <p>
1097     * Assert two Dates are equal, allowing nulls to be equal.
1098     * </p>
1099     */

1100    public void compareDates( String JavaDoc message, Object JavaDoc left, Object JavaDoc right )
1101        throws Exception JavaDoc
1102    {
1103        if ( left == null ) { assertNull( message, right ); }
1104        else { assertNotNull( right ); }
1105
1106        if ( !(left instanceof java.util.Date JavaDoc ) ) { fail( message ); }
1107        if ( !(right instanceof java.util.Date JavaDoc ) ) { fail( message ); }
1108
1109        assertEquals( message, left.toString(), right.toString() );
1110    }
1111    
1112}
1113
1114
Popular Tags