KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2
3    Derby - Class org.apache.derbyTesting.functionTests.util.TestUtil
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 package org.apache.derbyTesting.functionTests.util;
24
25 import java.sql.*;
26 import java.io.*;
27 import java.lang.reflect.*;
28 import java.util.Enumeration JavaDoc;
29 import java.util.Hashtable JavaDoc;
30 import java.util.Locale JavaDoc;
31 import java.util.Properties JavaDoc;
32 import java.util.StringTokenizer JavaDoc;
33 import java.util.NoSuchElementException JavaDoc;
34 import java.security.AccessController JavaDoc;
35 import java.security.PrivilegedAction JavaDoc;
36 import java.security.PrivilegedExceptionAction JavaDoc;
37 import java.security.PrivilegedActionException JavaDoc;
38 import javax.sql.DataSource JavaDoc;
39
40 import org.apache.derby.iapi.reference.JDBC30Translation;
41 import org.apache.derby.iapi.services.info.JVMInfo;
42 import org.apache.derbyTesting.functionTests.harness.RunTest;
43
44
45
46
47 /**
48     Utility methods for tests, in order to bring some consistency to test
49     output and handle testing framework differences
50
51 */

52 public class TestUtil {
53     
54     //Used for JSR169
55
public static boolean HAVE_DRIVER_CLASS;
56     static{
57         try{
58             Class.forName("java.sql.Driver");
59             HAVE_DRIVER_CLASS = true;
60         }
61         catch(ClassNotFoundException JavaDoc e){
62             //Used for JSR169
63
HAVE_DRIVER_CLASS = false;
64         }
65     }
66
67     public static final int UNKNOWN_FRAMEWORK = -1;
68
69     /**
70        framework = embedded (or null) jdbc:derby:
71     */

72     public static final int EMBEDDED_FRAMEWORK = 0;
73     
74     /**
75        framework = DerbyNet for JCC jdbc:derby:net:
76     */

77     public static final int DERBY_NET_FRAMEWORK = 1;
78
79     /**
80        framework = DB2JCC for testing JCC against DB2 for
81        debugging jcc problems jdbc:db2://
82     */

83
84     public static final int DB2JCC_FRAMEWORK = 2; // jdbc:db2//
85

86     /**
87        framework = DerbyNetClient for Derby cient jdbc:derby://
88     */

89     public static final int DERBY_NET_CLIENT_FRAMEWORK = 3; // jdbc:derby://
90

91
92     /**
93        framework = DB2jNet
94        OLD_NET_FRAMEWORK is for tests that have not yet been contributed.
95        it can be removed once all tests are at apache
96     */

97     public static final int OLD_NET_FRAMEWORK = 4; // jdbc:derby:net:
98

99
100     private static int framework = UNKNOWN_FRAMEWORK;
101
102
103     // DataSource Type strings used to build up datasource names.
104
// e.g. "Embed" + XA_DATASOURCE_STRING + "DataSource
105
private static String JavaDoc XA_DATASOURCE_STRING = "XA";
106     private static String JavaDoc CONNECTION_POOL_DATASOURCE_STRING = "ConnectionPool";
107     private static String JavaDoc REGULAR_DATASOURCE_STRING = "";
108     private static String JavaDoc JSR169_DATASOURCE_STRING = "Simple";
109     
110     // Methods for making framework dependent decisions in tests.
111

112     /**
113      * Is this a network testingframework?
114      * return true if the System Property framework is set to Derby Network
115      * client or JCC
116      *
117      * @return true if this is a Network Server test
118      */

119     public static boolean isNetFramework()
120     {
121         framework = getFramework();
122         switch (framework)
123         {
124             case DERBY_NET_FRAMEWORK:
125             case DERBY_NET_CLIENT_FRAMEWORK:
126             case DB2JCC_FRAMEWORK:
127             case OLD_NET_FRAMEWORK:
128                 return true;
129             default:
130                 return false;
131         }
132     }
133             
134     /**
135         Is the JCC driver being used
136       
137         @return true for JCC driver
138     */

139     public static boolean isJCCFramework()
140     {
141         int framework = getFramework();
142         switch (framework)
143         {
144             case DERBY_NET_FRAMEWORK:
145             case DB2JCC_FRAMEWORK:
146             case OLD_NET_FRAMEWORK:
147                 return true;
148         }
149         return false;
150     }
151
152     public static boolean isDerbyNetClientFramework()
153     {
154         return (getFramework() == DERBY_NET_CLIENT_FRAMEWORK);
155     }
156
157     public static boolean isEmbeddedFramework()
158     {
159         return (getFramework() == EMBEDDED_FRAMEWORK);
160     }
161
162     /**
163        Get the framework from the System Property framework
164        @return constant for framework being used
165            TestUtil.EMBEDDED_FRAMEWORK for embedded
166            TestUtil.DERBY_NET_CLIENT_FRAMEWORK for Derby Network Client
167            TestUtil.DERBY_NET_FRAMEWORK for JCC to Network Server
168            TestUtil.DB2JCC_FRAMEWORK for JCC to DB2
169     */

170     private static int getFramework()
171     {
172         if (framework != UNKNOWN_FRAMEWORK)
173             return framework;
174               String JavaDoc frameworkString = (String JavaDoc) AccessController.doPrivileged
175                   (new PrivilegedAction JavaDoc() {
176                           public Object JavaDoc run() {
177                               return System.getProperty("framework");
178                           }
179                       }
180                    );
181         // last attempt to get useprocess to do networkserver stuff.
182
// If a suite has useprocess, it's possible there was no property set.
183
if (frameworkString == null)
184         {
185            String JavaDoc useprocessFramework = RunTest.framework;
186            if (useprocessFramework != null)
187             frameworkString = useprocessFramework;
188         }
189         if (frameworkString == null ||
190            frameworkString.toUpperCase(Locale.ENGLISH).equals("EMBEDDED"))
191             framework = EMBEDDED_FRAMEWORK;
192         else if (frameworkString.toUpperCase(Locale.ENGLISH).equals("DERBYNETCLIENT"))
193             framework = DERBY_NET_CLIENT_FRAMEWORK;
194         else if (frameworkString.toUpperCase(Locale.ENGLISH).equals("DERBYNET"))
195             framework = DERBY_NET_FRAMEWORK;
196         else if (frameworkString.toUpperCase(Locale.ENGLISH).indexOf("DB2JNET") != -1)
197             framework = OLD_NET_FRAMEWORK;
198
199         return framework;
200
201     }
202
203     /**
204         Get URL prefix for current framework.
205         
206         @return url, assume localhost - unless set differently in System property -
207                      and assume port 1527 for Network Tests
208         @see getJdbcUrlPrefix(String server, int port)
209         
210     */

211     public static String JavaDoc getJdbcUrlPrefix()
212     {
213         String JavaDoc hostName=getHostName();
214         return getJdbcUrlPrefix(hostName, 1527);
215     }
216
217     /** Get hostName as passed in - if not, set it to "localhost"
218         @return hostName, as passed into system properties, or "localhost"
219     */

220     public static String JavaDoc getHostName()
221     {
222         String JavaDoc hostName = (String JavaDoc) AccessController.doPrivileged
223             (new PrivilegedAction JavaDoc() {
224                     public Object JavaDoc run() {
225                         return System.getProperty("hostName");
226                     }
227                 }
228              );
229         if (hostName == null)
230             hostName="localhost";
231         return hostName;
232     }
233
234     /**
235         Get URL prefix for current framework
236         
237         @param server host to connect to with client driver
238                        ignored for embedded driver
239         @param port port to connect to with client driver
240                        ignored with embedded driver
241         @return URL prefix
242                 EMBEDDED_FRAMEWORK returns "jdbc:derby"
243                 DERBY_NET_FRAMEWORK = "jdbc:derby:net://<server>:port/"
244                 DERBY_NET_CLIENT_FRAMEWORK = "jdbc:derby://<server>:port/"
245                 DB2_JCC_FRAMEWORK = "jdbc:db2://<server>:port/"
246     */

247     public static String JavaDoc getJdbcUrlPrefix(String JavaDoc server, int port)
248     {
249         int framework = getFramework();
250         switch (framework)
251         {
252             case EMBEDDED_FRAMEWORK:
253                 return "jdbc:derby:";
254             case DERBY_NET_FRAMEWORK:
255             case OLD_NET_FRAMEWORK:
256                 return "jdbc:derby:net://" + server + ":" + port + "/";
257             case DERBY_NET_CLIENT_FRAMEWORK:
258                 return "jdbc:derby://" + server + ":" + port + "/";
259             case DB2JCC_FRAMEWORK:
260                 return "jdbc:db2://" + server + ":" + port + "/";
261         }
262         // Unknown framework
263
return null;
264         
265     }
266
267     /**
268        Load the appropriate driver for the current framework
269     */

270     public static void loadDriver() throws Exception JavaDoc
271     {
272               final String JavaDoc driverName;
273         framework = getFramework();
274         switch (framework)
275         {
276             case EMBEDDED_FRAMEWORK:
277                 driverName = "org.apache.derby.jdbc.EmbeddedDriver";
278                 break;
279             case DERBY_NET_FRAMEWORK:
280             case OLD_NET_FRAMEWORK:
281             case DB2JCC_FRAMEWORK:
282                 driverName = "com.ibm.db2.jcc.DB2Driver";
283                 break;
284             case DERBY_NET_CLIENT_FRAMEWORK:
285                 driverName = "org.apache.derby.jdbc.ClientDriver";
286                 break;
287                       default:
288                             driverName= "org.apache.derby.jdbc.EmbeddedDriver";
289                             break;
290         }
291                                 
292               try {
293                   AccessController.doPrivileged
294                       (new PrivilegedExceptionAction JavaDoc() {
295                               public Object JavaDoc run() throws Exception JavaDoc {
296                                   return Class.forName(driverName).newInstance();
297                               }
298                           }
299                        );
300               } catch (PrivilegedActionException JavaDoc e) {
301                   throw e.getException();
302               }
303         }
304
305
306     /**
307      * Get a data source for the appropriate framework
308      * @param attrs A set of attribute values to set on the datasource.
309      * The appropriate setter method wil b
310      * For example the property databaseName with value wombat,
311      * will mean ds.setDatabaseName("wombat") will be called
312      * @return datasource for current framework
313      */

314     public static javax.sql.DataSource JavaDoc getDataSource(Properties JavaDoc attrs)
315     {
316         String JavaDoc classname;
317         if(HAVE_DRIVER_CLASS)
318         {
319             classname = getDataSourcePrefix() + REGULAR_DATASOURCE_STRING + "DataSource";
320             classname = checkForJDBC40Implementation(classname);
321             return (javax.sql.DataSource JavaDoc) getDataSourceWithReflection(classname, attrs);
322         }
323         else
324             return getSimpleDataSource(attrs);
325         
326     }
327
328     public static DataSource JavaDoc getSimpleDataSource(Properties JavaDoc attrs)
329     {
330         String JavaDoc classname = getDataSourcePrefix() + JSR169_DATASOURCE_STRING + "DataSource";
331         return (javax.sql.DataSource JavaDoc) getDataSourceWithReflection(classname, attrs);
332     }
333     
334     /**
335      * Get an xa data source for the appropriate framework
336      * @param attrs A set of attribute values to set on the datasource.
337      * The appropriate setter method wil b
338      * For example the property databaseName with value wombat,
339      * will mean ds.setDatabaseName("wombat") will be called
340      * @return datasource for current framework
341      */

342     public static javax.sql.XADataSource JavaDoc getXADataSource(Properties JavaDoc attrs)
343     {
344         
345         String JavaDoc classname = getDataSourcePrefix() + XA_DATASOURCE_STRING + "DataSource";
346         classname = checkForJDBC40Implementation(classname);
347         return (javax.sql.XADataSource JavaDoc) getDataSourceWithReflection(classname, attrs);
348     }
349
350     
351     /**
352      * Get a ConnectionPoolDataSource for the appropriate framework
353      * @param attrs A set of attribute values to set on the datasource.
354      * The appropriate setter method wil b
355      * For example the property databaseName with value wombat,
356      * will mean ds.setDatabaseName("wombat") will be called
357      * @return datasource for current framework
358      */

359     public static javax.sql.ConnectionPoolDataSource JavaDoc getConnectionPoolDataSource(Properties JavaDoc attrs)
360     {
361         String JavaDoc classname = getDataSourcePrefix() + CONNECTION_POOL_DATASOURCE_STRING + "DataSource";
362                 classname = checkForJDBC40Implementation(classname);
363         return (javax.sql.ConnectionPoolDataSource JavaDoc) getDataSourceWithReflection(classname, attrs);
364     }
365         
366         /**
367          * returns the class name for the JDBC40 implementation
368          * if present. otherwise returns the class name of the class
369          * written for the lower jdk versions
370          * @param classname String
371          * @return String containing the name of the appropriate
372          * implementation
373          */

374         public static String JavaDoc checkForJDBC40Implementation(String JavaDoc classname) {
375                 String JavaDoc classname_ = classname;
376                 // The JDBC 4.0 implementation of the
377
// interface is suffixed with "40". Use it if it is available
378
// and the JVM version is at least 1.6.
379
if (JVMInfo.JDK_ID >= JVMInfo.J2SE_16) {
380                         String JavaDoc classname40 = classname_ + "40";
381                         try {
382                                 Class.forName(classname40);
383                                 classname_ = classname40;
384                         } catch (ClassNotFoundException JavaDoc e) {}
385                 }
386                 return classname_;
387         }
388
389     public static String JavaDoc getDataSourcePrefix()
390         {
391             framework = getFramework();
392             switch(framework)
393             {
394                 case OLD_NET_FRAMEWORK:
395                 case DERBY_NET_FRAMEWORK:
396                 case DB2JCC_FRAMEWORK:
397                     return "com.ibm.db2.jcc.DB2";
398                 case DERBY_NET_CLIENT_FRAMEWORK:
399                     return "org.apache.derby.jdbc.Client";
400                 case EMBEDDED_FRAMEWORK:
401                     return "org.apache.derby.jdbc.Embedded";
402                 default:
403                     Exception JavaDoc e = new Exception JavaDoc("FAIL: No DataSource Prefix for framework: " + framework);
404                     e.printStackTrace();
405             }
406             return null;
407         }
408
409
410
411     static private Class JavaDoc[] STRING_ARG_TYPE = {String JavaDoc.class};
412     static private Class JavaDoc[] INT_ARG_TYPE = {Integer.TYPE};
413     static private Class JavaDoc[] BOOLEAN_ARG_TYPE = { Boolean.TYPE };
414     // A hashtable of special non-string attributes.
415
private static Hashtable JavaDoc specialAttributes = null;
416     
417
418     private static Object JavaDoc getDataSourceWithReflection(String JavaDoc classname, Properties JavaDoc attrs)
419     {
420         Object JavaDoc[] args = null;
421         Object JavaDoc ds = null;
422         Method sh = null;
423         String JavaDoc methodName = null;
424         
425         if (specialAttributes == null)
426         {
427             specialAttributes = new Hashtable JavaDoc();
428             specialAttributes.put("portNumber",INT_ARG_TYPE);
429             specialAttributes.put("driverType",INT_ARG_TYPE);
430             specialAttributes.put("retrieveMessagesFromServerOnGetMessage",
431                                   BOOLEAN_ARG_TYPE);
432             specialAttributes.put("retrieveMessageText",
433                                   BOOLEAN_ARG_TYPE);
434         }
435         
436         try {
437         ds = Class.forName(classname).newInstance();
438
439         // for remote server testing, check whether the hostName is set for the test
440
// if so, and serverName is not yet set explicitly for the datasource, set it now
441
String JavaDoc hostName = getHostName();
442         if ( (!isEmbeddedFramework()) && (hostName != null ) && (attrs.getProperty("serverName") == null) )
443             attrs.setProperty("serverName", hostName);
444
445         for (Enumeration JavaDoc propNames = attrs.propertyNames();
446              propNames.hasMoreElements();)
447         {
448             String JavaDoc key = (String JavaDoc) propNames.nextElement();
449             Class JavaDoc[] argType = (Class JavaDoc[]) specialAttributes.get(key);
450             if (argType == null)
451                 argType = STRING_ARG_TYPE;
452             String JavaDoc value = attrs.getProperty(key);
453             if (argType == INT_ARG_TYPE)
454             {
455                 args = new Integer JavaDoc[]
456                 { new Integer JavaDoc(Integer.parseInt(value)) };
457             }
458             else if (argType == BOOLEAN_ARG_TYPE)
459             {
460                 args = new Boolean JavaDoc[] { new Boolean JavaDoc(value) };
461             }
462             else if (argType == STRING_ARG_TYPE)
463             {
464                 args = new String JavaDoc[] { value };
465             }
466             else // No other property types supported right now
467
{
468                 throw new Exception JavaDoc("FAIL: getDataSourceWithReflection: Argument type " + argType[0].getName() + " not supportted for attribute: " +
469                                     " key:" + key + " value:" +value);
470                
471             }
472             methodName = getSetterName(key);
473
474             
475             // Need to use reflection to load indirectly
476
// setDatabaseName
477
sh = ds.getClass().getMethod(methodName, argType);
478             sh.invoke(ds, args);
479         }
480
481         } catch (Exception JavaDoc e)
482         {
483             System.out.println("Error accessing method " + methodName);
484             System.out.println(e.getMessage());
485             e.printStackTrace();
486         }
487         return ds;
488     }
489
490     
491     public static String JavaDoc getSetterName(String JavaDoc attribute)
492     {
493         return "set" + Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1);
494     }
495
496     
497     public static String JavaDoc getGetterName(String JavaDoc attribute)
498     {
499         return "get" + Character.toUpperCase(attribute.charAt(0)) + attribute.substring(1);
500     }
501
502     // Some methods for test output.
503
public static void dumpSQLExceptions(SQLException sqle) {
504         TestUtil.dumpSQLExceptions(sqle, false);
505     }
506
507     public static void dumpSQLExceptions(SQLException sqle, boolean expected) {
508         String JavaDoc prefix = "";
509         if (!expected) {
510             System.out.println("FAIL -- unexpected exception ****************");
511         }
512         else
513         {
514             prefix = "EXPECTED ";
515         }
516
517         do
518         {
519             System.out.println(prefix + "SQLSTATE("+sqle.getSQLState()+"): " + sqle.getMessage());
520             sqle = sqle.getNextException();
521         } while (sqle != null);
522     }
523
524
525       public static String JavaDoc sqlNameFromJdbc(int jdbcType) {
526         switch (jdbcType) {
527             case Types.BIT : return "Types.BIT";
528             case JDBC30Translation.SQL_TYPES_BOOLEAN : return "Types.BOOLEAN";
529             case Types.TINYINT : return "Types.TINYINT";
530             case Types.SMALLINT : return "SMALLINT";
531             case Types.INTEGER : return "INTEGER";
532             case Types.BIGINT : return "BIGINT";
533
534             case Types.FLOAT : return "Types.FLOAT";
535             case Types.REAL : return "REAL";
536             case Types.DOUBLE : return "DOUBLE";
537
538             case Types.NUMERIC : return "Types.NUMERIC";
539             case Types.DECIMAL : return "DECIMAL";
540
541             case Types.CHAR : return "CHAR";
542             case Types.VARCHAR : return "VARCHAR";
543             case Types.LONGVARCHAR : return "LONG VARCHAR";
544             case Types.CLOB : return "CLOB";
545
546             case Types.DATE : return "DATE";
547             case Types.TIME : return "TIME";
548             case Types.TIMESTAMP : return "TIMESTAMP";
549
550             case Types.BINARY : return "CHAR () FOR BIT DATA";
551             case Types.VARBINARY : return "VARCHAR () FOR BIT DATA";
552             case Types.LONGVARBINARY : return "LONG VARCHAR FOR BIT DATA";
553             case Types.BLOB : return "BLOB";
554
555             case Types.OTHER : return "Types.OTHER";
556             case Types.NULL : return "Types.NULL";
557             default : return String.valueOf(jdbcType);
558         }
559     }
560       public static String JavaDoc getNameFromJdbcType(int jdbcType) {
561         switch (jdbcType) {
562             case Types.BIT : return "Types.BIT";
563             case JDBC30Translation.SQL_TYPES_BOOLEAN : return "Types.BOOLEAN";
564             case Types.TINYINT : return "Types.TINYINT";
565             case Types.SMALLINT : return "Types.SMALLINT";
566             case Types.INTEGER : return "Types.INTEGER";
567             case Types.BIGINT : return "Types.BIGINT";
568
569             case Types.FLOAT : return "Types.FLOAT";
570             case Types.REAL : return "Types.REAL";
571             case Types.DOUBLE : return "Types.DOUBLE";
572
573             case Types.NUMERIC : return "Types.NUMERIC";
574             case Types.DECIMAL : return "Types.DECIMAL";
575
576             case Types.CHAR : return "Types.CHAR";
577             case Types.VARCHAR : return "Types.VARCHAR";
578             case Types.LONGVARCHAR : return "Types.LONGVARCHAR";
579             case Types.CLOB : return "Types.CLOB";
580
581             case Types.DATE : return "Types.DATE";
582             case Types.TIME : return "Types.TIME";
583             case Types.TIMESTAMP : return "Types.TIMESTAMP";
584
585             case Types.BINARY : return "Types.BINARY";
586             case Types.VARBINARY : return "Types.VARBINARY";
587             case Types.LONGVARBINARY : return "Types.LONGVARBINARY";
588             case Types.BLOB : return "Types.BLOB";
589
590             case Types.OTHER : return "Types.OTHER";
591             case Types.NULL : return "Types.NULL";
592             default : return String.valueOf(jdbcType);
593         }
594     }
595
596     /*** Some routines for printing test information to html **/
597
598     public static String JavaDoc TABLE_START_TAG = "<TABLE border=1 cellspacing=1 cellpadding=1 bgcolor=white style='width:100%'>";
599     public static String JavaDoc TABLE_END_TAG = "</TABLE>";
600     public static String JavaDoc TD_INVERSE =
601         "<td valign=bottom align=center style=background:#DADADA; padding:.75pt .75pt .75pt .75pt'> <p class=MsoNormal style='margin-top:6.0pt;margin-right:0in;margin-bottom: 6.0pt;margin-left:0in'><b><span style='font-size:8.5pt;font-family:Arial; color:black'>";
602
603     public static String JavaDoc TD_CENTER = "<TD valign=center align=center> <p class=MsoNormal style='margin-top:6.0pt;margin-right:0in;margin-bottom:6.0pt;margin-left:0in'><b><span style='font-size:8.5pt;font-family:Arial; color:black'>";
604
605     public static String JavaDoc TD_LEFT = "<TD valign=center align=left> <p class=MsoNormal style='margin-top:6.0pt;margin-right:0in;margin-bottom:6.0pt;margin-left:0in'><b><span style='font-size:8.5pt;font-family:Arial; color:black'>";
606
607     
608     public static String JavaDoc TD_END = "</SPAN></TD>";
609
610     public static String JavaDoc END_HTML_PAGE="</BODY> </HTML>";
611     
612
613     public static void startHTMLPage(String JavaDoc title, String JavaDoc author)
614     {
615         System.out.println("<HTML> \n <HEAD>");
616         System.out.println(" <meta http-equiv=\"Content-Type\"content=\"text/html; charset=iso-8859-1\">");
617         System.out.println("<meta name=\"Author\" content=\"" + author + "\">");
618         System.out.println("<title>" + title + "</title>");
619         System.out.println("</HEAD> <BODY>");
620         System.out.println("<H1>" + title + "</H1>");
621     }
622
623     public static void endHTMLPage()
624     {
625         System.out.println(END_HTML_PAGE);
626     }
627
628 /* public static void main(String[] argv)
629     {
630         testBoolArrayToHTMLTable();
631     }
632 */

