0001: /*
0002: * The contents of this file are subject to the terms of the Common Development
0003: * and Distribution License (the License). You may not use this file except in
0004: * compliance with the License.
0005: *
0006: * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
0007: * or http://www.netbeans.org/cddl.txt.
0008: *
0009: * When distributing Covered Code, include this CDDL Header Notice in each file
0010: * and include the License file at http://www.netbeans.org/cddl.txt.
0011: * If applicable, add the following below the CDDL Header, with the fields
0012: * enclosed by brackets [] replaced by your own identifying information:
0013: * "Portions Copyrighted [year] [name of copyright owner]"
0014: *
0015: * The Original Software is NetBeans. The Initial Developer of the Original
0016: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
0017: * Microsystems, Inc. All Rights Reserved.
0018: */
0019:
0020: /*
0021: *
0022: * Copyright 2005 Sun Microsystems, Inc.
0023: *
0024: * Licensed under the Apache License, Version 2.0 (the "License");
0025: * you may not use this file except in compliance with the License.
0026: * You may obtain a copy of the License at
0027: *
0028: * http://www.apache.org/licenses/LICENSE-2.0
0029: *
0030: * Unless required by applicable law or agreed to in writing, software
0031: * distributed under the License is distributed on an "AS IS" BASIS,
0032: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0033: * See the License for the specific language governing permissions and
0034: * limitations under the License.
0035: *
0036: */
0037: package org.netbeans.modules.jdbcwizard.builder;
0038:
0039: import java.sql.Connection;
0040: import java.sql.DatabaseMetaData;
0041: import java.sql.PreparedStatement;
0042: import java.sql.CallableStatement;
0043: import java.sql.ResultSet;
0044: import java.sql.Statement;
0045: import java.sql.ResultSetMetaData;
0046: import java.sql.ParameterMetaData;
0047: import java.sql.SQLException;
0048: import java.sql.Driver;
0049: import java.sql.DriverPropertyInfo;
0050:
0051: import java.util.Collections;
0052: import java.util.HashMap;
0053: import java.util.List;
0054: import java.util.Vector;
0055: import java.util.Properties;
0056:
0057: import java.util.ArrayList;
0058: import java.util.Iterator;
0059: import java.util.StringTokenizer;
0060: import java.util.logging.Level;
0061: import java.util.logging.Logger;
0062:
0063: /**
0064: * Extracts database metadata information (table names and constraints, their associated columns,
0065: * etc.)
0066: *
0067: * @author
0068: */
0069:
0070: class DriverShim implements Driver {
0071: private final Driver driver;
0072:
0073: DriverShim(final Driver d) {
0074: this .driver = d;
0075: }
0076:
0077: public boolean acceptsURL(final String u) throws SQLException {
0078: return this .driver.acceptsURL(u);
0079: }
0080:
0081: public Connection connect(final String u, final Properties p)
0082: throws SQLException {
0083: return this .driver.connect(u, p);
0084: }
0085:
0086: public int getMajorVersion() {
0087: return this .driver.getMajorVersion();
0088: }
0089:
0090: public int getMinorVersion() {
0091: return this .driver.getMinorVersion();
0092: }
0093:
0094: public DriverPropertyInfo[] getPropertyInfo(final String u,
0095: final Properties p) throws SQLException {
0096: return this .driver.getPropertyInfo(u, p);
0097: }
0098:
0099: public boolean jdbcCompliant() {
0100: return this .driver.jdbcCompliant();
0101: }
0102: }
0103:
0104: public final class DBMetaData {
0105: // constants
0106:
0107: /** Index to the name field for results of table/view/procedure searches */
0108: public static final int NAME = 0;
0109:
0110: /** Index to the catalog field for results of table/view/procedure searches */
0111: public static final int CATALOG = 1;
0112:
0113: /** Index to the schema field for results of table/view/procedure searches */
0114: public static final int SCHEMA = 2;
0115:
0116: /** Index to the type field for results of table/view/procedure searches */
0117: public static final int TYPE = 3;
0118:
0119: /** Database OTD type for DB2 */
0120: public static final String DB2 = "DB2"; // NOI18N
0121:
0122: /** Database OTD type for Oracle */
0123: public static final String ORACLE = "ORACLE"; // NOI18N
0124:
0125: /** Database OTD type for SQL Server */
0126: public static final String SQLSERVER = "SQLSERVER"; // NOI18N
0127:
0128: /** Database OTD type for JDBC */
0129: public static final String JDBC = "JDBC"; // NOI18N
0130:
0131: /** Database OTD type for VSAM */
0132: public static final String VSAM_ADABAS_IAM = "LEGACY"; // NOI18N
0133:
0134: /** Database OTD type for JDBC-ODBC */
0135: public static final String JDBC_ODBC = "JDBC"; // NOI18N
0136:
0137: /** Database type display description for DB2 */
0138: public static final String DB2_TEXT = "DB2"; // NOI18N
0139:
0140: /** Database type display description for Oracle */
0141: public static final String ORACLE_TEXT = "ORACLE"; // NOI18N
0142:
0143: /** Database type display description for Derby */
0144: public static final String DERBY = "DERBY"; // NOI18N
0145:
0146: /** Database type display description for SQL Server */
0147: public static final String SQLSERVER_TEXT = "SQL SERVER"; // NOI18N
0148:
0149: /** Database type display description for MySQL Server */
0150: public static final String MYSQL_TEXT = "MySQL"; // NOI18N
0151: public static final String MYSQL = "MYSQL"; // NOI18N
0152: /** Database type display description for JDBC */
0153: // public static final String JDBC_TEXT = "JDBC"; // NOI18N
0154: /** Database type display description for VSAM/ADABAS/IAM */
0155: public static final String VSAM_ADABAS_IAM_TEXT = "VSAM/ADABAS/IAM"; // NOI18N
0156:
0157: /** Database type display description for JDBC-ODBC */
0158: public static final String JDBC_TEXT = "JDBC-ODBC"; // NOI18N
0159:
0160: /** List of database type display descriptions */
0161: public static final String[] DBTYPES = { DBMetaData.DB2_TEXT,
0162: DBMetaData.ORACLE_TEXT, DBMetaData.SQLSERVER_TEXT,
0163: DBMetaData.JDBC_TEXT, DBMetaData.VSAM_ADABAS_IAM_TEXT,
0164: DBMetaData.JDBC_TEXT, DBMetaData.MYSQL_TEXT };
0165:
0166: /** List of Java types */
0167: public static final String[] JAVATYPES = { "boolean", "byte",
0168: "byte[]", "double", "float", "int", "java.lang.String",
0169: "java.lang.Object", "java.math.BigDecimal", "java.net.URL",
0170: "java.sql.Array", "java.sql.Blob", "java.sql.Clob",
0171: "java.sql.Date", "java.sql.Ref", "java.sql.Struct",
0172: "java.sql.Time", "java.sql.Timestamp", "long", "short" };
0173:
0174: /** List of JDBC SQL types */
0175: public static final String[] SQLTYPES = { "ARRAY", "BIGINT",
0176: "BINARY", "BIT", "BLOB", "BOOLEAN", "CHAR", "CLOB",
0177: "DATALINK", "DATE", "DECIMAL", "DISTINCT", "DOUBLE",
0178: "FLOAT", "INTEGER", "JAVA_OBJECT", "LONGVARBINARY",
0179: "LONGVARCHAR", "NULL", "NUMERIC", "OTHER", "REAL", "REF",
0180: "SMALLINT", "STRUCT", "TIME", "TIMESTAMP", "TINYINT",
0181: "VARBINARY", "VARCHAR" };
0182:
0183: public static final int[] SQLTYPE_CODES = {
0184: java.sql.Types.ARRAY,
0185: java.sql.Types.BIGINT,
0186: java.sql.Types.BINARY,
0187: java.sql.Types.BIT,
0188: java.sql.Types.BLOB,
0189: 16, // java.sql.Types.BOOLEAN,
0190: java.sql.Types.CHAR,
0191: java.sql.Types.CLOB,
0192: 70, // case java.sql.Types.DATALINK,
0193: java.sql.Types.DATE, java.sql.Types.DECIMAL,
0194: java.sql.Types.DISTINCT, java.sql.Types.DOUBLE,
0195: java.sql.Types.FLOAT, java.sql.Types.INTEGER,
0196: java.sql.Types.JAVA_OBJECT, java.sql.Types.LONGVARBINARY,
0197: java.sql.Types.LONGVARCHAR, java.sql.Types.NULL,
0198: java.sql.Types.NUMERIC, java.sql.Types.OTHER,
0199: java.sql.Types.REAL, java.sql.Types.REF,
0200: java.sql.Types.SMALLINT, java.sql.Types.STRUCT,
0201: java.sql.Types.TIME, java.sql.Types.TIMESTAMP,
0202: java.sql.Types.TINYINT, java.sql.Types.VARBINARY,
0203: java.sql.Types.VARCHAR };
0204:
0205: /** Map SQL type to Java type */
0206: public static final HashMap SQLTOJAVATYPES = new HashMap();
0207: static {
0208: DBMetaData.SQLTOJAVATYPES.put("ARRAY", "java.sql.Array"); // NOI18N
0209: DBMetaData.SQLTOJAVATYPES.put("BIGINT", "long"); // NOI18N
0210: DBMetaData.SQLTOJAVATYPES.put("BINARY", "byte[]"); // NOI18N
0211: DBMetaData.SQLTOJAVATYPES.put("BIT", "boolean"); // NOI18N
0212: DBMetaData.SQLTOJAVATYPES.put("BLOB", "java.sql.Blob"); // NOI18N
0213: DBMetaData.SQLTOJAVATYPES.put("BOOLEAN", "boolean"); // NOI18N
0214: DBMetaData.SQLTOJAVATYPES.put("CHAR", "java.lang.String"); // NOI18N
0215: DBMetaData.SQLTOJAVATYPES.put("CLOB", "java.sql.Clob"); // NOI18N
0216: DBMetaData.SQLTOJAVATYPES.put("DATALINK", "java.net.URL"); // NOI18N
0217: DBMetaData.SQLTOJAVATYPES.put("DATE", "java.sql.Date"); // NOI18N
0218: DBMetaData.SQLTOJAVATYPES
0219: .put("DECIMAL", "java.math.BigDecimal"); // NOI18N
0220: DBMetaData.SQLTOJAVATYPES.put("DISTINCT", "java.lang.String"); // NOI18N
0221: DBMetaData.SQLTOJAVATYPES.put("DOUBLE", "double"); // NOI18N
0222: DBMetaData.SQLTOJAVATYPES.put("FLOAT", "double"); // NOI18N
0223: DBMetaData.SQLTOJAVATYPES.put("INTEGER", "int"); // NOI18N
0224: DBMetaData.SQLTOJAVATYPES
0225: .put("JAVA_OBJECT", "java.lang.Object"); // NOI18N
0226: DBMetaData.SQLTOJAVATYPES.put("LONGVARBINARY", "byte[]"); // NOI18N
0227: DBMetaData.SQLTOJAVATYPES
0228: .put("LONGVARCHAR", "java.lang.String"); // NOI18N
0229: DBMetaData.SQLTOJAVATYPES.put("NULL", "java.lang.String"); // NOI18N
0230: DBMetaData.SQLTOJAVATYPES
0231: .put("NUMERIC", "java.math.BigDecimal"); // NOI18N
0232: DBMetaData.SQLTOJAVATYPES.put("OTHER", "java.lang.String"); // NOI18N
0233: DBMetaData.SQLTOJAVATYPES.put("REAL", "float"); // NOI18N
0234: DBMetaData.SQLTOJAVATYPES.put("REF", "java.sql.Ref"); // NOI18N
0235: DBMetaData.SQLTOJAVATYPES.put("SMALLINT", "short"); // NOI18N
0236: DBMetaData.SQLTOJAVATYPES.put("STRUCT", "java.sql.Struct"); // NOI18N
0237: DBMetaData.SQLTOJAVATYPES.put("TIME", "java.sql.Time"); // NOI18N
0238: DBMetaData.SQLTOJAVATYPES
0239: .put("TIMESTAMP", "java.sql.Timestamp"); // NOI18N
0240: DBMetaData.SQLTOJAVATYPES.put("TINYINT", "byte"); // NOI18N
0241: DBMetaData.SQLTOJAVATYPES.put("VARBINARY", "byte[]"); // NOI18N
0242: DBMetaData.SQLTOJAVATYPES.put("VARCHAR", "java.lang.String"); // NOI18N
0243: // added abey for Procedure ResultSets
0244: DBMetaData.SQLTOJAVATYPES
0245: .put("RESULTSET", "java.sql.ResultSet"); // NOI18N
0246: }
0247:
0248: // String used in java.sql.DatabaseMetaData to indicate system tables.
0249: private static final String SYSTEM_TABLE = "SYSTEM TABLE"; // NOI18N
0250:
0251: // String used in java.sql.DatabaseMetaData to indicate system tables.
0252: private static final String TABLE = "TABLE"; // NOI18N
0253:
0254: // String used in java.sql.DatabaseMetaData to indicate system tables.
0255: private static final String VIEW = "VIEW"; // NOI18N
0256:
0257: //private Connection dbconn; // db connection
0258:
0259: //private DatabaseMetaData dbmeta; // db metadata
0260:
0261: //private String errMsg; // error message
0262:
0263: //private boolean checkPrepStmtMetaData = true; // indicates driver does not
0264:
0265: // fully support finding prepared
0266: // statement metadata
0267: //private boolean errPrepStmtParameters = false; // error getting prep. stmt. parameters
0268:
0269: //private boolean errPrepStmtResultSetColumns = false; // error getting prep. stmt. resultset
0270:
0271: // columns
0272:
0273: /**
0274: * Gets the primary keys for a table.
0275: *
0276: * @param newTable Table to get the primary key(s) for
0277: * @throws Exception DOCUMENT ME!
0278: */
0279: public static final void checkPrimaryKeys(final Table newTable,
0280: final Connection connection) throws Exception {
0281: //this.errMsg = "";
0282: try {
0283: // get the primary keys
0284: final List primaryKeys = getPrimaryKeys(newTable
0285: .getCatalog(), newTable.getSchema(), newTable
0286: .getName(), connection);
0287:
0288: if (primaryKeys.size() != 0) {
0289: newTable.setPrimaryKeyColumnList(primaryKeys);
0290:
0291: // create a hash set of the keys
0292: final java.util.Set primaryKeysSet = new java.util.HashSet();
0293: for (int i = 0; i < primaryKeys.size(); i++) {
0294: final KeyColumn key = (KeyColumn) primaryKeys
0295: .get(i);
0296: primaryKeysSet.add(key.getColumnName());
0297: }
0298:
0299: // now loop through all the columns flagging the primary keys
0300: final TableColumn[] columns = newTable.getColumns();
0301: if (columns != null) {
0302: for (int i = 0; i < columns.length; i++) {
0303: if (primaryKeysSet.contains(columns[i]
0304: .getName())) {
0305: columns[i].setIsPrimaryKey(true);
0306: }
0307: }
0308: }
0309: }
0310: } catch (final Exception e) {
0311: e.printStackTrace();
0312: //this.errMsg = e.getLocalizedMessage();
0313: throw e;
0314: }
0315: }
0316:
0317: /**
0318: * Gets the foreign keys for a table.
0319: *
0320: * @param newTable Table to get the foreign key(s) for
0321: * @throws Exception DOCUMENT ME!
0322: */
0323: public static void checkForeignKeys(final Table newTable,
0324: final Connection connection) throws Exception {
0325: //this.errMsg = "";
0326: try {
0327: // get the foreing keys
0328: final List foreignKeys = getForeignKeys(newTable
0329: .getCatalog(), newTable.getSchema(), newTable
0330: .getName(), connection);
0331: if (foreignKeys != null) {
0332: newTable.setForeignKeyColumnList(foreignKeys);
0333:
0334: // create a hash set of the keys
0335: final java.util.Set foreignKeysSet = new java.util.HashSet();
0336: for (int i = 0; i < foreignKeys.size(); i++) {
0337: final ForeignKeyColumn key = (ForeignKeyColumn) foreignKeys
0338: .get(i);
0339: foreignKeysSet.add(key.getColumnName());
0340: }
0341:
0342: // now loop through all the columns flagging the foreign keys
0343: final TableColumn[] columns = newTable.getColumns();
0344: if (columns != null) {
0345: for (int i = 0; i < columns.length; i++) {
0346: if (foreignKeysSet.contains(columns[i]
0347: .getName())) {
0348: columns[i].setIsForeignKey(true);
0349: }
0350: }
0351: }
0352: }
0353:
0354: } catch (final Exception e) {
0355: e.printStackTrace();
0356: //this.errMsg = e.getLocalizedMessage();
0357: throw e;
0358: }
0359: }
0360:
0361: private static final Logger mLogger = Logger
0362: .getLogger(DBMetaData.class.getName());
0363:
0364: /**
0365: * Establishes a connection to the database.
0366: *
0367: * @param conn JDBC connection
0368: * @throws Exception DOCUMENT ME!
0369: */
0370: /*public void connectDB(final Connection conn) throws Exception {
0371: this.errMsg = "";
0372: if (conn == null) {
0373: throw new IllegalArgumentException("Connection can't be null.");
0374: }
0375:
0376: this.dbconn = conn;
0377: this.getDBMetaData();
0378: }*/
0379:
0380: /**
0381: * Disconnects from the database.
0382: *
0383: * @throws Exception DOCUMENT ME!
0384: */
0385: /*public void disconnectDB() throws Exception {
0386: this.errMsg = "";
0387: // close connection to database
0388: try {
0389: if (this.dbconn != null && !this.dbconn.isClosed()) {
0390: this.dbconn.close();
0391: this.dbconn = null;
0392: }
0393: } catch (final SQLException e) {
0394: e.printStackTrace();
0395: this.errMsg = e.getLocalizedMessage();
0396: throw e;
0397: }
0398: }*/
0399:
0400: /*private void getDBMetaData() throws Exception {
0401: this.errMsg = "";
0402: // get the metadata
0403: try {
0404: this.dbmeta = this.dbconn.getMetaData();
0405: } catch (final SQLException e) {
0406: e.printStackTrace();
0407: this.errMsg = e.getLocalizedMessage();
0408: throw e;
0409: }
0410: }*/
0411:
0412: /**
0413: * Returns the database product name
0414: *
0415: * @return String database product name
0416: * @throws Exception DOCUMENT ME!
0417: */
0418: /*public String getDBName() throws Exception {
0419: String dbname = "";
0420:
0421: this.errMsg = "";
0422: // get the database product name
0423: try {
0424: dbname = this.dbmeta.getDatabaseProductName();
0425: } catch (final SQLException e) {
0426: e.printStackTrace();
0427: this.errMsg = e.getLocalizedMessage();
0428: throw e;
0429: }
0430: return dbname;
0431: }*/
0432:
0433: /**
0434: * Returns the database OTD type.
0435: *
0436: * @return String Database OTD type
0437: * @throws Exception DOCUMENT ME!
0438: */
0439: public static String getDBType(final Connection conn)
0440: throws Exception {
0441: String dbtype = "";
0442:
0443: // get the database type based on the product name converted to lowercase
0444: final String dbname = conn.getMetaData()
0445: .getDatabaseProductName().toLowerCase();
0446: if (dbname.equals("microsoft sql server")) {
0447: // Microsoft SQL Server
0448: dbtype = DBMetaData.SQLSERVER;
0449: } else if (dbname.equals("mysql")) {
0450: // Microsoft SQL Server
0451: dbtype = DBMetaData.MYSQL;
0452: } else if (dbname.equals("sql server")
0453: || dbname.indexOf("jdbc") > -1) {
0454: // JDBC
0455: dbtype = DBMetaData.JDBC;
0456: } else if (dbname.indexOf("db2") > -1 || dbname.equals("as")) {
0457: // DB2
0458: dbtype = DBMetaData.DB2;
0459: } else if (dbname.equals("exadas")
0460: || dbname.equals("attunity connect driver")) {
0461: // VSAM
0462: dbtype = DBMetaData.VSAM_ADABAS_IAM;
0463: } else if (dbname.indexOf("orac") > -1) {
0464: // Oracle
0465: dbtype = DBMetaData.ORACLE;
0466: } else if (dbname.indexOf("derby") > -1) {
0467: // derby
0468: dbtype = DBMetaData.DERBY;
0469: } else {
0470: // other type, default to JDBC-ODBC
0471: dbtype = DBMetaData.JDBC_ODBC;
0472: }
0473:
0474: return dbtype;
0475: }
0476:
0477: public static int getDatabaseMajorVersion(final Connection conn)
0478: throws Exception {
0479: final DatabaseMetaData dbmeta = conn.getMetaData();
0480: return dbmeta.getDatabaseMajorVersion();
0481: }
0482:
0483: public static List getOracleRecycleBinTables(final Connection conn) {
0484: List result = new ArrayList();
0485: try {
0486: Statement stmt = conn.createStatement();
0487: try {
0488: ResultSet rs = stmt
0489: .executeQuery("SELECT OBJECT_NAME FROM RECYCLEBIN WHERE TYPE = 'TABLE'"); // NOI18N
0490: try {
0491: while (rs.next()) {
0492: result.add(rs.getString("OBJECT_NAME")); // NOI18N
0493: }
0494: } finally {
0495: rs.close();
0496: }
0497: } finally {
0498: stmt.close();
0499: }
0500: } catch (SQLException exc) {
0501: result = Collections.EMPTY_LIST;
0502: }
0503: return result;
0504: }
0505:
0506: private static final String getJDBCSearchPattern(
0507: final String guiPattern, final Connection connection)
0508: throws Exception {
0509: //this.errMsg = "";
0510:
0511: // Converts the passed in GUI pattern to one understood by the
0512: // JDBC driver:
0513: // change _ to <escape char>_
0514: // change % to <escape char>%
0515: // change * to % = GUI uses * to represent 0 or more characters
0516: // change ? to _ = GUI uses ? to represent any single character
0517: try {
0518: String jdbcPattern = guiPattern;
0519: final String escapeChar = connection.getMetaData()
0520: .getSearchStringEscape();
0521:
0522: // change _ to <escape char>_
0523: // PP:See bug 10718. Disabling the escape character for _
0524: // jdbcPattern = replaceAllChars(jdbcPattern, '_', escapeChar + "_");
0525:
0526: // change % to <escape char>%
0527: jdbcPattern = replaceAllChars(jdbcPattern, '%', escapeChar
0528: + "%");
0529:
0530: // change * to %
0531: jdbcPattern = jdbcPattern.replace('*', '%');
0532:
0533: // change ? to _
0534: jdbcPattern = jdbcPattern.replace('?', '_');
0535:
0536: return jdbcPattern;
0537: } catch (final Exception e) {
0538: e.printStackTrace();
0539: //this.errMsg = e.getLocalizedMessage();
0540: throw e;
0541: }
0542: }
0543:
0544: /**
0545: * Returns a list of schemas in the database.
0546: *
0547: * @return String[] List of schema names
0548: * @throws Exception DOCUMENT ME!
0549: */
0550: public static final String[] getSchemas(final Connection connection)
0551: throws Exception {
0552: //this.errMsg = "";
0553: // get all schemas
0554: try {
0555: final ResultSet rs = connection.getMetaData().getSchemas();
0556: final Vector v = new Vector();
0557: String[] schemaNames = null;
0558:
0559: while (rs.next()) {
0560: final String schema = rs.getString("TABLE_SCHEM");
0561: v.add(schema);
0562: }
0563: if (v.size() > 0) {
0564: // copy into array to return
0565: schemaNames = new String[v.size()];
0566: v.copyInto(schemaNames);
0567: }
0568: rs.close();
0569: return schemaNames;
0570: } catch (final Exception e) {
0571: e.printStackTrace();
0572: //this.errMsg = e.getLocalizedMessage();
0573: throw e;
0574: }
0575: }
0576:
0577: /**
0578: * Returns a list of tables matching in the passed in filters.
0579: *
0580: * @param catalog Catalog name
0581: * @param schemaPattern Schema pattern
0582: * @param tablePattern Table name pattern
0583: * @param includeSystemTables Indicate whether to include system tables in search
0584: * @return String[][] List of tables matching search filters
0585: * @throws Exception DOCUMENT ME!
0586: */
0587: public static final String[][] getTablesOnly(final String catalog,
0588: final String schemaPattern, final String tablePattern,
0589: final boolean includeSystemTables,
0590: final Connection connection) throws Exception {
0591: String[] tableTypes;
0592:
0593: if (includeSystemTables) {
0594: final String[] types = { DBMetaData.TABLE,
0595: DBMetaData.SYSTEM_TABLE };
0596: tableTypes = types;
0597: } else {
0598: final String[] types = { DBMetaData.TABLE };
0599: tableTypes = types;
0600: }
0601:
0602: return getTables(catalog, schemaPattern, tablePattern,
0603: tableTypes, connection);
0604: }
0605:
0606: /**
0607: * Returns a list of views matching in the passed in filters.
0608: *
0609: * @param catalog Catalog name
0610: * @param schemaPattern Schema pattern
0611: * @param viewPattern View name pattern
0612: * @param includeSystemTables Indicate whether to include system tables in search
0613: * @return String[][] List of views matching search filters
0614: * @throws Exception DOCUMENT ME!
0615: */
0616: public static final String[][] getViewsOnly(final String catalog,
0617: final String schemaPattern, final String viewPattern,
0618: final boolean includeSystemTables,
0619: final Connection connection) throws Exception {
0620: String[] tableTypes;
0621:
0622: if (includeSystemTables) {
0623: final String[] types = { DBMetaData.VIEW,
0624: DBMetaData.SYSTEM_TABLE };
0625: tableTypes = types;
0626: } else {
0627: final String[] types = { DBMetaData.VIEW };
0628: tableTypes = types;
0629: }
0630:
0631: return getTables(catalog, schemaPattern, viewPattern,
0632: tableTypes, connection);
0633: }
0634:
0635: /**
0636: * Returns a list of tables and views matching in the passed in filters.
0637: *
0638: * @param catalog Catalog name
0639: * @param schemaPattern Schema pattern
0640: * @param tablePattern Table/View name pattern
0641: * @param includeSystemTables Indicate whether to include system tables in search
0642: * @return String[][] List of tables and views matching search filters
0643: * @throws Exception DOCUMENT ME!
0644: */
0645: public static final String[][] getTablesAndViews(
0646: final String catalog, final String schemaPattern,
0647: final String tablePattern,
0648: final boolean includeSystemTables,
0649: final Connection connection) throws Exception {
0650: String[] tableTypes;
0651:
0652: if (includeSystemTables) {
0653: final String[] types = { DBMetaData.TABLE, DBMetaData.VIEW,
0654: DBMetaData.SYSTEM_TABLE };
0655: tableTypes = types;
0656: } else {
0657: final String[] types = { DBMetaData.TABLE, DBMetaData.VIEW };
0658: tableTypes = types;
0659: }
0660:
0661: return getTables(catalog, schemaPattern, tablePattern,
0662: tableTypes, connection);
0663: }
0664:
0665: /**
0666: * Returns a list of tables/views matching in the passed in filters.
0667: *
0668: * @param catalog Catalog name
0669: * @param schemaPattern Schema pattern
0670: * @param tablePattern Table/View name pattern
0671: * @param tableTypes List of table types to include (ex. TABLE, VIEW)
0672: * @return String[][] List of tables matching search filters
0673: * @throws Exception DOCUMENT ME!
0674: */
0675: public static final String[][] getTables(String catalog,
0676: String schemaPattern, String tablePattern,
0677: final String[] tableTypes, final Connection connection)
0678: throws Exception {
0679: //this.errMsg = "";
0680: try {
0681: if (catalog.equals("")) {
0682: catalog = null;
0683: }
0684: if (schemaPattern.equals("")) {
0685: schemaPattern = null;
0686: }
0687: if (tablePattern.equals("")) {
0688: tablePattern = null;
0689: }
0690:
0691: if (tablePattern != null) {
0692: tablePattern = getJDBCSearchPattern(tablePattern,
0693: connection);
0694: }
0695:
0696: final ResultSet rs = connection.getMetaData().getTables(
0697: catalog, schemaPattern, tablePattern, tableTypes);
0698:
0699: final Vector v = new Vector();
0700: String[][] tables = null; // array of table structures: Name, Catalog, Schema
0701:
0702: while (rs.next()) {
0703: String tableCatalog = rs.getString("TABLE_CAT");
0704: String tableSchema = rs.getString("TABLE_SCHEM");
0705: final String tableName = rs.getString("TABLE_NAME");
0706: final String tableType = rs.getString("TABLE_TYPE");
0707:
0708: if (tableCatalog == null) {
0709: tableCatalog = "";
0710: }
0711: if (tableSchema == null) {
0712: tableSchema = "";
0713: }
0714:
0715: // fill in table info
0716: final String[] tableItem = new String[4]; // hold info for each table
0717: tableItem[DBMetaData.NAME] = tableName;
0718: tableItem[DBMetaData.CATALOG] = tableCatalog;
0719: tableItem[DBMetaData.SCHEMA] = tableSchema;
0720: tableItem[DBMetaData.TYPE] = tableType;
0721:
0722: // add table to Vector
0723: v.add(tableItem);
0724: }
0725:
0726: // now copy Vector to array to return back
0727: if (v.size() > 0) {
0728: tables = new String[v.size()][4];
0729: v.copyInto(tables);
0730: }
0731: rs.close();
0732: return tables;
0733: } catch (final Exception e) {
0734: e.printStackTrace();
0735: //this.errMsg = e.getLocalizedMessage();
0736: throw e;
0737: }
0738: }
0739:
0740: /**
0741: * Gets the prepared statement metadata (parameters, resultsets).
0742: *
0743: * @param catalog Catalog name
0744: * @param schema Schema name
0745: * @param name Prepared statement name
0746: * @param sqlText SQL text of prepared statement
0747: * @return PrepStmt Prepared statement object
0748: * @throws Exception DOCUMENT ME!
0749: */
0750: public static final PrepStmt getPrepStmtMetaData(
0751: final String catalog, final String schema,
0752: final String name, final String sqlText,
0753: final Connection connection) throws Exception {
0754:
0755: //this.errMsg = "";
0756: //this.checkPrepStmtMetaData = false;
0757:
0758: try {
0759: PrepStmt newPrepStmt = null;
0760:
0761: // make sure there is some sql text for the prepared statement
0762: if (sqlText == null || sqlText.equals("")) {
0763: return null;
0764: }
0765:
0766: // fill in name and sql text
0767: newPrepStmt = new PrepStmt(name, catalog, schema, sqlText);
0768:
0769: // prepare the statement
0770: final PreparedStatement pstmt = connection
0771: .prepareStatement(sqlText);
0772:
0773: // Parameter metadata only available through JDBC 3.0, JDK 1.4
0774: // get parameter meta data of the prepared statment from the DB connection
0775: Parameter[] parameters = null;
0776:
0777: // pass sqlText to getPrepStmtParameters(...) so that in case
0778: // the driver does not support java.sql.ParameterMetaData we
0779: // can construct a paramters array using default values. see
0780: // details inside getPrepStmtParameters(...)
0781: parameters = getPrepStmtParameters(pstmt, sqlText,
0782: connection);
0783:
0784: newPrepStmt.setParameters(parameters);
0785:
0786: ResultSetColumn[] cols = null;
0787:
0788: // get the resultset metadata
0789: // of the prepared statment from the DB connection
0790: cols = getPrepStmtResultSetColumns(pstmt);
0791:
0792: // set the prepared statement's resultset columns
0793: newPrepStmt.setResultSetColumns(cols);
0794:
0795: //this.checkPrepStmtMetaData = this.errPrepStmtParameters && this.errPrepStmtResultSetColumns;
0796:
0797: pstmt.close();
0798:
0799: return newPrepStmt;
0800: } catch (final Exception e) {
0801: e.printStackTrace();
0802: //this.errMsg = e.getLocalizedMessage();
0803: throw e;
0804: }
0805: }
0806:
0807: /**
0808: * Returns a list of procedures matching in the passed in filters.
0809: *
0810: * @param catalog Catalog name
0811: * @param schemaPattern Schema pattern
0812: * @param procedurePattern Procedure name pattern
0813: * @return String[][] List of procedures matching search filters
0814: * @throws Exception DOCUMENT ME!
0815: */
0816: public static final String[][] getProcedures(String catalog,
0817: String schemaPattern, String procedurePattern,
0818: final Connection connection) throws Exception {
0819: //this.errMsg = "";
0820: try {
0821: if (catalog.equals("")) {
0822: catalog = null;
0823: }
0824: if (schemaPattern.equals("")) {
0825: schemaPattern = null;
0826: }
0827: if (procedurePattern.equals("")) {
0828: procedurePattern = null;
0829: }
0830:
0831: if (procedurePattern != null) {
0832: procedurePattern = getJDBCSearchPattern(
0833: procedurePattern, connection);
0834: }
0835:
0836: final Vector v = new Vector();
0837: String[][] procedures = null; // array of procedure structures: Name, Catalog, Schema,
0838: // Type
0839:
0840: final ResultSet rs = connection.getMetaData()
0841: .getProcedures(catalog, schemaPattern,
0842: procedurePattern);
0843: while (rs.next()) {
0844: String procedureCatalog = rs.getString("PROCEDURE_CAT");
0845: String procedureSchema = rs
0846: .getString("PROCEDURE_SCHEM");
0847: final String procedureName = rs
0848: .getString("PROCEDURE_NAME");
0849: final String procedureType = getProcedureTypeDescription(rs
0850: .getShort("PROCEDURE_TYPE"));
0851:
0852: if (procedureCatalog == null) {
0853: procedureCatalog = "";
0854: }
0855: if (procedureSchema == null) {
0856: procedureSchema = "";
0857: }
0858:
0859: // fill in procedure info
0860: final String[] procedureItem = new String[4]; // hold info for each procedure
0861: procedureItem[DBMetaData.NAME] = procedureName;
0862: procedureItem[DBMetaData.CATALOG] = procedureCatalog;
0863: procedureItem[DBMetaData.SCHEMA] = procedureSchema;
0864: procedureItem[DBMetaData.TYPE] = procedureType;
0865:
0866: // add procedure to Vector
0867: v.add(procedureItem);
0868: }
0869:
0870: // now copy Vector to array to return back
0871: if (v.size() > 0) {
0872: procedures = new String[v.size()][4];
0873: v.copyInto(procedures);
0874: }
0875: rs.close();
0876: return procedures;
0877: } catch (final Exception e) {
0878: e.printStackTrace();
0879: //this.errMsg = e.getLocalizedMessage();
0880: throw e;
0881: }
0882: }
0883:
0884: /**
0885: * Returns a list of primary keys for a table.
0886: *
0887: * @param tcatalog Catalog name
0888: * @param tschema Schema name
0889: * @param tname Table name
0890: * @return List List of primary keys
0891: * @throws Exception DOCUMENT ME!
0892: */
0893: public static final List getPrimaryKeys(String tcatalog,
0894: String tschema, final String tname, final Connection v)
0895: throws Exception {
0896: List pkList = Collections.EMPTY_LIST;
0897: ResultSet rs = null;
0898:
0899: //this.errMsg = "";
0900: try {
0901: if (tcatalog.equals("")) {
0902: tcatalog = null;
0903: }
0904: if (tschema.equals("")) {
0905: tschema = null;
0906: }
0907:
0908: rs = v.getMetaData().getPrimaryKeys(tcatalog, tschema,
0909: tname);
0910: if (v.getMetaData().getDriverName().startsWith("JDBC-ODBC")) {
0911: pkList = KeyColumn.createPrimaryKeyColumnList(rs, true);
0912: } else {
0913: pkList = KeyColumn
0914: .createPrimaryKeyColumnList(rs, false);
0915: }
0916: } catch (final Exception e) {
0917: e.printStackTrace();
0918: //this.errMsg = e.getLocalizedMessage();
0919: throw e;
0920: } finally {
0921: if (rs != null) {
0922: try {
0923: rs.close();
0924: } catch (final SQLException e) {
0925: /* Ignore */;
0926: }
0927: }
0928: }
0929:
0930: return pkList;
0931: }
0932:
0933: /**
0934: * Returns a list of foreign keys for a table.
0935: *
0936: * @param tcatalog Catalog name
0937: * @param tschema Schema name
0938: * @param tname Table name
0939: * @return List List of foreign keys
0940: * @throws Exception DOCUMENT ME!
0941: */
0942: public static final List getForeignKeys(String tcatalog,
0943: String tschema, final String tname,
0944: final Connection connection) throws Exception {
0945: //this.errMsg = "";
0946: List fkList = Collections.EMPTY_LIST;
0947: ResultSet rs = null;
0948:
0949: try {
0950: if (tcatalog.equals("")) {
0951: tcatalog = null;
0952: }
0953: if (tschema.equals("")) {
0954: tschema = null;
0955: }
0956: try {
0957: rs = connection.getMetaData().getImportedKeys(tcatalog,
0958: tschema, tname);
0959: fkList = ForeignKeyColumn
0960: .createForeignKeyColumnList(rs);
0961: } catch (final Exception e) {
0962: e.printStackTrace();
0963: DBMetaData.mLogger
0964: .warning("JDBC driver does not support java.sql.ParameterMetaData "
0965: + e.getMessage());
0966: //this.errMsg = e.getLocalizedMessage();
0967: }
0968: } catch (final Exception e) {
0969: e.printStackTrace();
0970: //this.errMsg = e.getLocalizedMessage();
0971: throw e;
0972: } finally {
0973: if (rs != null) {
0974: try {
0975: rs.close();
0976: } catch (final SQLException e) {
0977: /* Ignore */;
0978: }
0979: }
0980: }
0981:
0982: return fkList;
0983: }
0984:
0985: /**
0986: * Gets the procedure metadata (parameters).
0987: *
0988: * @param pcatalog Catalog name
0989: * @param pschema Schema name
0990: * @param pname Procedure name
0991: * @param ptype Procedure type
0992: * @return Procedure object
0993: * @throws Exception DOCUMENT ME!
0994: */
0995: public static final Procedure getProcedureMetaData(String pcatalog,
0996: String pschema, final String pname, final String ptype,
0997: final Connection connection) throws Exception {
0998: //this.errMsg = "";
0999: try {
1000: // create a new procedure object
1001: final Procedure newProcedure = new Procedure(pname,
1002: pcatalog, pschema, ptype);
1003: final Vector v = new Vector();
1004:
1005: if (pcatalog.equals("")) {
1006: pcatalog = null;
1007: }
1008: if (pschema.equals("")) {
1009: pschema = null;
1010: }
1011:
1012: // get procedure parameter information
1013: final ResultSet rs = connection.getMetaData()
1014: .getProcedureColumns(pcatalog, pschema, pname, "%");
1015:
1016: Parameter[] parameters = null;
1017: int pos = 0;
1018: boolean hasReturn = false;
1019:
1020: while (rs.next()) {
1021: pos++;
1022: String parmName = rs.getString("COLUMN_NAME");
1023: if (parmName != null) {
1024: // strip off "@" in front of parameter name
1025: if (parmName.charAt(0) == '@') {
1026: parmName = parmName.substring(1);
1027: }
1028: } else {
1029: // parameter name is not return - call it "param<pos>"
1030: parmName = "param" + String.valueOf(pos);
1031: }
1032: String sqlType = DBMetaData.getSQLTypeDescription(rs
1033: .getInt("DATA_TYPE"));
1034: String javaType = getJavaFromSQLTypeDescription(sqlType);
1035: // added abey for Procedure ResultSet
1036: final int dataType = rs.getInt("DATA_TYPE");
1037: if (dataType == java.sql.Types.OTHER
1038: && rs.getString("TYPE_NAME").equalsIgnoreCase(
1039: "REF CURSOR")) {
1040: sqlType = "RESULTSET";
1041: javaType = "java.sql.ResultSet";
1042: }
1043: final String paramType = getParamTypeDescription(rs
1044: .getShort("COLUMN_TYPE"));
1045: final int nullable = rs.getShort("NULLABLE");
1046: final int numericPrecision = rs.getInt("PRECISION");
1047: final short numericScale = rs.getShort("SCALE");
1048:
1049: // create a parameter and add it to the vector
1050: final Parameter parm = new Parameter(parmName, javaType);
1051: boolean isNullable = false;
1052: if (nullable == DatabaseMetaData.procedureNullable) {
1053: isNullable = true;
1054: }
1055: parm.setJavaType(javaType);
1056: parm.setSqlType(sqlType);
1057: parm.setParamType(paramType);
1058: parm.setOrdinalPosition(pos);
1059: parm.setNumericPrecision(numericPrecision);
1060: parm.setNumericScale(numericScale);
1061: parm.setIsNullable(isNullable);
1062:
1063: if (paramType.equals("RETURN")) {
1064: hasReturn = true;
1065: }
1066:
1067: // add to vector
1068: v.add(parm);
1069: }
1070: rs.close();
1071:
1072: // now copy Vector to array
1073: if (v.size() > 0) {
1074: parameters = new Parameter[v.size()];
1075: v.copyInto(parameters);
1076: }
1077:
1078: // now set up parameters in the procedure to return
1079: newProcedure.setParameters(parameters);
1080: newProcedure.setHasReturn(hasReturn);
1081:
1082: return newProcedure;
1083: } catch (final Exception e) {
1084: e.printStackTrace();
1085: //this.errMsg = e.getLocalizedMessage();
1086: throw e;
1087: }
1088: }
1089:
1090: /**
1091: * Gets the table metadata (columns).
1092: *
1093: * @param tcatalog Catalog name
1094: * @param tschema Schema name
1095: * @param tname Table name
1096: * @param ttype Table type
1097: * @return Table object
1098: * @throws Exception DOCUMENT ME!
1099: */
1100: public static final Table getTableMetaData(String tcatalog,
1101: String tschema, final String tname, final String ttype,
1102: final Connection connection) throws Exception {
1103: //this.errMsg = "";
1104: ResultSet rs = null;
1105:
1106: try {
1107: // create a new Table object
1108: final Table newTable = new Table(tname, tcatalog, tschema,
1109: ttype);
1110: final Vector v = new Vector();
1111:
1112: if (tcatalog.equals("")) {
1113: tcatalog = null;
1114: }
1115:
1116: if (tschema.equals("")) {
1117: tschema = null;
1118: }
1119:
1120: // get table column information
1121: rs = connection.getMetaData().getColumns(tcatalog, tschema,
1122: tname, "%");
1123:
1124: TableColumn[] columns = null;
1125:
1126: while (rs.next()) {
1127: final String defaultValue = rs.getString("COLUMN_DEF");
1128:
1129: final int sqlTypeCode = rs.getInt("DATA_TYPE");
1130:
1131: final String colName = rs.getString("COLUMN_NAME");
1132: final String sqlType = DBMetaData
1133: .getSQLTypeDescription(sqlTypeCode);
1134: final String javaType = getJavaFromSQLTypeDescription(sqlType);
1135:
1136: final int position = rs.getInt("ORDINAL_POSITION");
1137:
1138: final int scale = rs.getInt("DECIMAL_DIGITS");
1139: final int precision = rs.getInt("COLUMN_SIZE");
1140: final int radix = rs.getInt("NUM_PREC_RADIX");
1141:
1142: // create a table column and add it to the vector
1143: final TableColumn col = new TableColumn(colName,
1144: javaType);
1145: boolean isNullable = false;
1146: if (rs.getString("IS_NULLABLE").equals("YES")) {
1147: isNullable = true;
1148: }
1149: col.setJavaType(javaType);
1150: col.setSqlType(sqlType);
1151: col.setIsNullable(isNullable);
1152: col.setIsSelected(true);
1153: col.setIsPrimaryKey(false);
1154: col.setIsForeignKey(false);
1155: col.setSqlTypeCode(sqlTypeCode);
1156:
1157: col.setOrdinalPosition(position);
1158: col.setNumericPrecision(precision);
1159: col.setNumericScale(scale);
1160: col.setNumericRadix(radix);
1161:
1162: if (defaultValue != null) {
1163: col.setDefaultValue(defaultValue.trim());
1164: }
1165:
1166: // add to vector
1167: v.add(col);
1168: }
1169:
1170: // now copy Vector to array
1171: if (v.size() > 0) {
1172: columns = new TableColumn[v.size()];
1173: v.copyInto(columns);
1174: }
1175:
1176: // now set up columns in the table to return
1177: newTable.setColumns(columns);
1178:
1179: // now check the columns that are primary keys
1180: checkPrimaryKeys(newTable, connection);
1181:
1182: // now check the columns that are foreign keys
1183: checkForeignKeys(newTable, connection);
1184:
1185: // catch exceptions for this as index only makes sense for
1186: // tables and not views (can't check the table type because it's dependent on driver)
1187: try {
1188: // get index info for this table
1189: rs = connection.getMetaData().getIndexInfo(tcatalog,
1190: tschema, tname, false, true);
1191: newTable.setIndexList(IndexColumn.createIndexList(rs));
1192: } catch (final Exception e) {
1193: // ignore and continue
1194: //this.errMsg = e.getLocalizedMessage();
1195: }
1196:
1197: return newTable;
1198: } catch (final Exception e) {
1199: e.printStackTrace();
1200: //this.errMsg = e.getLocalizedMessage();
1201: throw e;
1202: } finally {
1203: if (rs != null) {
1204: try {
1205: rs.close();
1206: } catch (final SQLException e) {
1207: /* Ignore... */;
1208: }
1209: }
1210: }
1211: }
1212:
1213: public static final Table getTableMetaDataForODBCDriver(
1214: String tcatalog, String tschema, final String tname,
1215: final String ttype, final Connection connection)
1216: throws Exception {
1217: //this.errMsg = "";
1218: ResultSet rs = null;
1219:
1220: try {
1221: // create a new Table object
1222: final Table newTable = new Table(tname, tcatalog, tschema,
1223: ttype);
1224: final Vector v = new Vector();
1225:
1226: if (tcatalog.equals("")) {
1227: tcatalog = null;
1228: }
1229:
1230: if (tschema.equals("")) {
1231: tschema = null;
1232: }
1233:
1234: // get table column information
1235: rs = connection.getMetaData().getColumns(tcatalog, tschema,
1236: tname, "%");
1237:
1238: TableColumn[] columns = null;
1239:
1240: while (rs.next()) {
1241: // {13=COLUMN_DEF, 12=REMARKS, 11=NULLABLE, 10=NUM_PREC_RADIX,
1242: // 9=DECIMAL_DIGITS, 8=BUFFER_LENGTH, 7=COLUMN_SIZE,
1243: // 6=TYPE_NAME,
1244: // 5=DATA_TYPE, 4=COLUMN_NAME, 3=TABLE_NAME, 2=TABLE_SCHEM,
1245: // 1=TABLE_CAT}
1246: String tablecat = rs.getString(1);
1247: String tablesch = rs.getString(2);
1248: String tablename = rs.getString(3);
1249: String colName = rs.getString(4);
1250: int sqlTypeCode = rs.getInt(5);
1251: String typename = rs.getString(6);
1252: int precision = rs.getInt(7);
1253: int bufflen = rs.getInt(8);
1254: int scale = rs.getInt(9);
1255: int radix = rs.getInt(10);
1256: boolean nullable = rs.getBoolean(11);
1257: String remarks = rs.getString(12);
1258: String defaultValue = rs.getString(13);
1259:
1260: final String sqlType = DBMetaData
1261: .getSQLTypeDescription(sqlTypeCode);
1262: final String javaType = getJavaFromSQLTypeDescription(sqlType);
1263:
1264: // create a table column and add it to the vector
1265: final TableColumn col = new TableColumn(colName,
1266: javaType);
1267: boolean isNullable = false;
1268: if (rs.getString("IS_NULLABLE").equals("YES")) {
1269: isNullable = true;
1270: }
1271: col.setJavaType(javaType);
1272: col.setSqlType(sqlType);
1273: col.setIsNullable(isNullable);
1274: col.setIsSelected(true);
1275: col.setIsPrimaryKey(false);
1276: col.setIsForeignKey(false);
1277: col.setSqlTypeCode(sqlTypeCode);
1278: //col.setOrdinalPosition(position);
1279: col.setNumericPrecision(precision);
1280: col.setNumericScale(scale);
1281: col.setNumericRadix(radix);
1282:
1283: if (defaultValue != null) {
1284: col.setDefaultValue(defaultValue.trim());
1285: }
1286:
1287: // add to vector
1288: v.add(col);
1289: }
1290:
1291: // now copy Vector to array
1292: if (v.size() > 0) {
1293: columns = new TableColumn[v.size()];
1294: v.copyInto(columns);
1295: }
1296:
1297: // now set up columns in the table to return
1298: newTable.setColumns(columns);
1299:
1300: // now check the columns that are primary keys
1301: checkPrimaryKeys(newTable, connection);
1302:
1303: // now check the columns that are foreign keys
1304: checkForeignKeys(newTable, connection);
1305:
1306: // catch exceptions for this as index only makes sense for
1307: // tables and not views (can't check the table type because it's dependent on driver)
1308: try {
1309: // get index info for this table
1310: rs = connection.getMetaData().getIndexInfo(tcatalog,
1311: tschema, tname, false, true);
1312: newTable.setIndexList(IndexColumn.createIndexList(rs));
1313: } catch (final Exception e) {
1314: // ignore and continue
1315: //this.errMsg = e.getLocalizedMessage();
1316: }
1317:
1318: return newTable;
1319: } catch (final Exception e) {
1320: e.printStackTrace();
1321: //this.errMsg = e.getLocalizedMessage();
1322: throw e;
1323: } finally {
1324: if (rs != null) {
1325: try {
1326: rs.close();
1327: } catch (final SQLException e) {
1328: /* Ignore... */;
1329: }
1330: }
1331: }
1332: }
1333:
1334: /**
1335: * Converts a JDBC SQL Type to a Java Type.
1336: *
1337: * @param sqlType JDBC SQL Type
1338: * @return Java Type
1339: */
1340: public static final String getJavaFromSQLTypeDescription(
1341: final String sqlType) {
1342: Object t;
1343: String javaType = "java.lang.String"; // default value
1344: t = DBMetaData.SQLTOJAVATYPES.get(sqlType);
1345:
1346: if (t != null) {
1347: javaType = t.toString();
1348: }
1349:
1350: return javaType;
1351: }
1352:
1353: /**
1354: * Converts the numeric value of a JDBC SQL type to a display string.
1355: *
1356: * @param type JDBC numeric SQL type value
1357: * @return JDBC SQL type string
1358: */
1359: public static final String getSQLTypeDescription(final int type) {
1360: // returns a String representing the passed in numeric
1361: // SQL type
1362: switch (type) {
1363: case java.sql.Types.ARRAY:
1364: return "ARRAY";
1365: case java.sql.Types.BIGINT:
1366: return "BIGINT";
1367: case java.sql.Types.BINARY:
1368: return "BINARY";
1369: case java.sql.Types.BIT:
1370: return "BIT";
1371: case java.sql.Types.BLOB:
1372: return "BLOB";
1373: case 16:
1374: // case java.sql.Types.BOOLEAN:
1375: return "BOOLEAN";
1376: case java.sql.Types.CHAR:
1377: return "CHAR";
1378: case java.sql.Types.CLOB:
1379: return "CLOB";
1380: case 70:
1381: // case java.sql.Types.DATALINK:
1382: return "DATALINK";
1383: case java.sql.Types.DATE:
1384: return "DATE";
1385: case java.sql.Types.DECIMAL:
1386: return "DECIMAL";
1387: case java.sql.Types.DOUBLE:
1388: return "DOUBLE";
1389: case java.sql.Types.FLOAT:
1390: return "FLOAT";
1391: case java.sql.Types.INTEGER:
1392: return "INTEGER";
1393: case java.sql.Types.JAVA_OBJECT:
1394: return "JAVA_OBJECT";
1395: case java.sql.Types.LONGVARBINARY:
1396: return "LONGVARBINARY";
1397: case java.sql.Types.LONGVARCHAR:
1398: return "LONGVARCHAR";
1399: case java.sql.Types.NULL:
1400: return "NULL";
1401: case java.sql.Types.NUMERIC:
1402: return "NUMERIC";
1403: case java.sql.Types.OTHER:
1404: return "OTHER";
1405: case java.sql.Types.REAL:
1406: return "REAL";
1407: case java.sql.Types.REF:
1408: return "REF";
1409: case java.sql.Types.SMALLINT:
1410: return "SMALLINT";
1411: case java.sql.Types.STRUCT:
1412: return "STRUCT";
1413: case java.sql.Types.TIME:
1414: return "TIME";
1415: case java.sql.Types.TIMESTAMP:
1416: return "TIMESTAMP";
1417: case java.sql.Types.TINYINT:
1418: return "TINYINT";
1419: case java.sql.Types.VARBINARY:
1420: return "VARBINARY";
1421: case java.sql.Types.VARCHAR:
1422: return "VARCHAR";
1423: }
1424: // all others default to OTHER
1425: return "OTHER";
1426: }
1427:
1428: /**
1429: * Converts a text representation of a JDBC SQL type to a display string.
1430: *
1431: * @param sqlText JDBC SQL type string
1432: * @return JDBC numeric SQL type value
1433: */
1434: public static final int getSQLTypeCode(String sqlText) {
1435: if (sqlText == null) {
1436: throw new IllegalArgumentException(
1437: "Must supply non-null String value for sqlText.");
1438: }
1439:
1440: sqlText = sqlText.trim().toUpperCase();
1441: for (int i = 0; i < DBMetaData.SQLTYPES.length; i++) {
1442: if (DBMetaData.SQLTYPES[i].equals(sqlText)) {
1443: return DBMetaData.SQLTYPE_CODES[i];
1444: }
1445: }
1446:
1447: return java.sql.Types.OTHER;
1448: }
1449:
1450: private static final String getJavaTypeDescription(final int type) {
1451: // converts a numeric SQL type to a Java type
1452: String javaType = "java.lang.String";
1453:
1454: switch (type) {
1455: case java.sql.Types.ARRAY:
1456: javaType = "java.sql.ARRAY";
1457: case java.sql.Types.BIGINT:
1458: javaType = "long";
1459: case java.sql.Types.BINARY:
1460: javaType = "byte[]";
1461: case java.sql.Types.BIT:
1462: javaType = "boolean";
1463: case java.sql.Types.BLOB:
1464: javaType = "java.sql.Blob";
1465: // case java.sql.Types.BOOLEAN:
1466: // javaType = "boolean";
1467: case java.sql.Types.CHAR:
1468: javaType = "java.lang.String";
1469: case java.sql.Types.CLOB:
1470: javaType = "java.sql.Clob";
1471: case java.sql.Types.DATE:
1472: javaType = "java.sql.Date";
1473: case java.sql.Types.DECIMAL:
1474: javaType = "java.math.BigDecimal";
1475: case java.sql.Types.DOUBLE:
1476: javaType = "double";
1477: case java.sql.Types.FLOAT:
1478: javaType = "double";
1479: case java.sql.Types.INTEGER:
1480: javaType = "int";
1481: case java.sql.Types.LONGVARBINARY:
1482: javaType = "byte[]";
1483: case java.sql.Types.LONGVARCHAR:
1484: javaType = "java.lang.String";
1485: case java.sql.Types.NUMERIC:
1486: javaType = "java.math.BigDecimal";
1487: // case java.sql.Types.OTHER:
1488: // javaType = "java.sql.Blob";
1489: case java.sql.Types.REAL:
1490: javaType = "float";
1491: case java.sql.Types.REF:
1492: javaType = "java.sql.Ref";
1493: case java.sql.Types.SMALLINT:
1494: javaType = "short";
1495: case java.sql.Types.STRUCT:
1496: javaType = "java.sql.Struct";
1497: case java.sql.Types.TIME:
1498: javaType = "java.sql.Time";
1499: case java.sql.Types.TIMESTAMP:
1500: javaType = "java.sql.Timestamp";
1501: case java.sql.Types.TINYINT:
1502: javaType = "byte";
1503: case java.sql.Types.VARBINARY:
1504: javaType = "byte[]";
1505: case java.sql.Types.VARCHAR:
1506: javaType = "java.lang.String";
1507: }
1508: return javaType;
1509: }
1510:
1511: private static final String getParamTypeDescription(final int type) {
1512: String descr = "";
1513:
1514: if (type == DatabaseMetaData.procedureColumnIn) {
1515: descr = "IN";
1516: } else if (type == DatabaseMetaData.procedureColumnInOut) {
1517: descr = "INOUT";
1518: } else if (type == DatabaseMetaData.procedureColumnOut) {
1519: descr = "OUT";
1520: } else if (type == DatabaseMetaData.procedureColumnReturn) {
1521: descr = "RETURN";
1522: } else if (type == DatabaseMetaData.procedureColumnResult) {
1523: descr = "RESULT";
1524: } else {
1525: descr = "UNKNOWN";
1526: }
1527:
1528: return descr;
1529: }
1530:
1531: private static final String getProcedureTypeDescription(
1532: final int type) {
1533: // converts the numeric procedure type code to a string description
1534: String descr = "";
1535: if (type == DatabaseMetaData.procedureNoResult) {
1536: descr = Procedure.PROCEDURE;
1537: } else if (type == DatabaseMetaData.procedureReturnsResult) {
1538: descr = Procedure.FUNCTION;
1539: } else if (type == DatabaseMetaData.procedureResultUnknown) {
1540: descr = Procedure.UNKNOWN;
1541: } else {
1542: descr = Procedure.UNKNOWN;
1543: }
1544:
1545: return descr;
1546: }
1547:
1548: private static final String getPrepStmtParamTypeDescription(
1549: final int type) {
1550: String descr = "";
1551:
1552: if (type == ParameterMetaData.parameterModeIn) {
1553: descr = "IN";
1554: } else if (type == ParameterMetaData.parameterModeInOut) {
1555: descr = "INOUT";
1556: } else if (type == ParameterMetaData.parameterModeOut) {
1557: descr = "OUT";
1558: } else if (type == ParameterMetaData.parameterModeUnknown) {
1559: descr = "UNKNOWN";
1560: } else {
1561: descr = "UNKNOWN";
1562: }
1563:
1564: return descr;
1565: }
1566:
1567: private static final String replaceAllChars(final String orig,
1568: final char oldChar, final String replStr) {
1569: String newString = "";
1570:
1571: for (int i = 0; i < orig.length(); i++) {
1572: if (orig.charAt(i) == oldChar) {
1573: newString = newString + replStr;
1574: } else {
1575: newString = newString + orig.charAt(i);
1576: }
1577: }
1578: return newString;
1579: }
1580:
1581: /**
1582: * Get String representing current error message, if any.
1583: *
1584: * @return error message
1585: */
1586: /*public String getErrString() {
1587: return this.errMsg;
1588: }*/
1589:
1590: private static final Parameter[] getPrepStmtParameters(
1591: final PreparedStatement pstmt, final String sqlText,
1592: final Connection connection) {
1593: String errMsg = "";
1594: //errPrepStmtParameters = false;
1595: Parameter[] parameters = null;
1596:
1597: try {
1598: ParameterMetaData pmeta = null;
1599: try {
1600: pmeta = pstmt.getParameterMetaData();
1601: }
1602: // just catch all exception since
1603: // attunity throws java.lang.AbstractMethodError
1604: // SequeLink throws SQLException
1605: catch (final AbstractMethodError absE) {
1606: DBMetaData.mLogger.log(Level.INFO,
1607: "JDBC driver does not support java.sql.ParameterMetaData "
1608: + absE.getMessage());
1609: return handleUnsupportParameterMetaData(sqlText);
1610: } catch (final SQLException sqlE) {
1611: DBMetaData.mLogger.log(Level.INFO,
1612: "JDBC driver does not support java.sql.ParameterMetaData "
1613: + sqlE.getMessage());
1614: return handleUnsupportParameterMetaData(sqlText);
1615: } catch (final Exception e) {
1616: DBMetaData.mLogger.log(Level.INFO,
1617: "JDBC driver does not support java.sql.ParameterMetaData "
1618: + e.getMessage());
1619: return handleUnsupportParameterMetaData(sqlText);
1620: }
1621:
1622: if (pmeta != null) {
1623: final int numParams = pmeta.getParameterCount();
1624: if (numParams > 0) {
1625: parameters = new Parameter[numParams];
1626: // get info for each parameter
1627: for (int i = 1; i <= numParams; i++) {
1628: final Parameter currParam = new Parameter();
1629: final String paramname = "param"
1630: + String.valueOf(i);
1631: currParam.setName(paramname);
1632:
1633: // try to get the sql type info - default to VARCHAR
1634: String sqltype = "VARCHAR";
1635: try {
1636: sqltype = DBMetaData
1637: .getSQLTypeDescription(pmeta
1638: .getParameterType(i));
1639: } catch (final SQLException e) {
1640: // default to VARCHAR if we can't get the type
1641: //this.errPrepStmtParameters = true;
1642: e.printStackTrace();
1643: errMsg = e.getLocalizedMessage();
1644: }
1645:
1646: // try to get the java type info - default to String
1647: /**
1648: * Changing it to not use metadata class name and instead use the HashMap
1649: * SQLTOJAVATYPES. Without the change the parameter datatypes
1650: * java.lang.Double and WSDLGenerator look up list exepects native type
1651: * double, float, short etc.
1652: */
1653: String javatype = "java.lang.String";
1654: javatype = getJavaFromSQLTypeDescription(sqltype);
1655:
1656: // try to get the numeric precision, default to 0
1657: int precision = 0;
1658: try {
1659: precision = pmeta.getPrecision(i);
1660: } catch (final SQLException e) {
1661: //this.errPrepStmtParameters = true;
1662: e.printStackTrace();
1663: errMsg = e.getLocalizedMessage();
1664: }
1665:
1666: // try to get the numeric scale, default to 0
1667: int scale = 0;
1668: try {
1669: scale = pmeta.getScale(i);
1670: } catch (final SQLException e) {
1671: //this.errPrepStmtParameters = true;
1672: e.printStackTrace();
1673: errMsg = e.getLocalizedMessage();
1674: }
1675:
1676: // try to get the param type, default to IN
1677: String paramType = "IN";
1678: try {
1679: paramType = getPrepStmtParamTypeDescription(pmeta
1680: .getParameterMode(i));
1681: } catch (final SQLException e) {
1682: //this.errPrepStmtParameters = true;
1683: e.printStackTrace();
1684: errMsg = e.getLocalizedMessage();
1685: }
1686:
1687: // try to get is nullable, default to TRUE
1688: boolean isNullable = true;
1689: try {
1690: if (pmeta.isNullable(i) == java.sql.ParameterMetaData.parameterNullable) {
1691: isNullable = true;
1692: } else {
1693: isNullable = false;
1694: }
1695: } catch (final SQLException e) {
1696: //this.errPrepStmtParameters = true;
1697: e.printStackTrace();
1698: errMsg = e.getLocalizedMessage();
1699: }
1700:
1701: currParam.setJavaType(javatype);
1702: currParam.setSqlType(sqltype);
1703: currParam.setNumericPrecision(precision);
1704: currParam.setNumericScale(scale);
1705: currParam.setOrdinalPosition(i);
1706: currParam.setParamType(paramType);
1707: currParam.setIsNullable(isNullable);
1708:
1709: parameters[i - 1] = currParam;
1710: }
1711: }
1712: }
1713: } catch (final Exception e) {
1714: // parameter metadata not supported
1715: parameters = null;
1716: //this.errPrepStmtParameters = true;
1717: e.printStackTrace();
1718: errMsg = e.getLocalizedMessage();
1719: }
1720:
1721: return parameters;
1722: }
1723:
1724: private static final ResultSetColumn[] getPrepStmtResultSetColumns(
1725: final PreparedStatement pstmt) {
1726: String errMsg = "";
1727: //this.errPrepStmtResultSetColumns = false;
1728: ResultSetColumn[] cols = null;
1729: try {
1730: final ResultSetMetaData rsmd = pstmt.getMetaData();
1731: int count = 0;
1732: if (rsmd != null) {
1733: count = rsmd.getColumnCount();
1734: } else {
1735: //this.errPrepStmtResultSetColumns = true;
1736: }
1737: if (count > 0) {
1738: // scroll through the resultset column information
1739: cols = new ResultSetColumn[count];
1740: for (int i = 1; i <= count; i++) {
1741: final ResultSetColumn currCol = new ResultSetColumn();
1742: currCol.setName(rsmd.getColumnName(i));
1743: currCol.setSqlType(DBMetaData
1744: .getSQLTypeDescription(rsmd
1745: .getColumnType(i)));
1746: currCol
1747: .setJavaType(getJavaFromSQLTypeDescription(currCol
1748: .getSqlType()));
1749: currCol.setOrdinalPosition(i);
1750: currCol.setNumericPrecision(rsmd.getPrecision(i));
1751: currCol.setNumericScale(rsmd.getScale(i));
1752:
1753: if (rsmd.isNullable(i) == DatabaseMetaData.columnNullable) {
1754: currCol.setIsNullable(true);
1755: } else {
1756: currCol.setIsNullable(false);
1757: }
1758:
1759: cols[i - 1] = currCol;
1760: }
1761: }
1762:
1763: } catch (final Exception e) {
1764: // resultset column metadata not supported
1765: //this.errPrepStmtResultSetColumns = true;
1766: cols = null;
1767: e.printStackTrace();
1768: errMsg = e.getLocalizedMessage();
1769: }
1770:
1771: return cols;
1772: }
1773:
1774: /**
1775: * check all the used APIs to see if they are supported.
1776: *
1777: * @param type none
1778: * @return boolean
1779: */
1780: /*public boolean checkAPIsForSupport() {
1781: boolean support = true;
1782:
1783: try {
1784: this.dbmeta.supportsBatchUpdates();
1785: } catch (final SQLException e) {
1786: support = false;
1787: DBMetaData.mLogger.warning("supportsBatchUpdates() failed - " + e.getMessage());
1788: } catch (final AbstractMethodError errE) {
1789: support = false;
1790: DBMetaData.mLogger.warning("supportsBatchUpdates() failed - " + errE.getMessage());
1791: }
1792: try {
1793: this.dbmeta.supportsCatalogsInDataManipulation();
1794: } catch (final SQLException e) {
1795: support = false;
1796: DBMetaData.mLogger.warning("supportsCatalogsInDataManipulation() failed - " + e.getMessage());
1797: } catch (final AbstractMethodError errE) {
1798: support = false;
1799: DBMetaData.mLogger.warning("supportsCatalogsInDataManipulation() failed - " + errE.getMessage());
1800: }
1801: try {
1802: this.dbmeta.supportsCatalogsInProcedureCalls();
1803: } catch (final SQLException e) {
1804: support = false;
1805: DBMetaData.mLogger.warning("supportsCatalogsInProcedureCalls() failed - " + e.getMessage());
1806: } catch (final AbstractMethodError errE) {
1807: support = false;
1808: DBMetaData.mLogger.warning("supportsCatalogsInProcedureCalls() failed - " + errE.getMessage());
1809: }
1810: try {
1811: this.dbmeta.supportsCatalogsInTableDefinitions();
1812: } catch (final SQLException e) {
1813: support = false;
1814: DBMetaData.mLogger.warning("supportsCatalogsInTableDefinitions() failed - " + e.getMessage());
1815: } catch (final AbstractMethodError errE) {
1816: support = false;
1817: DBMetaData.mLogger.warning("supportsCatalogsInTableDefinitions() failed - " + errE.getMessage());
1818: }
1819: try {
1820: this.dbmeta.supportsCatalogsInIndexDefinitions();
1821: } catch (final AbstractMethodError errE) {
1822: support = false;
1823: DBMetaData.mLogger.warning("supportsCatalogsInIndexDefinitions() failed - " + errE.getMessage());
1824: } catch (final SQLException e) {
1825: support = false;
1826: DBMetaData.mLogger.warning("supportsCatalogsInIndexDefinitions() failed - " + e.getMessage());
1827: }
1828: try {
1829: this.dbmeta.supportsCatalogsInPrivilegeDefinitions();
1830: } catch (final SQLException e) {
1831: support = false;
1832: DBMetaData.mLogger.warning("supportsCatalogsInPrivilegeDefinitions() failed - " + e.getMessage());
1833: } catch (final AbstractMethodError errE) {
1834: support = false;
1835: DBMetaData.mLogger.warning("supportsCatalogsInPrivilegeDefinitions() failed - " + errE.getMessage());
1836: }
1837: try {
1838: this.dbmeta.supportsConvert();
1839: } catch (final SQLException e) {
1840: support = false;
1841: DBMetaData.mLogger.warning("supportsConvert() failed - " + e.getMessage());
1842: } catch (final AbstractMethodError errE) {
1843: support = false;
1844: DBMetaData.mLogger.warning("supportsConvert() failed - " + errE.getMessage());
1845: }
1846: try {
1847: this.dbmeta.supportsExpressionsInOrderBy();
1848: } catch (final SQLException e) {
1849: support = false;
1850: DBMetaData.mLogger.warning("supportsExpressionsInOrderBy() failed - " + e.getMessage());
1851: } catch (final AbstractMethodError errE) {
1852: support = false;
1853: DBMetaData.mLogger.warning("supportsExpressionsInOrderBy() failed - " + errE.getMessage());
1854: }
1855: try {
1856: this.dbmeta.supportsLikeEscapeClause();
1857: } catch (final SQLException e) {
1858: support = false;
1859: DBMetaData.mLogger.warning("supportsLikeEscapeClause() failed - " + e.getMessage());
1860: } catch (final AbstractMethodError errE) {
1861: support = false;
1862: DBMetaData.mLogger.warning("supportsLikeEscapeClause() failed - " + errE.getMessage());
1863: }
1864: try {
1865: this.dbmeta.supportsNamedParameters();
1866: } catch (final Exception e) {
1867: support = false;
1868: DBMetaData.mLogger.warning("supportsNamedParameters() failed - " + e.getMessage());
1869: } catch (final AbstractMethodError errE) {
1870: support = false;
1871: DBMetaData.mLogger.warning("supportsNamedParameters() failed - " + errE.getMessage());
1872: }
1873: try {
1874: this.dbmeta.supportsNonNullableColumns();
1875: } catch (final SQLException e) {
1876: support = false;
1877: DBMetaData.mLogger.warning("supportsNonNullableColumns() failed - " + e.getMessage());
1878: } catch (final AbstractMethodError errE) {
1879: support = false;
1880: DBMetaData.mLogger.warning("supportsNonNullableColumns() failed - " + errE.getMessage());
1881: }
1882: try {
1883: this.dbmeta.supportsOuterJoins();
1884: } catch (final SQLException e) {
1885: support = false;
1886: DBMetaData.mLogger.warning("supportsOuterJoins() failed - " + e.getMessage());
1887: } catch (final AbstractMethodError errE) {
1888: support = false;
1889: DBMetaData.mLogger.warning("supportsOuterJoins() failed - " + errE.getMessage());
1890: }
1891: try {
1892: this.dbmeta.supportsPositionedDelete();
1893: } catch (final SQLException e) {
1894: support = false;
1895: DBMetaData.mLogger.warning("supportsPositionedDelete() failed - " + e.getMessage());
1896: } catch (final AbstractMethodError errE) {
1897: support = false;
1898: DBMetaData.mLogger.warning("supportsPositionedDelete() failed - " + errE.getMessage());
1899: }
1900: try {
1901: this.dbmeta.supportsPositionedUpdate();
1902: } catch (final SQLException e) {
1903: support = false;
1904: DBMetaData.mLogger.warning("supportsPositionedUpdate() failed - " + e.getMessage());
1905: } catch (final AbstractMethodError errE) {
1906: support = false;
1907: DBMetaData.mLogger.warning("supportsPositionedUpdate() failed - " + errE.getMessage());
1908: }
1909: try {
1910: this.dbmeta.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
1911: } catch (final SQLException e) {
1912: support = false;
1913: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY ) failed - "
1914: + e.getMessage());
1915: } catch (final AbstractMethodError errE) {
1916: support = false;
1917: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY ) failed - "
1918: + errE.getMessage());
1919: }
1920: try {
1921: this.dbmeta.supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
1922: } catch (final SQLException e) {
1923: support = false;
1924: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE) failed - "
1925: + e.getMessage());
1926: } catch (final AbstractMethodError errE) {
1927: support = false;
1928: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE) failed - "
1929: + errE.getMessage());
1930: }
1931: try {
1932: this.dbmeta.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
1933: } catch (final SQLException e) {
1934: support = false;
1935: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ) failed - "
1936: + e.getMessage());
1937: } catch (final AbstractMethodError errE) {
1938: support = false;
1939: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ) failed - "
1940: + errE.getMessage());
1941: }
1942: try {
1943: this.dbmeta.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
1944: } catch (final SQLException e) {
1945: support = false;
1946: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) failed - "
1947: + e.getMessage());
1948: } catch (final AbstractMethodError errE) {
1949: support = false;
1950: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) failed - "
1951: + errE.getMessage());
1952: }
1953: try {
1954: this.dbmeta.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
1955: } catch (final SQLException e) {
1956: support = false;
1957: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ) failed - "
1958: + e.getMessage());
1959: } catch (final AbstractMethodError errE) {
1960: support = false;
1961: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY ) failed - "
1962: + errE.getMessage());
1963: }
1964: try {
1965: this.dbmeta.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
1966: } catch (final SQLException e) {
1967: support = false;
1968: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) failed - "
1969: + e.getMessage());
1970: } catch (final AbstractMethodError errE) {
1971: support = false;
1972: DBMetaData.mLogger.warning("supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) failed - "
1973: + errE.getMessage());
1974: }
1975: try {
1976: this.dbmeta.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY);
1977: } catch (final SQLException e) {
1978: support = false;
1979: DBMetaData.mLogger.warning("supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY) failed - " + e.getMessage());
1980: } catch (final AbstractMethodError errE) {
1981: support = false;
1982: DBMetaData.mLogger.warning("supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY) failed - " + errE.getMessage());
1983: }
1984: try {
1985: this.dbmeta.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);
1986: } catch (final SQLException e) {
1987: support = false;
1988: DBMetaData.mLogger.warning("supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) failed - " + e.getMessage());
1989: } catch (final AbstractMethodError errE) {
1990: support = false;
1991: DBMetaData.mLogger.warning("supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) failed - " + errE.getMessage());
1992: }
1993: try {
1994: this.dbmeta.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);
1995: } catch (final SQLException e) {
1996: support = false;
1997: DBMetaData.mLogger.warning("supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE) failed - " + e.getMessage());
1998: } catch (final AbstractMethodError errE) {
1999: support = false;
2000: DBMetaData.mLogger.warning("supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE) failed - " + errE.getMessage());
2001: }
2002: try {
2003: this.dbmeta.supportsSchemasInDataManipulation();
2004: } catch (final SQLException e) {
2005: support = false;
2006: DBMetaData.mLogger.warning("supportsSchemasInDataManipulation() failed - " + e.getMessage());
2007: } catch (final AbstractMethodError errE) {
2008: support = false;
2009: DBMetaData.mLogger.warning("supportsSchemasInDataManipulation() failed - " + errE.getMessage());
2010: }
2011: try {
2012: this.dbmeta.supportsSchemasInIndexDefinitions();
2013: } catch (final SQLException e) {
2014: support = false;
2015: DBMetaData.mLogger.warning("supportsSchemasInIndexDefinitions() failed - " + e.getMessage());
2016: } catch (final AbstractMethodError errE) {
2017: support = false;
2018: DBMetaData.mLogger.warning("supportsSchemasInIndexDefinitions() failed - " + errE.getMessage());
2019: }
2020: try {
2021: this.dbmeta.supportsSchemasInPrivilegeDefinitions();
2022: } catch (final SQLException e) {
2023: support = false;
2024: DBMetaData.mLogger.warning("supportsSchemasInPrivilegeDefinitions() failed - " + e.getMessage());
2025: } catch (final AbstractMethodError errE) {
2026: support = false;
2027: DBMetaData.mLogger.warning("supportsSchemasInPrivilegeDefinitions() failed - " + errE.getMessage());
2028: }
2029: try {
2030: this.dbmeta.supportsSchemasInProcedureCalls();
2031: } catch (final SQLException e) {
2032: support = false;
2033: DBMetaData.mLogger.warning("supportsSchemasInProcedureCalls() failed - " + e.getMessage());
2034: } catch (final AbstractMethodError errE) {
2035: support = false;
2036: DBMetaData.mLogger.warning("supportsSchemasInProcedureCalls() failed - " + errE.getMessage());
2037: }
2038: try {
2039: this.dbmeta.supportsSchemasInTableDefinitions();
2040: } catch (final SQLException e) {
2041: support = false;
2042: DBMetaData.mLogger.warning("supportsSchemasInTableDefinitions() failed - " + e.getMessage());
2043: } catch (final AbstractMethodError errE) {
2044: support = false;
2045: DBMetaData.mLogger.warning("supportsSchemasInTableDefinitions() failed - " + errE.getMessage());
2046: }
2047: try {
2048: this.dbmeta.supportsSelectForUpdate();
2049: } catch (final SQLException e) {
2050: support = false;
2051: DBMetaData.mLogger.warning("supportsSelectForUpdate() failed - " + e.getMessage());
2052: } catch (final AbstractMethodError errE) {
2053: support = false;
2054: DBMetaData.mLogger.warning("supportsSelectForUpdate() failed - " + errE.getMessage());
2055: }
2056: try {
2057: this.dbmeta.supportsStoredProcedures();
2058: } catch (final SQLException e) {
2059: support = false;
2060: DBMetaData.mLogger.warning("supportsStoredProcedures() failed - " + e.getMessage());
2061: } catch (final AbstractMethodError errE) {
2062: support = false;
2063: DBMetaData.mLogger.warning("supportsStoredProcedures() failed - " + errE.getMessage());
2064: }
2065: try {
2066: this.dbmeta.supportsSubqueriesInComparisons();
2067: } catch (final SQLException e) {
2068: support = false;
2069: DBMetaData.mLogger.warning("supportsSubqueriesInComparisons() failed - " + e.getMessage());
2070: } catch (final AbstractMethodError errE) {
2071: support = false;
2072: DBMetaData.mLogger.warning("supportsSubqueriesInComparisons() failed - " + errE.getMessage());
2073: }
2074: try {
2075: this.dbmeta.supportsSubqueriesInExists();
2076: } catch (final SQLException e) {
2077: support = false;
2078: DBMetaData.mLogger.warning("supportsSubqueriesInExists() failed - " + e.getMessage());
2079: } catch (final AbstractMethodError errE) {
2080: support = false;
2081: DBMetaData.mLogger.warning("supportsSubqueriesInExists() failed - " + errE.getMessage());
2082: }
2083: try {
2084: this.dbmeta.supportsSubqueriesInIns();
2085: } catch (final SQLException e) {
2086: support = false;
2087: DBMetaData.mLogger.warning("supportsSubqueriesInIns() failed - " + e.getMessage());
2088: } catch (final AbstractMethodError errE) {
2089: support = false;
2090: DBMetaData.mLogger.warning("supportsSubqueriesInIns() failed - " + errE.getMessage());
2091: }
2092: try {
2093: this.dbmeta.supportsSubqueriesInQuantifieds();
2094: } catch (final SQLException e) {
2095: support = false;
2096: DBMetaData.mLogger.warning("supportsSubqueriesInQuantifieds() failed - " + e.getMessage());
2097: } catch (final AbstractMethodError errE) {
2098: support = false;
2099: DBMetaData.mLogger.warning("supportsSubqueriesInQuantifieds() failed - " + errE.getMessage());
2100: }
2101: try {
2102: this.dbmeta.supportsTableCorrelationNames();
2103: } catch (final SQLException e) {
2104: support = false;
2105: DBMetaData.mLogger.warning("supportsTableCorrelationNames() failed - " + e.getMessage());
2106: } catch (final AbstractMethodError errE) {
2107: support = false;
2108: DBMetaData.mLogger.warning("supportsTableCorrelationNames() failed - " + errE.getMessage());
2109: }
2110: try {
2111: this.dbmeta.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE);
2112: } catch (final SQLException e) {
2113: support = false;
2114: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE) failed - " + e.getMessage());
2115: } catch (final AbstractMethodError errE) {
2116: support = false;
2117: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE) failed - "
2118: + errE.getMessage());
2119: }
2120: try {
2121: this.dbmeta.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED);
2122: } catch (final SQLException e) {
2123: support = false;
2124: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED) failed - "
2125: + e.getMessage());
2126: } catch (final AbstractMethodError errE) {
2127: support = false;
2128: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED) failed - "
2129: + errE.getMessage());
2130: }
2131: try {
2132: this.dbmeta.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED);
2133: } catch (final SQLException e) {
2134: support = false;
2135: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED) failed - "
2136: + e.getMessage());
2137: } catch (final AbstractMethodError errE) {
2138: support = false;
2139: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED) failed - "
2140: + errE.getMessage());
2141: }
2142: try {
2143: this.dbmeta.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ);
2144: } catch (final SQLException e) {
2145: support = false;
2146: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ) failed - "
2147: + e.getMessage());
2148: } catch (final AbstractMethodError errE) {
2149: support = false;
2150: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ) failed - "
2151: + errE.getMessage());
2152: }
2153: try {
2154: this.dbmeta.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE);
2155: } catch (final SQLException e) {
2156: support = false;
2157: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE) failed - "
2158: + e.getMessage());
2159: } catch (final AbstractMethodError errE) {
2160: support = false;
2161: DBMetaData.mLogger.warning("supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE) failed - "
2162: + errE.getMessage());
2163: }
2164: try {
2165: this.dbmeta.supportsTransactions();
2166: } catch (final SQLException e) {
2167: support = false;
2168: DBMetaData.mLogger.warning("supportsTransactions() failed - " + e.getMessage());
2169: } catch (final AbstractMethodError errE) {
2170: support = false;
2171: DBMetaData.mLogger.warning("supportsTransactions() failed - " + errE.getMessage());
2172: }
2173:
2174: return support;
2175: }*/
2176:
2177: private static final Parameter[] handleUnsupportParameterMetaData(
2178: final String sqlText) {
2179: int numParams = 0;
2180: for (int i = 0; i < sqlText.length(); i++) {
2181: if (sqlText.charAt(i) == '?') {
2182: numParams++;
2183: }
2184: }
2185: final Parameter[] parameters = new Parameter[numParams];
2186: for (int i = 1; i <= numParams; i++) {
2187: final Parameter currParam = new Parameter();
2188: final String paramname = "param" + String.valueOf(i);
2189: currParam.setName(paramname);
2190: final String javatype = "java.lang.String";
2191: final String sqltype = "VARCHAR";
2192: final int precision = 0;
2193: final int scale = 0;
2194: final String paramType = "IN";
2195: final boolean isNullable = true;
2196:
2197: currParam.setJavaType(javatype);
2198: currParam.setSqlType(sqltype);
2199: currParam.setNumericPrecision(precision);
2200: currParam.setNumericScale(scale);
2201: currParam.setOrdinalPosition(i);
2202: currParam.setParamType(paramType);
2203: currParam.setIsNullable(isNullable);
2204:
2205: parameters[i - 1] = currParam;
2206: }
2207: return parameters;
2208: }
2209:
2210: /**
2211: * added by Bobby to retrieve the resultset metadata of a procedure
2212: *
2213: * @param pcatalog Catalog (package) name of the procedure
2214: * @param pschema Schema name of the procdure
2215: * @param pname Name of the procedure
2216: * @param columnName Name of the column
2217: * @return Procedure resultset encapsulated in a Procedure object
2218: * @throws SQLException, NullPointerException
2219: */
2220: public static final Procedure getProcResultSetColumns(
2221: final String pcatalog, final String pschema,
2222: final String pname, final String columnName,
2223: final Connection connection) throws SQLException,
2224: NullPointerException {
2225:
2226: String errMsg = "";
2227: String cstmtString = "";
2228: int colCount = 0;
2229: boolean isFunction = false;
2230: boolean hasParameters = true;
2231: // indicates if the procedure is within a package or standalone
2232: boolean isPackaged = true;
2233:
2234: final Procedure procResult = new Procedure(pname, pcatalog,
2235: pschema, new String("PROCEDURE"));
2236: final ResultSetColumn resultCol = new ResultSetColumn();
2237: final ArrayList paramIndices = new ArrayList(); // arraylist to hold the indices of the
2238: // paramters that return resultsets
2239: final ArrayList result = new ArrayList(); // arraylist to hold ResultSetColumns objects
2240:
2241: // check if the procedure is within a package or not
2242: if (pcatalog.trim().equalsIgnoreCase("") || pcatalog == null) {
2243: isPackaged = false;
2244: }
2245: try {
2246: final DatabaseMetaData dbmeta = connection.getMetaData();
2247: ResultSet rs = dbmeta.getProcedureColumns(pcatalog,
2248: pschema, pname, columnName);
2249:
2250: // loop to identify if the procedure is actually a function
2251: while (rs.next()) {
2252: if (rs.getShort("COLUMN_TYPE") == DatabaseMetaData.procedureColumnReturn) {
2253: // this is a function, so set the flag to true
2254: isFunction = true;
2255: }
2256: }
2257:
2258: rs = dbmeta.getProcedureColumns(pcatalog, pschema, pname,
2259: columnName);
2260:
2261: // get the count of the parameters
2262: while (rs.next()) {
2263: colCount++;
2264: }
2265:
2266: // check if the procedure has parameters or not
2267: if (colCount == 0) {
2268: hasParameters = false;
2269: }
2270:
2271: // construct the procedure execution command string
2272: if (isFunction == true) {
2273: cstmtString = "{ ? = call ";
2274: // use the package name to qualify the procedure name if the procedure is within a
2275: // package
2276: if (isPackaged) {
2277: cstmtString += pcatalog + "." + pname + "(";
2278: } else {
2279: cstmtString += pname + "(";
2280: }
2281:
2282: for (int j = 1; j < colCount; j++) {
2283: cstmtString += "?,";
2284: }
2285:
2286: // trim the last comma only if the procedure has any parameters
2287: if (hasParameters) {
2288: cstmtString = cstmtString.substring(0, cstmtString
2289: .length() - 1);
2290: }
2291: cstmtString += ") }";
2292: } else {
2293: cstmtString = "call ";
2294: // use the package name to qualify the procedure name if the procedure is within a
2295: // package
2296: if (isPackaged) {
2297: cstmtString += pcatalog + "." + pname + "(";
2298: } else {
2299: cstmtString += pname + "(";
2300: }
2301:
2302: for (int j = 0; j < colCount; j++) {
2303: cstmtString += "?,";
2304: }
2305:
2306: // trim the last comma only if the procedure has any parameters
2307: if (hasParameters) {
2308: cstmtString = cstmtString.substring(0, cstmtString
2309: .length() - 1);
2310: }
2311: cstmtString += ")";
2312: }
2313:
2314: final CallableStatement cstmt = connection
2315: .prepareCall(cstmtString);
2316:
2317: rs = dbmeta.getProcedureColumns(pcatalog, pschema, pname,
2318: columnName);
2319: int paramIndex = 0;
2320:
2321: // loop through the list of parameters and register them
2322: for (int j = 0; j < colCount; j++) {
2323: rs.next();
2324: paramIndex++;
2325: final String parameterName = rs
2326: .getString("COLUMN_NAME");
2327: int targetSqlType = rs.getInt("DATA_TYPE");
2328: final int colType = rs.getShort("COLUMN_TYPE");
2329: final String type_Name = rs.getString("TYPE_NAME");
2330: cstmt.setNull(paramIndex, targetSqlType);
2331:
2332: if (colType == DatabaseMetaData.procedureColumnInOut
2333: || colType == DatabaseMetaData.procedureColumnOut) {
2334: try {
2335: // if the parameter is a cursor type, add its index to the arraylist
2336: if (targetSqlType == 1111
2337: && type_Name.equals("OTHER")) {
2338: targetSqlType = java.sql.Types.OTHER;
2339: paramIndices.add(Integer.valueOf(String
2340: .valueOf(paramIndex)));
2341: }
2342: cstmt.registerOutParameter(paramIndex,
2343: targetSqlType);
2344: } catch (final SQLException e) {
2345: e.printStackTrace();
2346: throw e;
2347: }
2348: }
2349:
2350: // check if the parameter is RETURN type (i.e. it is a function)
2351: if (colType == DatabaseMetaData.procedureColumnReturn) {
2352: try {
2353: // if the parameter is a cursor type, add its index to the arraylist
2354: if (targetSqlType == 1111
2355: && type_Name.equals("OTHER")) {
2356: targetSqlType = java.sql.Types.OTHER;
2357: paramIndices.add(Integer.valueOf(String
2358: .valueOf(paramIndex)));
2359: }
2360: cstmt.registerOutParameter(paramIndex,
2361: targetSqlType);
2362: } catch (final SQLException e) {
2363: e.printStackTrace();
2364: throw e;
2365: }
2366: }
2367: }
2368:
2369: // execute the stored procedure
2370: final boolean resultsAvailable = cstmt.execute();
2371: int count = -1;
2372: final int numResults = paramIndices.size();
2373:
2374: final Iterator paramIdxIter = paramIndices.iterator();
2375:
2376: // iterate through the resultsets returned, whose indices are stored in the arraylist
2377: while (paramIdxIter.hasNext()) {
2378: final ArrayList resultArray = new ArrayList(); // arraylist to hold the objects of
2379: // ResultSetColumn
2380: count += 1;
2381: // get the index (from the arraylist) of the parameter which is a resultset
2382: final int index = ((Integer) paramIdxIter.next())
2383: .intValue();
2384: ResultSet paramRS;
2385: ResultSetMetaData rsmd;
2386: // if the resultset returns nothing, set the metadata object to null
2387: try {
2388: paramRS = (ResultSet) cstmt.getObject(index);
2389: rsmd = paramRS.getMetaData();
2390: } catch (final SQLException e) {
2391: rsmd = null;
2392: }
2393:
2394: int rsmdColCount = 0;
2395: if (rsmd != null) {
2396: rsmdColCount = rsmd.getColumnCount();
2397: }
2398: // scroll through the resultset column information
2399: for (int i = 1; i <= rsmdColCount; i++) {
2400: final ResultSetColumn currCol = new ResultSetColumn();
2401: currCol.setOrdinalPosition(i);
2402: currCol.setName(rsmd.getColumnName(i));
2403: currCol.setLabel(rsmd.getColumnLabel(i));
2404: currCol.setSqlType(DBMetaData
2405: .getSQLTypeDescription(rsmd
2406: .getColumnType(i)));
2407: currCol
2408: .setJavaType((String) DBMetaData.SQLTOJAVATYPES
2409: .get(DBMetaData
2410: .getSQLTypeDescription(rsmd
2411: .getColumnType(i))));
2412:
2413: if (rsmd.isNullable(i) == DatabaseMetaData.columnNullable) {
2414: currCol.setIsNullable(true);
2415: } else {
2416: currCol.setIsNullable(false);
2417: }
2418: // add ResultSetColumn object to the arraylist
2419: final boolean addToArray = resultArray.add(currCol);
2420: }
2421:
2422: // add the arraylist having ResultSetColumn objects to the ResultSetColumns object
2423: // now add this ResultSetColumns object to the arraylist object (result)
2424: if (resultArray.size() > 0) {
2425: final ResultSetColumns rsColbj = new ResultSetColumns();
2426: rsColbj.setColumns(resultArray);
2427: rsColbj.setName(pname + "_" + count);
2428: result.add(rsColbj);
2429: }
2430: }
2431: } catch (final SQLException e) {
2432: // resultset column metadata not supported
2433: e.printStackTrace();
2434: errMsg = e.getLocalizedMessage();
2435: throw e;
2436: } catch (final NullPointerException npe) {
2437: npe.printStackTrace();
2438: errMsg = npe.getLocalizedMessage();
2439: throw npe;
2440: } catch (final Exception e) {
2441: // resultset column metadata not supported
2442: e.printStackTrace();
2443: errMsg = e.getLocalizedMessage();
2444: }
2445:
2446: // add the arraylist object to the Procedure object
2447: procResult.setResultSetColumns(result);
2448: return procResult;
2449: }
2450:
2451: /**
2452: * added by Bobby to retrieve the resultset metadata of an SQL query
2453: *
2454: * @param pcatalog Catalog (package) name of the procedure
2455: * @param pschema Schema name of the procdure
2456: * @param pname Name of the procedure
2457: * @param sqlText Text of the procedure/function
2458: * @return Procedure resultset encapsulated in a Procedure object
2459: * @throws SQLException, NullPointerException
2460: */
2461: public static final Procedure getQueryResultSet(
2462: final String pcatalog, final String pschema,
2463: final String pname, final String sqlText,
2464: final Connection connection) throws SQLException,
2465: NullPointerException {
2466: String errMsg = "";
2467: final Procedure procResult = new Procedure(pname, pcatalog,
2468: pschema, new String("PROCEDURE"));
2469: ResultSetColumns[] result = null;
2470: final ArrayList resultList = new ArrayList();
2471:
2472: try {
2473: final DatabaseMetaData dbmeta = connection.getMetaData();
2474: final Statement stmt = connection.createStatement();
2475:
2476: // retrieve the names of the fields in the select query
2477: // required if the query contains calculated fields
2478: final String[] queryFields = getQueryFields(sqlText);
2479:
2480: // execute the SQL query and retrieve the resultset
2481: final ResultSet rs = stmt.executeQuery(sqlText);
2482: final ResultSetMetaData rsmd = rs.getMetaData();
2483: final int numColumns = rsmd.getColumnCount();
2484:
2485: for (int i = 1; i <= numColumns; i++) {
2486: final ResultSetColumn resultCol = new ResultSetColumn();
2487: resultCol.setOrdinalPosition(i);
2488: final String colName = rsmd.getColumnName(i).trim();
2489: final String colLabel = rsmd.getColumnLabel(i).trim();
2490:
2491: // check if the column names/labels are returned as null
2492: // (this happens in the case of derived/calculated fields and no aliases are
2493: // provided)
2494: if (colName.equalsIgnoreCase("") || colName == null) {
2495: // parse the query string to extract derived field names
2496: final String strFieldName = queryFields[i - 1];
2497: resultCol.setName(strFieldName);
2498: } else {
2499: resultCol.setName(colName);
2500: }
2501:
2502: if (colLabel.equalsIgnoreCase("") || colLabel == null) {
2503: // parse the query string to extract derived field names
2504: final String strFieldName = queryFields[i - 1];
2505: resultCol.setLabel(strFieldName);
2506: } else {
2507: resultCol.setLabel(colLabel);
2508: }
2509:
2510: resultCol.setSqlType(DBMetaData
2511: .getSQLTypeDescription(rsmd.getColumnType(i)));
2512: resultCol
2513: .setJavaType((String) DBMetaData.SQLTOJAVATYPES
2514: .get(DBMetaData
2515: .getSQLTypeDescription(rsmd
2516: .getColumnType(i))));
2517:
2518: if (rsmd.isNullable(i) == DatabaseMetaData.columnNullable) {
2519: resultCol.setIsNullable(true);
2520: } else {
2521: resultCol.setIsNullable(false);
2522: }
2523:
2524: // add ResultSetColumn object to the arraylist
2525: final boolean addToArray = resultList.add(resultCol);
2526: }
2527:
2528: result = new ResultSetColumns[1];
2529: result[0] = new ResultSetColumns();
2530: // add the arraylist to the ResultSetColumns object
2531: result[0].setColumns(resultList);
2532: result[0].setName(pname + "_0");
2533: } catch (final SQLException e) {
2534: e.printStackTrace();
2535: errMsg = e.getLocalizedMessage();
2536: throw e;
2537: } catch (final NullPointerException npe) {
2538: npe.printStackTrace();
2539: errMsg = npe.getLocalizedMessage();
2540: throw npe;
2541: } catch (final Exception e) {
2542: // resultset column metadata not supported
2543: e.printStackTrace();
2544: errMsg = e.getLocalizedMessage();
2545: }
2546:
2547: // add the ResultSetColumns array to the Procedure object
2548: procResult.setResultSetColumns(result);
2549: return procResult;
2550: }
2551:
2552: /**
2553: * added by Bobby to retrieve the text of a procedure/function
2554: *
2555: * @param Procedure Procedure object representing a procedure or function
2556: * @return String Text of the procedure or function
2557: */
2558: public static final String getProcedureText(final Procedure proc,
2559: final Connection connection) {
2560: String procText = "";
2561: String stmtString = "";
2562: final String procName = proc.getName();
2563: final String packageName = proc.getCatalog();
2564:
2565: // construct the SQL select query depending on whether
2566: // the procedure or function is part of a package or not
2567: if (packageName.equals("") || packageName == null) {
2568: stmtString = "select text from user_source where name = '"
2569: + procName + "'";
2570: } else {
2571: stmtString = "select text from user_source where name = '"
2572: + packageName + "'";
2573: }
2574:
2575: try {
2576: final Statement stmt = connection.createStatement();
2577: final ResultSet rsProcText = stmt.executeQuery(stmtString);
2578:
2579: while (rsProcText.next()) {
2580: procText += rsProcText.getString(1);
2581: }
2582: } catch (final SQLException e) {
2583: e.printStackTrace();
2584: //this.errMsg = e.getLocalizedMessage();
2585: }
2586:
2587: return procText;
2588: }
2589:
2590: /**
2591: * added by Bobby to parse an SQL query string and return a String array containing the names of
2592: * the select fields
2593: *
2594: * @param sqlQuery the SQL query string to be parsed
2595: * @return String array containing the list of derived field names
2596: */
2597: private static final String[] getQueryFields(final String sqlQuery) {
2598: String[] strFieldNames = null;
2599:
2600: final String queryString = sqlQuery.toUpperCase().trim();
2601: final int fromIndex = queryString.indexOf("FROM");
2602:
2603: // extract the part of the query between the SELECT and the FROM keywords
2604: final String searchString = sqlQuery.substring(7, fromIndex);
2605:
2606: final StringTokenizer stFields = new StringTokenizer(
2607: searchString, ",");
2608: final int noTokens = stFields.countTokens();
2609: strFieldNames = new String[noTokens];
2610:
2611: int tokenNo = 0;
2612: // extract the string tokens fom the query (the derived columns)
2613: while (stFields.hasMoreTokens()) {
2614: strFieldNames[tokenNo] = stFields.nextToken().trim();
2615: tokenNo++;
2616: }
2617:
2618: return strFieldNames;
2619: }
2620: }
|