001: /*
002:
003: Derby - Class org.apache.derbyTesting.functionTests.util.TestUtil
004:
005: Licensed to the Apache Software Foundation (ASF) under one or more
006: contributor license agreements. See the NOTICE file distributed with
007: this work for additional information regarding copyright ownership.
008: The ASF licenses this file to You under the Apache License, Version 2.0
009: (the "License"); you may not use this file except in compliance with
010: the License. You may obtain a copy of the License at
011:
012: http://www.apache.org/licenses/LICENSE-2.0
013:
014: Unless required by applicable law or agreed to in writing, software
015: distributed under the License is distributed on an "AS IS" BASIS,
016: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017: See the License for the specific language governing permissions and
018: limitations under the License.
019:
020: */
021:
022: package org.apache.derbyTesting.functionTests.util;
023:
024: import java.sql.*;
025: import java.io.*;
026: import java.lang.reflect.*;
027: import java.util.Enumeration;
028: import java.util.Hashtable;
029: import java.util.Locale;
030: import java.util.Properties;
031: import java.util.StringTokenizer;
032: import java.util.NoSuchElementException;
033: import java.security.AccessController;
034: import java.security.PrivilegedAction;
035: import java.security.PrivilegedExceptionAction;
036: import java.security.PrivilegedActionException;
037: import javax.sql.DataSource;
038:
039: import org.apache.derby.iapi.reference.JDBC30Translation;
040: import org.apache.derby.iapi.services.info.JVMInfo;
041: import org.apache.derbyTesting.functionTests.harness.RunTest;
042:
043: /**
044: Utility methods for tests, in order to bring some consistency to test
045: output and handle testing framework differences
046:
047: */
048: public class TestUtil {
049:
050: //Used for JSR169
051: public static boolean HAVE_DRIVER_CLASS;
052: static {
053: try {
054: Class.forName("java.sql.Driver");
055: HAVE_DRIVER_CLASS = true;
056: } catch (ClassNotFoundException e) {
057: //Used for JSR169
058: HAVE_DRIVER_CLASS = false;
059: }
060: }
061:
062: public static final int UNKNOWN_FRAMEWORK = -1;
063:
064: /**
065: framework = embedded (or null) jdbc:derby:
066: */
067: public static final int EMBEDDED_FRAMEWORK = 0;
068:
069: /**
070: framework = DerbyNet for JCC jdbc:derby:net:
071: */
072: public static final int DERBY_NET_FRAMEWORK = 1;
073:
074: /**
075: framework = DB2JCC for testing JCC against DB2 for
076: debugging jcc problems jdbc:db2://
077: */
078:
079: public static final int DB2JCC_FRAMEWORK = 2; // jdbc:db2//
080:
081: /**
082: framework = DerbyNetClient for Derby cient jdbc:derby://
083: */
084: public static final int DERBY_NET_CLIENT_FRAMEWORK = 3; // jdbc:derby://
085:
086: /**
087: framework = DB2jNet
088: OLD_NET_FRAMEWORK is for tests that have not yet been contributed.
089: it can be removed once all tests are at apache
090: */
091: public static final int OLD_NET_FRAMEWORK = 4; // jdbc:derby:net:
092:
093: private static int framework = UNKNOWN_FRAMEWORK;
094:
095: // DataSource Type strings used to build up datasource names.
096: // e.g. "Embed" + XA_DATASOURCE_STRING + "DataSource
097: private static String XA_DATASOURCE_STRING = "XA";
098: private static String CONNECTION_POOL_DATASOURCE_STRING = "ConnectionPool";
099: private static String REGULAR_DATASOURCE_STRING = "";
100: private static String JSR169_DATASOURCE_STRING = "Simple";
101:
102: // Methods for making framework dependent decisions in tests.
103:
104: /**
105: * Is this a network testingframework?
106: * return true if the System Property framework is set to Derby Network
107: * client or JCC
108: *
109: * @return true if this is a Network Server test
110: */
111: public static boolean isNetFramework() {
112: framework = getFramework();
113: switch (framework) {
114: case DERBY_NET_FRAMEWORK:
115: case DERBY_NET_CLIENT_FRAMEWORK:
116: case DB2JCC_FRAMEWORK:
117: case OLD_NET_FRAMEWORK:
118: return true;
119: default:
120: return false;
121: }
122: }
123:
124: /**
125: Is the JCC driver being used
126:
127: @return true for JCC driver
128: */
129: public static boolean isJCCFramework() {
130: int framework = getFramework();
131: switch (framework) {
132: case DERBY_NET_FRAMEWORK:
133: case DB2JCC_FRAMEWORK:
134: case OLD_NET_FRAMEWORK:
135: return true;
136: }
137: return false;
138: }
139:
140: public static boolean isDerbyNetClientFramework() {
141: return (getFramework() == DERBY_NET_CLIENT_FRAMEWORK);
142: }
143:
144: public static boolean isEmbeddedFramework() {
145: return (getFramework() == EMBEDDED_FRAMEWORK);
146: }
147:
148: /**
149: Get the framework from the System Property framework
150: @return constant for framework being used
151: TestUtil.EMBEDDED_FRAMEWORK for embedded
152: TestUtil.DERBY_NET_CLIENT_FRAMEWORK for Derby Network Client
153: TestUtil.DERBY_NET_FRAMEWORK for JCC to Network Server
154: TestUtil.DB2JCC_FRAMEWORK for JCC to DB2
155: */
156: private static int getFramework() {
157: if (framework != UNKNOWN_FRAMEWORK)
158: return framework;
159: String frameworkString = (String) AccessController
160: .doPrivileged(new PrivilegedAction() {
161: public Object run() {
162: return System.getProperty("framework");
163: }
164: });
165: // last attempt to get useprocess to do networkserver stuff.
166: // If a suite has useprocess, it's possible there was no property set.
167: if (frameworkString == null) {
168: String useprocessFramework = RunTest.framework;
169: if (useprocessFramework != null)
170: frameworkString = useprocessFramework;
171: }
172: if (frameworkString == null
173: || frameworkString.toUpperCase(Locale.ENGLISH).equals(
174: "EMBEDDED"))
175: framework = EMBEDDED_FRAMEWORK;
176: else if (frameworkString.toUpperCase(Locale.ENGLISH).equals(
177: "DERBYNETCLIENT"))
178: framework = DERBY_NET_CLIENT_FRAMEWORK;
179: else if (frameworkString.toUpperCase(Locale.ENGLISH).equals(
180: "DERBYNET"))
181: framework = DERBY_NET_FRAMEWORK;
182: else if (frameworkString.toUpperCase(Locale.ENGLISH).indexOf(
183: "DB2JNET") != -1)
184: framework = OLD_NET_FRAMEWORK;
185:
186: return framework;
187:
188: }
189:
190: /**
191: Get URL prefix for current framework.
192:
193: @return url, assume localhost - unless set differently in System property -
194: and assume port 1527 for Network Tests
195: @see getJdbcUrlPrefix(String server, int port)
196:
197: */
198: public static String getJdbcUrlPrefix() {
199: String hostName = getHostName();
200: return getJdbcUrlPrefix(hostName, 1527);
201: }
202:
203: /** Get hostName as passed in - if not, set it to "localhost"
204: @return hostName, as passed into system properties, or "localhost"
205: */
206: public static String getHostName() {
207: String hostName = (String) AccessController
208: .doPrivileged(new PrivilegedAction() {
209: public Object run() {
210: return System.getProperty("hostName");
211: }
212: });
213: if (hostName == null)
214: hostName = "localhost";
215: return hostName;
216: }
217:
218: /**
219: Get URL prefix for current framework
220:
221: @param server host to connect to with client driver
222: ignored for embedded driver
223: @param port port to connect to with client driver
224: ignored with embedded driver
225: @return URL prefix
226: EMBEDDED_FRAMEWORK returns "jdbc:derby"
227: DERBY_NET_FRAMEWORK = "jdbc:derby:net://<server>:port/"
228: DERBY_NET_CLIENT_FRAMEWORK = "jdbc:derby://<server>:port/"
229: DB2_JCC_FRAMEWORK = "jdbc:db2://<server>:port/"
230: */
231: public static String getJdbcUrlPrefix(String server, int port) {
232: int framework = getFramework();
233: switch (framework) {
234: case EMBEDDED_FRAMEWORK:
235: return "jdbc:derby:";
236: case DERBY_NET_FRAMEWORK:
237: case OLD_NET_FRAMEWORK:
238: return "jdbc:derby:net://" + server + ":" + port + "/";
239: case DERBY_NET_CLIENT_FRAMEWORK:
240: return "jdbc:derby://" + server + ":" + port + "/";
241: case DB2JCC_FRAMEWORK:
242: return "jdbc:db2://" + server + ":" + port + "/";
243: }
244: // Unknown framework
245: return null;
246:
247: }
248:
249: /**
250: Load the appropriate driver for the current framework
251: */
252: public static void loadDriver() throws Exception {
253: final String driverName;
254: framework = getFramework();
255: switch (framework) {
256: case EMBEDDED_FRAMEWORK:
257: driverName = "org.apache.derby.jdbc.EmbeddedDriver";
258: break;
259: case DERBY_NET_FRAMEWORK:
260: case OLD_NET_FRAMEWORK:
261: case DB2JCC_FRAMEWORK:
262: driverName = "com.ibm.db2.jcc.DB2Driver";
263: break;
264: case DERBY_NET_CLIENT_FRAMEWORK:
265: driverName = "org.apache.derby.jdbc.ClientDriver";
266: break;
267: default:
268: driverName = "org.apache.derby.jdbc.EmbeddedDriver";
269: break;
270: }
271:
272: try {
273: AccessController
274: .doPrivileged(new PrivilegedExceptionAction() {
275: public Object run() throws Exception {
276: return Class.forName(driverName)
277: .newInstance();
278: }
279: });
280: } catch (PrivilegedActionException e) {
281: throw e.getException();
282: }
283: }
284:
285: /**
286: * Get a data source for the appropriate framework
287: * @param attrs A set of attribute values to set on the datasource.
288: * The appropriate setter method wil b
289: * For example the property databaseName with value wombat,
290: * will mean ds.setDatabaseName("wombat") will be called
291: * @return datasource for current framework
292: */
293: public static javax.sql.DataSource getDataSource(Properties attrs) {
294: String classname;
295: if (HAVE_DRIVER_CLASS) {
296: classname = getDataSourcePrefix()
297: + REGULAR_DATASOURCE_STRING + "DataSource";
298: classname = checkForJDBC40Implementation(classname);
299: return (javax.sql.DataSource) getDataSourceWithReflection(
300: classname, attrs);
301: } else
302: return getSimpleDataSource(attrs);
303:
304: }
305:
306: public static DataSource getSimpleDataSource(Properties attrs) {
307: String classname = getDataSourcePrefix()
308: + JSR169_DATASOURCE_STRING + "DataSource";
309: return (javax.sql.DataSource) getDataSourceWithReflection(
310: classname, attrs);
311: }
312:
313: /**
314: * Get an xa data source for the appropriate framework
315: * @param attrs A set of attribute values to set on the datasource.
316: * The appropriate setter method wil b
317: * For example the property databaseName with value wombat,
318: * will mean ds.setDatabaseName("wombat") will be called
319: * @return datasource for current framework
320: */
321: public static javax.sql.XADataSource getXADataSource(
322: Properties attrs) {
323:
324: String classname = getDataSourcePrefix() + XA_DATASOURCE_STRING
325: + "DataSource";
326: classname = checkForJDBC40Implementation(classname);
327: return (javax.sql.XADataSource) getDataSourceWithReflection(
328: classname, attrs);
329: }
330:
331: /**
332: * Get a ConnectionPoolDataSource for the appropriate framework
333: * @param attrs A set of attribute values to set on the datasource.
334: * The appropriate setter method wil b
335: * For example the property databaseName with value wombat,
336: * will mean ds.setDatabaseName("wombat") will be called
337: * @return datasource for current framework
338: */
339: public static javax.sql.ConnectionPoolDataSource getConnectionPoolDataSource(
340: Properties attrs) {
341: String classname = getDataSourcePrefix()
342: + CONNECTION_POOL_DATASOURCE_STRING + "DataSource";
343: classname = checkForJDBC40Implementation(classname);
344: return (javax.sql.ConnectionPoolDataSource) getDataSourceWithReflection(
345: classname, attrs);
346: }
347:
348: /**
349: * returns the class name for the JDBC40 implementation
350: * if present. otherwise returns the class name of the class
351: * written for the lower jdk versions
352: * @param classname String
353: * @return String containing the name of the appropriate
354: * implementation
355: */
356: public static String checkForJDBC40Implementation(String classname) {
357: String classname_ = classname;
358: // The JDBC 4.0 implementation of the
359: // interface is suffixed with "40". Use it if it is available
360: // and the JVM version is at least 1.6.
361: if (JVMInfo.JDK_ID >= JVMInfo.J2SE_16) {
362: String classname40 = classname_ + "40";
363: try {
364: Class.forName(classname40);
365: classname_ = classname40;
366: } catch (ClassNotFoundException e) {
367: }
368: }
369: return classname_;
370: }
371:
372: public static String getDataSourcePrefix() {
373: framework = getFramework();
374: switch (framework) {
375: case OLD_NET_FRAMEWORK:
376: case DERBY_NET_FRAMEWORK:
377: case DB2JCC_FRAMEWORK:
378: return "com.ibm.db2.jcc.DB2";
379: case DERBY_NET_CLIENT_FRAMEWORK:
380: return "org.apache.derby.jdbc.Client";
381: case EMBEDDED_FRAMEWORK:
382: return "org.apache.derby.jdbc.Embedded";
383: default:
384: Exception e = new Exception(
385: "FAIL: No DataSource Prefix for framework: "
386: + framework);
387: e.printStackTrace();
388: }
389: return null;
390: }
391:
392: static private Class[] STRING_ARG_TYPE = { String.class };
393: static private Class[] INT_ARG_TYPE = { Integer.TYPE };
394: static private Class[] BOOLEAN_ARG_TYPE = { Boolean.TYPE };
395: // A hashtable of special non-string attributes.
396: private static Hashtable specialAttributes = null;
397:
398: private static Object getDataSourceWithReflection(String classname,
399: Properties attrs) {
400: Object[] args = null;
401: Object ds = null;
402: Method sh = null;
403: String methodName = null;
404:
405: if (specialAttributes == null) {
406: specialAttributes = new Hashtable();
407: specialAttributes.put("portNumber", INT_ARG_TYPE);
408: specialAttributes.put("driverType", INT_ARG_TYPE);
409: specialAttributes.put(
410: "retrieveMessagesFromServerOnGetMessage",
411: BOOLEAN_ARG_TYPE);
412: specialAttributes.put("retrieveMessageText",
413: BOOLEAN_ARG_TYPE);
414: }
415:
416: try {
417: ds = Class.forName(classname).newInstance();
418:
419: // for remote server testing, check whether the hostName is set for the test
420: // if so, and serverName is not yet set explicitly for the datasource, set it now
421: String hostName = getHostName();
422: if ((!isEmbeddedFramework()) && (hostName != null)
423: && (attrs.getProperty("serverName") == null))
424: attrs.setProperty("serverName", hostName);
425:
426: for (Enumeration propNames = attrs.propertyNames(); propNames
427: .hasMoreElements();) {
428: String key = (String) propNames.nextElement();
429: Class[] argType = (Class[]) specialAttributes.get(key);
430: if (argType == null)
431: argType = STRING_ARG_TYPE;
432: String value = attrs.getProperty(key);
433: if (argType == INT_ARG_TYPE) {
434: args = new Integer[] { new Integer(Integer
435: .parseInt(value)) };
436: } else if (argType == BOOLEAN_ARG_TYPE) {
437: args = new Boolean[] { new Boolean(value) };
438: } else if (argType == STRING_ARG_TYPE) {
439: args = new String[] { value };
440: } else // No other property types supported right now
441: {
442: throw new Exception(
443: "FAIL: getDataSourceWithReflection: Argument type "
444: + argType[0].getName()
445: + " not supportted for attribute: "
446: + " key:" + key + " value:" + value);
447:
448: }
449: methodName = getSetterName(key);
450:
451: // Need to use reflection to load indirectly
452: // setDatabaseName
453: sh = ds.getClass().getMethod(methodName, argType);
454: sh.invoke(ds, args);
455: }
456:
457: } catch (Exception e) {
458: System.out.println("Error accessing method " + methodName);
459: System.out.println(e.getMessage());
460: e.printStackTrace();
461: }
462: return ds;
463: }
464:
465: public static String getSetterName(String attribute) {
466: return "set" + Character.toUpperCase(attribute.charAt(0))
467: + attribute.substring(1);
468: }
469:
470: public static String getGetterName(String attribute) {
471: return "get" + Character.toUpperCase(attribute.charAt(0))
472: + attribute.substring(1);
473: }
474:
475: // Some methods for test output.
476: public static void dumpSQLExceptions(SQLException sqle) {
477: TestUtil.dumpSQLExceptions(sqle, false);
478: }
479:
480: public static void dumpSQLExceptions(SQLException sqle,
481: boolean expected) {
482: String prefix = "";
483: if (!expected) {
484: System.out
485: .println("FAIL -- unexpected exception ****************");
486: } else {
487: prefix = "EXPECTED ";
488: }
489:
490: do {
491: System.out.println(prefix + "SQLSTATE("
492: + sqle.getSQLState() + "): " + sqle.getMessage());
493: sqle = sqle.getNextException();
494: } while (sqle != null);
495: }
496:
497: public static String sqlNameFromJdbc(int jdbcType) {
498: switch (jdbcType) {
499: case Types.BIT:
500: return "Types.BIT";
501: case JDBC30Translation.SQL_TYPES_BOOLEAN:
502: return "Types.BOOLEAN";
503: case Types.TINYINT:
504: return "Types.TINYINT";
505: case Types.SMALLINT:
506: return "SMALLINT";
507: case Types.INTEGER:
508: return "INTEGER";
509: case Types.BIGINT:
510: return "BIGINT";
511:
512: case Types.FLOAT:
513: return "Types.FLOAT";
514: case Types.REAL:
515: return "REAL";
516: case Types.DOUBLE:
517: return "DOUBLE";
518:
519: case Types.NUMERIC:
520: return "Types.NUMERIC";
521: case Types.DECIMAL:
522: return "DECIMAL";
523:
524: case Types.CHAR:
525: return "CHAR";
526: case Types.VARCHAR:
527: return "VARCHAR";
528: case Types.LONGVARCHAR:
529: return "LONG VARCHAR";
530: case Types.CLOB:
531: return "CLOB";
532:
533: case Types.DATE:
534: return "DATE";
535: case Types.TIME:
536: return "TIME";
537: case Types.TIMESTAMP:
538: return "TIMESTAMP";
539:
540: case Types.BINARY:
541: return "CHAR () FOR BIT DATA";
542: case Types.VARBINARY:
543: return "VARCHAR () FOR BIT DATA";
544: case Types.LONGVARBINARY:
545: return "LONG VARCHAR FOR BIT DATA";
546: case Types.BLOB:
547: return "BLOB";
548:
549: case Types.OTHER:
550: return "Types.OTHER";
551: case Types.NULL:
552: return "Types.NULL";
553: default:
554: return String.valueOf(jdbcType);
555: }
556: }
557:
558: public static String getNameFromJdbcType(int jdbcType) {
559: switch (jdbcType) {
560: case Types.BIT:
561: return "Types.BIT";
562: case JDBC30Translation.SQL_TYPES_BOOLEAN:
563: return "Types.BOOLEAN";
564: case Types.TINYINT:
565: return "Types.TINYINT";
566: case Types.SMALLINT:
567: return "Types.SMALLINT";
568: case Types.INTEGER:
569: return "Types.INTEGER";
570: case Types.BIGINT:
571: return "Types.BIGINT";
572:
573: case Types.FLOAT:
574: return "Types.FLOAT";
575: case Types.REAL:
576: return "Types.REAL";
577: case Types.DOUBLE:
578: return "Types.DOUBLE";
579:
580: case Types.NUMERIC:
581: return "Types.NUMERIC";
582: case Types.DECIMAL:
583: return "Types.DECIMAL";
584:
585: case Types.CHAR:
586: return "Types.CHAR";
587: case Types.VARCHAR:
588: return "Types.VARCHAR";
589: case Types.LONGVARCHAR:
590: return "Types.LONGVARCHAR";
591: case Types.CLOB:
592: return "Types.CLOB";
593:
594: case Types.DATE:
595: return "Types.DATE";
596: case Types.TIME:
597: return "Types.TIME";
598: case Types.TIMESTAMP:
599: return "Types.TIMESTAMP";
600:
601: case Types.BINARY:
602: return "Types.BINARY";
603: case Types.VARBINARY:
604: return "Types.VARBINARY";
605: case Types.LONGVARBINARY:
606: return "Types.LONGVARBINARY";
607: case Types.BLOB:
608: return "Types.BLOB";
609:
610: case Types.OTHER:
611: return "Types.OTHER";
612: case Types.NULL:
613: return "Types.NULL";
614: default:
615: return String.valueOf(jdbcType);
616: }
617: }
618:
619: /*** Some routines for printing test information to html **/
620:
621: public static String TABLE_START_TAG = "<TABLE border=1 cellspacing=1 cellpadding=1 bgcolor=white style='width:100%'>";
622: public static String TABLE_END_TAG = "</TABLE>";
623: public static String TD_INVERSE = "<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'>";
624:
625: public static String 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'>";
626:
627: public static String 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'>";
628:
629: public static String TD_END = "</SPAN></TD>";
630:
631: public static String END_HTML_PAGE = "</BODY> </HTML>";
632:
633: public static void startHTMLPage(String title, String author) {
634: System.out.println("<HTML> \n <HEAD>");
635: System.out
636: .println(" <meta http-equiv=\"Content-Type\"content=\"text/html; charset=iso-8859-1\">");
637: System.out.println("<meta name=\"Author\" content=\"" + author
638: + "\">");
639: System.out.println("<title>" + title + "</title>");
640: System.out.println("</HEAD> <BODY>");
641: System.out.println("<H1>" + title + "</H1>");
642: }
643:
644: public static void endHTMLPage() {
645: System.out.println(END_HTML_PAGE);
646: }
647:
648: /* public static void main(String[] argv)
649: {
650: testBoolArrayToHTMLTable();
651: }
652: */
653:
654: /**
655: * Converts 2 dimensional boolean array into an HTML table.
656: * used by casting.java to print out casting doc
657: *
658: * @param rowLabels - Row labels
659: * @param colLabels - Column labels
660: **/
661: public static void printBoolArrayHTMLTable(String rowDescription,
662: String columnDescription, String[] rowLabels,
663: String[] colLabels, boolean[][] array, String tableInfo) {
664:
665: System.out.println("<H2>" + tableInfo + "</H2>");
666:
667: System.out.println(TABLE_START_TAG);
668: System.out.println("<TR>");
669: // Print corner with labels
670: System.out.println(TD_INVERSE + columnDescription
671: + "---><BR><BR><BR><BR><BR>");
672: System.out.println("<---" + rowDescription);
673: System.out.println(TD_END);
674:
675: // Print column headers
676: for (int i = 0; i < colLabels.length; i++) {
677: System.out.println(TD_INVERSE);
678: for (int c = 0; c < colLabels[i].length() && c < 20; c++) {
679: System.out.println(colLabels[i].charAt(c) + "<BR>");
680: }
681: System.out.println(TD_END);
682: }
683:
684: System.out.println("</TR>");
685:
686: // Print the Row Labels and Data
687: for (int i = 0; i < rowLabels.length; i++) {
688: System.out.println("<TR>");
689: System.out.println(TD_LEFT);
690: System.out.println("<C> " + rowLabels[i] + "</C>");
691: System.out.println(TD_END);
692:
693: for (int j = 0; j < colLabels.length; j++) {
694: System.out.println(TD_CENTER);
695: System.out.println((array[i][j]) ? "Y" : "-");
696: System.out.println(TD_END);
697: }
698: System.out.println("</TR>");
699: }
700:
701: System.out.println(TABLE_END_TAG);
702: System.out.println("<P><P>");
703:
704: }
705:
706: /**
707: * Just converts a string to a hex literal to assist in converting test
708: * cases that used to insert strings into bit data tables
709: * Converts using UTF-16BE just like the old casts used to.
710: *
711: * @ param s String to convert (e.g
712: * @ resturns hex literal that can be inserted into a bit column.
713: */
714: public static String stringToHexLiteral(String s) {
715: byte[] bytes;
716: String hexLiteral = null;
717: try {
718: bytes = s.getBytes("UTF-16BE");
719: hexLiteral = convertToHexString(bytes);
720: } catch (UnsupportedEncodingException ue) {
721: System.out
722: .println("This shouldn't happen as UTF-16BE should be supported");
723: ue.printStackTrace();
724: }
725:
726: return hexLiteral;
727: }
728:
729: private static String convertToHexString(byte[] buf) {
730: StringBuffer str = new StringBuffer();
731: str.append("X'");
732: String val;
733: int byteVal;
734: for (int i = 0; i < buf.length; i++) {
735: byteVal = buf[i] & 0xff;
736: val = Integer.toHexString(byteVal);
737: if (val.length() < 2)
738: str.append("0");
739: str.append(val);
740: }
741: return str.toString() + "'";
742: }
743:
744: /**
745: Get the JDBC version, inferring it from the driver.
746: */
747:
748: public static int getJDBCMajorVersion(Connection conn) {
749: try {
750: // DatabaseMetaData.getJDBCMajorVersion() was not part of JDBC 2.0.
751: // Check if setSavepoint() is present to decide whether the version
752: // is > 2.0.
753: conn.getClass().getMethod("setSavepoint", null);
754: DatabaseMetaData meta = conn.getMetaData();
755: Method method = meta.getClass().getMethod(
756: "getJDBCMajorVersion", null);
757: return ((Number) method.invoke(meta, null)).intValue();
758: } catch (Throwable t) {
759: // Error probably means that either setSavepoint() or
760: // getJDBCMajorVersion() is not present. Assume JDBC 2.0.
761: return 2;
762: }
763:
764: }
765:
766: /**
767: Drop the test objects passed in as a string identifying the
768: type of object (e.g. TABLE, PROCEDURE) and its name.
769: Thus, for example, a testObject array could be:
770: {"TABLE MYSCHEMA.MYTABLE", "PROCEDURE THISDUMMY"}
771: The statement passed in must be a 'live' statement in the test.
772: */
773: public static void cleanUpTest(Statement s, String[] testObjects)
774: throws SQLException {
775: /* drop each object named */
776: for (int i = 0; i < testObjects.length; i++) {
777: try {
778: s.execute("drop " + testObjects[i]);
779: //System.out.println("now dropping " + testObjects[i]);
780: } catch (SQLException se) { // ignore...
781: }
782: }
783: }
784:
785: /**
786: * Get connection to given database using the connection attributes. This
787: * method is used by tests to get a secondary connection with
788: * different set of attributes. It does not use what is specified in
789: * app_properties file or system properties. This method uses DataSource
790: * class for CDC/Foundation Profile environments, which are based on
791: * JSR169. Using DataSource will not work with other j9 profiles. So
792: * DriverManager is used for non-JSR169. The method is used as a wrapper to
793: * hide this difference in getting connections in different environments.
794: *
795: * @param databaseName
796: * @param connAttrs
797: * @return Connection to database
798: * @throws SQLException on failure to connect.
799: * @throws ClassNotFoundException on failure to load driver.
800: * @throws InstantiationException on failure to load driver.
801: * @throws IllegalAccessException on failure to load driver.
802: */
803: public static Connection getConnection(String databaseName,
804: String connAttrs) throws SQLException {
805: try {
806: Connection conn;
807: if (TestUtil.HAVE_DRIVER_CLASS) {
808: // following is like loadDriver(), but
809: // that method throws Exception, we want finer granularity
810: String driverName;
811: int framework = getFramework();
812: switch (framework) {
813: case EMBEDDED_FRAMEWORK:
814: driverName = "org.apache.derby.jdbc.EmbeddedDriver";
815: break;
816: case DERBY_NET_FRAMEWORK:
817: case OLD_NET_FRAMEWORK:
818: case DB2JCC_FRAMEWORK:
819: driverName = "com.ibm.db2.jcc.DB2Driver";
820: break;
821: case DERBY_NET_CLIENT_FRAMEWORK:
822: driverName = "org.apache.derby.jdbc.ClientDriver";
823: break;
824: default:
825: driverName = "org.apache.derby.jdbc.EmbeddedDriver";
826: break;
827: }
828: // q: do we need a privileged action here, like in loadDriver?
829: Class.forName(driverName).newInstance();
830:
831: String url = getJdbcUrlPrefix() + databaseName;
832: if (connAttrs != null)
833: url += ";" + connAttrs;
834: if (framework == DERBY_NET_FRAMEWORK) {
835: if ((connAttrs == null)
836: || ((connAttrs != null) && (connAttrs
837: .indexOf("user") < 0)))
838: url += ":"
839: + "user=APP;password=APP;retrieveMessagesFromServerOnGetMessage=true;";
840: }
841: conn = DriverManager.getConnection(url);
842: } else {
843: //Use DataSource for JSR169
844: Properties prop = new Properties();
845: prop.setProperty("databaseName", databaseName);
846: if (connAttrs != null)
847: prop.setProperty("connectionAttributes", connAttrs);
848: conn = getDataSourceConnection(prop);
849: }
850: return conn;
851: } catch (ClassNotFoundException cnfe) {
852: System.out.println("FAILure: Class not found!");
853: cnfe.printStackTrace();
854: return null;
855: } catch (InstantiationException inste) {
856: System.out.println("FAILure: Cannot instantiate class");
857: inste.printStackTrace();
858: return null;
859: } catch (IllegalAccessException ille) {
860: System.out.println("FAILure: Not allowed to use class");
861: ille.printStackTrace();
862: return null;
863: }
864: }
865:
866: public static Connection getDataSourceConnection(Properties prop)
867: throws SQLException {
868: DataSource ds = TestUtil.getDataSource(prop);
869: try {
870: Connection conn = ds.getConnection();
871: return conn;
872: } catch (SQLException e) {
873: throw e;
874: }
875: }
876:
877: public static void shutdownUsingDataSource(String dbName)
878: throws SQLException {
879: Properties prop = new Properties();
880: prop.setProperty("databaseName", dbName);
881: prop.setProperty("shutdownDatabase", "shutdown");
882: DataSource ds = TestUtil.getDataSource(prop);
883: try {
884: Connection conn = ds.getConnection();
885: } catch (SQLException e) {
886: throw e;
887: }
888: }
889:
890: //Used by metadata tests for DatabaseMetadata.getURL
891: public static boolean compareURL(String url) {
892:
893: if (isEmbeddedFramework()) {
894: if (url.compareTo("jdbc:derby:wombat") == 0)
895: return true;
896: } else if (isNetFramework()) {
897: try {
898: StringTokenizer urlTokenizer = new StringTokenizer(url,
899: "/");
900: String urlStart = urlTokenizer.nextToken();
901: urlTokenizer.nextToken();
902: String urlEnd = urlTokenizer.nextToken();
903:
904: if (urlEnd.compareTo("wombat;create=true") != 0)
905: return false;
906:
907: if (isJCCFramework()
908: && (urlStart.compareTo("jdbc:derby:net:") == 0))
909: return true;
910:
911: if (isDerbyNetClientFramework()
912: && (urlStart.compareTo("jdbc:derby:") == 0))
913: return true;
914:
915: } catch (NoSuchElementException nsee) {
916: //Should not reach here.
917: return false;
918: }
919: }
920:
921: return false;
922: }
923:
924: }
|