633
634     /**
635      * Converts 2 dimensional boolean array into an HTML table.
636      * used by casting.java to print out casting doc
637      *
638      * @param rowLabels - Row labels
639      * @param colLabels - Column labels
640      **/

641     public static void printBoolArrayHTMLTable(String JavaDoc rowDescription,
642                                                String JavaDoc columnDescription,
643                                                String JavaDoc [] rowLabels,
644                                                String JavaDoc [] colLabels,
645                                                boolean[][] array,
646                                                String JavaDoc tableInfo)
647     {
648
649         System.out.println("<H2>" + tableInfo + "</H2>");
650
651         System.out.println(TABLE_START_TAG);
652         System.out.println("<TR>");
653         // Print corner with labels
654
System.out.println(TD_INVERSE +columnDescription + "---><BR><BR><BR><BR><BR>");
655         System.out.println("<---" +rowDescription);
656         System.out.println(TD_END);
657
658         
659         // Print column headers
660
for (int i = 0; i < colLabels.length; i++)
661         {
662             System.out.println(TD_INVERSE);
663             for (int c = 0; c < colLabels[i].length() && c < 20; c++)
664             {
665                 System.out.println(colLabels[i].charAt(c) + "<BR>");
666             }
667             System.out.println(TD_END);
668         }
669
670         System.out.println("</TR>");
671
672         // Print the Row Labels and Data
673
for (int i = 0; i < rowLabels.length; i ++)
674         {
675             System.out.println("<TR>");
676             System.out.println(TD_LEFT);
677             System.out.println("<C> " + rowLabels[i] + "</C>");
678             System.out.println(TD_END);
679
680             for (int j = 0; j < colLabels.length; j ++)
681             {
682                 System.out.println(TD_CENTER);
683                 System.out.println((array[i][j]) ? "Y" : "-");
684                 System.out.println(TD_END);
685             }
686             System.out.println("</TR>");
687         }
688
689
690         System.out.println(TABLE_END_TAG);
691         System.out.println("<P><P>");
692
693     }
694
695     /**
696      * Just converts a string to a hex literal to assist in converting test
697      * cases that used to insert strings into bit data tables
698      * Converts using UTF-16BE just like the old casts used to.
699      *
700      * @ param s String to convert (e.g
701      * @ resturns hex literal that can be inserted into a bit column.
702      */

703     public static String JavaDoc stringToHexLiteral(String JavaDoc s)
704     {
705         byte[] bytes;
706         String JavaDoc hexLiteral = null;
707         try {
708             bytes = s.getBytes("UTF-16BE");
709             hexLiteral = convertToHexString(bytes);
710         }
711         catch (UnsupportedEncodingException ue)
712         {
713             System.out.println("This shouldn't happen as UTF-16BE should be supported");
714             ue.printStackTrace();
715         }
716
717         return hexLiteral;
718     }
719
720     private static String JavaDoc convertToHexString(byte [] buf)
721     {
722         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
723         str.append("X'");
724         String JavaDoc val;
725         int byteVal;
726         for (int i = 0; i < buf.length; i++)
727         {
728             byteVal = buf[i] & 0xff;
729             val = Integer.toHexString(byteVal);
730             if (val.length() < 2)
731                 str.append("0");
732             str.append(val);
733         }
734         return str.toString() +"'";
735     }
736
737
738
739     /**
740         Get the JDBC version, inferring it from the driver.
741     */

742
743     public static int getJDBCMajorVersion(Connection conn)
744     {
745         try {
746             // DatabaseMetaData.getJDBCMajorVersion() was not part of JDBC 2.0.
747
// Check if setSavepoint() is present to decide whether the version
748
// is > 2.0.
749
conn.getClass().getMethod("setSavepoint", null);
750             DatabaseMetaData meta = conn.getMetaData();
751             Method method =
752                 meta.getClass().getMethod("getJDBCMajorVersion", null);
753             return ((Number JavaDoc) method.invoke(meta, null)).intValue();
754         } catch (Throwable JavaDoc t) {
755             // Error probably means that either setSavepoint() or
756
// getJDBCMajorVersion() is not present. Assume JDBC 2.0.
757
return 2;
758         }
759
760     }
761
762     /**
763         Drop the test objects passed in as a string identifying the
764         type of object (e.g. TABLE, PROCEDURE) and its name.
765         Thus, for example, a testObject array could be:
766         {"TABLE MYSCHEMA.MYTABLE", "PROCEDURE THISDUMMY"}
767         The statement passed in must be a 'live' statement in the test.
768     */

769     public static void cleanUpTest (Statement s, String JavaDoc[] testObjects)
770                                     throws SQLException {
771         /* drop each object named */
772         for (int i=0; i < testObjects.length; i++) {
773             try {
774                 s.execute("drop " + testObjects[i]);
775                 //System.out.println("now dropping " + testObjects[i]);
776
} catch (SQLException se) { // ignore...
777
}
778         }
779     }
780
781     
782     /**
783      * Get connection to given database using the connection attributes. This
784      * method is used by tests to get a secondary connection with
785      * different set of attributes. It does not use what is specified in
786      * app_properties file or system properties. This method uses DataSource
787      * class for CDC/Foundation Profile environments, which are based on
788      * JSR169. Using DataSource will not work with other j9 profiles. So
789      * DriverManager is used for non-JSR169. The method is used as a wrapper to
790      * hide this difference in getting connections in different environments.
791      *
792      * @param databaseName
793      * @param connAttrs
794      * @return Connection to database
795      * @throws SQLException on failure to connect.
796      * @throws ClassNotFoundException on failure to load driver.
797      * @throws InstantiationException on failure to load driver.
798      * @throws IllegalAccessException on failure to load driver.
799      */

800     public static Connection getConnection(String JavaDoc databaseName, String JavaDoc connAttrs)
801         throws SQLException {
802         try {
803             Connection conn;
804             if(TestUtil.HAVE_DRIVER_CLASS) {
805                 // following is like loadDriver(), but
806
// that method throws Exception, we want finer granularity
807
String JavaDoc driverName;
808                 int framework = getFramework();
809                 switch (framework)
810                 {
811                     case EMBEDDED_FRAMEWORK:
812                         driverName = "org.apache.derby.jdbc.EmbeddedDriver";
813                         break;
814                     case DERBY_NET_FRAMEWORK:
815                     case OLD_NET_FRAMEWORK:
816                     case DB2JCC_FRAMEWORK:
817                         driverName = "com.ibm.db2.jcc.DB2Driver";
818                         break;
819                     case DERBY_NET_CLIENT_FRAMEWORK:
820                         driverName = "org.apache.derby.jdbc.ClientDriver";
821                         break;
822                     default:
823                         driverName = "org.apache.derby.jdbc.EmbeddedDriver";
824                         break;
825                 }
826                 // q: do we need a privileged action here, like in loadDriver?
827
Class.forName(driverName).newInstance();
828                 
829                 String JavaDoc url = getJdbcUrlPrefix() + databaseName;
830                 if (connAttrs != null) url += ";" + connAttrs;
831                 if (framework == DERBY_NET_FRAMEWORK)
832                 {
833                     if (( connAttrs == null) || ((connAttrs != null) && (connAttrs.indexOf("user") < 0)))
834                         url += ":" + "user=APP;password=APP;retrieveMessagesFromServerOnGetMessage=true;";
835                 }
836                 conn = DriverManager.getConnection(url);
837             }
838             else {
839                 //Use DataSource for JSR169
840
Properties JavaDoc prop = new Properties JavaDoc();
841                 prop.setProperty("databaseName", databaseName);
842                 if (connAttrs != null)
843                     prop.setProperty("connectionAttributes", connAttrs);
844                 conn = getDataSourceConnection(prop);
845             }
846             return conn;
847         } catch (ClassNotFoundException JavaDoc cnfe) {
848             System.out.println("FAILure: Class not found!");
849             cnfe.printStackTrace();
850             return null;
851         } catch (InstantiationException JavaDoc inste) {
852             System.out.println("FAILure: Cannot instantiate class");
853             inste.printStackTrace();
854             return null;
855         } catch (IllegalAccessException JavaDoc ille) {
856             System.out.println("FAILure: Not allowed to use class");
857             ille.printStackTrace();
858             return null;
859         }
860     }
861     
862     public static Connection getDataSourceConnection (Properties JavaDoc prop) throws SQLException {
863         DataSource JavaDoc ds = TestUtil.getDataSource(prop);
864         try {
865             Connection conn = ds.getConnection();
866             return conn;
867         }
868         catch (SQLException e) {
869             throw e;
870         }
871     }
872     
873     public static void shutdownUsingDataSource (String JavaDoc dbName) throws SQLException {
874         Properties JavaDoc prop = new Properties JavaDoc();
875         prop.setProperty("databaseName", dbName );
876         prop.setProperty("shutdownDatabase", "shutdown" );
877         DataSource JavaDoc ds = TestUtil.getDataSource(prop);
878         try {
879             Connection conn = ds.getConnection();
880         }
881         catch (SQLException e) {
882             throw e;
883         }
884     }
885     
886     //Used by metadata tests for DatabaseMetadata.getURL
887
public static boolean compareURL(String JavaDoc url) {
888             
889         if(isEmbeddedFramework()) {
890             if(url.compareTo("jdbc:derby:wombat") == 0)
891                 return true;
892         } else if(isNetFramework()) {
893             try {
894                 StringTokenizer JavaDoc urlTokenizer = new StringTokenizer JavaDoc(url, "/");
895                 String JavaDoc urlStart = urlTokenizer.nextToken();
896                 urlTokenizer.nextToken();
897                 String JavaDoc urlEnd = urlTokenizer.nextToken();
898                 
899                 if(urlEnd.compareTo("wombat;create=true") != 0)
900                     return false;
901                 
902                 if(isJCCFramework() && (urlStart.compareTo("jdbc:derby:net:") == 0))
903                     return true;
904                 
905                 if(isDerbyNetClientFramework() && (urlStart.compareTo("jdbc:derby:") == 0))
906                     return true;
907                 
908             } catch (NoSuchElementException JavaDoc nsee) {
909                 //Should not reach here.
910
return false;
911             }
912         }
913         
914         return false;
915     }
916
917 }
918
919
Popular Tags