Example usage for java.sql DatabaseMetaData getSchemas

List of usage examples for java.sql DatabaseMetaData getSchemas

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getSchemas.

Prototype

ResultSet getSchemas() throws SQLException;

Source Link

Document

Retrieves the schema names available in this database.

Usage

From source file:DatabaseBrowser.java

protected void populateSchemaBox() {
    try {//from w w w  .ja  va 2s . c  o m
        DatabaseMetaData dmd = connection.getMetaData();
        ResultSet rset = dmd.getSchemas();
        Vector values = new Vector();
        while (rset.next()) {
            values.addElement(rset.getString(1));
        }
        rset.close();
        schemaBox.setModel(new DefaultComboBoxModel(values));
        schemaBox.setEnabled(values.size() > 0);
    } catch (Exception e) {
        schemaBox.setEnabled(false);
    }
}

From source file:com.nridge.core.ds.rdbms.SQLConnection.java

/**
 * Returns an array of RDBMS schema names associated with
 * an opened connection.//ww  w. j a  v a2  s  . c o m
 *
 * @return An array of schema names.
 *
 * @throws NSException Catch-all exception for any SQL related issue.
 */
public ArrayList<String> getSchemaNames() throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "getSchemaNames");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    mSQLStatement = StringUtils.EMPTY;
    ArrayList<String> schemaNames = new ArrayList<String>();

    try {
        String schemaName;
        DatabaseMetaData dbMetaData = mConnection.getMetaData();
        ResultSet rsSchemas = dbMetaData.getSchemas();
        while (rsSchemas.next()) {
            schemaName = rsSchemas.getString("TABLE_SCHEM");
            if (!StringUtils.isEmpty(schemaName))
                schemaNames.add(schemaName);
        }
        rsSchemas.close();
    } catch (SQLException e) {
        throw new NSException("Unable to retrieve RDBMS schemas: " + e.getMessage(), e);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return schemaNames;
}

From source file:com.mirth.connect.connectors.jdbc.JdbcConnectorService.java

public Object invoke(String method, Object object, String sessionsId) throws Exception {
    if (method.equals("getInformationSchema")) {
        // method 'getInformationSchema' will return Set<Table>

        Connection connection = null;
        try {//w  w w.  jav a 2s. co m
            Properties properties = (Properties) object;
            String driver = properties.getProperty(DatabaseReaderProperties.DATABASE_DRIVER);
            String address = properties.getProperty(DatabaseReaderProperties.DATABASE_URL);
            String user = properties.getProperty(DatabaseReaderProperties.DATABASE_USERNAME);
            String password = properties.getProperty(DatabaseReaderProperties.DATABASE_PASSWORD);

            // Although these properties are not persisted, they used by the JdbcConnectorService
            String tableNamePatternExp = properties
                    .getProperty(DatabaseReaderProperties.DATABASE_TABLE_NAME_PATTERN_EXPRESSION);
            String selectLimit = properties.getProperty(DatabaseReaderProperties.DATABASE_SELECT_LIMIT);

            String schema = null;

            Class.forName(driver);
            int oldLoginTimeout = DriverManager.getLoginTimeout();
            DriverManager.setLoginTimeout(30);
            connection = DriverManager.getConnection(address, user, password);
            DriverManager.setLoginTimeout(oldLoginTimeout);
            DatabaseMetaData dbMetaData = connection.getMetaData();

            // the sorted set to hold the table information
            SortedSet<Table> tableInfoList = new TreeSet<Table>();

            // Use a schema if the user name matches one of the schemas.
            // Fix for Oracle: MIRTH-1045
            ResultSet schemasResult = null;
            try {
                schemasResult = dbMetaData.getSchemas();
                while (schemasResult.next()) {
                    String schemaResult = schemasResult.getString(1);
                    if (user.equalsIgnoreCase(schemaResult)) {
                        schema = schemaResult;
                    }
                }
            } finally {
                if (schemasResult != null) {
                    schemasResult.close();
                }
            }

            // based on the table name pattern, attempt to retrieve the table information
            List<String> tablePatternList = translateTableNamePatternExpression(tableNamePatternExp);
            List<String> tableNameList = new ArrayList<String>();

            // go through each possible table name patterns and query for the tables
            for (String tableNamePattern : tablePatternList) {
                ResultSet rs = null;
                try {
                    rs = dbMetaData.getTables(null, schema, tableNamePattern, TABLE_TYPES);

                    // based on the result set, loop through to store the table name so it can be used to
                    // retrieve the table's column information
                    while (rs.next()) {
                        tableNameList.add(rs.getString("TABLE_NAME"));
                    }
                } finally {
                    if (rs != null) {
                        rs.close();
                    }
                }
            }

            // for each table, grab their column information
            for (String tableName : tableNameList) {
                ResultSet rs = null;
                ResultSet backupRs = null;
                boolean fallback = false;
                try {
                    // apparently it's much more efficient to use ResultSetMetaData to retrieve
                    // column information.  So each driver is defined with their own unique SELECT
                    // statement to query the table columns and use ResultSetMetaData to retrieve
                    // the column information.  If driver is not defined with the select statement
                    // then we'll define to the generic method of getting column information, but
                    // this could be extremely slow
                    List<Column> columnList = new ArrayList<Column>();
                    if (StringUtils.isEmpty(selectLimit)) {
                        logger.debug("No select limit is defined, using generic method");
                        rs = dbMetaData.getColumns(null, null, tableName, null);

                        // retrieve all relevant column information                         
                        for (int i = 0; rs.next(); i++) {
                            Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
                                    rs.getInt("COLUMN_SIZE"));
                            columnList.add(column);
                        }
                    } else {
                        logger.debug(
                                "Select limit is defined, using specific select query : '" + selectLimit + "'");

                        // replace the '?' with the appropriate schema.table name, and use ResultSetMetaData to 
                        // retrieve column information 
                        final String schemaTableName = StringUtils.isNotEmpty(schema) ? schema + "." + tableName
                                : tableName;
                        final String queryString = selectLimit.trim().replaceAll("\\?", schemaTableName);
                        Statement statement = connection.createStatement();
                        try {
                            rs = statement.executeQuery(queryString);
                            ResultSetMetaData rsmd = rs.getMetaData();

                            // retrieve all relevant column information
                            for (int i = 1; i < rsmd.getColumnCount() + 1; i++) {
                                Column column = new Column(rsmd.getColumnName(i), rsmd.getColumnTypeName(i),
                                        rsmd.getPrecision(i));
                                columnList.add(column);
                            }
                        } catch (SQLException sqle) {
                            logger.info("Failed to execute '" + queryString
                                    + "', fall back to generic approach to retrieve column information");
                            fallback = true;
                        } finally {
                            if (statement != null) {
                                statement.close();
                            }
                        }

                        // failed to use selectLimit method, so we need to fall back to generic
                        // if this generic approach fails, then there's nothing we can do
                        if (fallback) {
                            // Re-initialize in case some columns were added before failing
                            columnList = new ArrayList<Column>();

                            logger.debug("Using fallback method for retrieving columns");
                            backupRs = dbMetaData.getColumns(null, null, tableName, null);

                            // retrieve all relevant column information                         
                            for (int i = 0; backupRs.next(); i++) {
                                Column column = new Column(backupRs.getString("COLUMN_NAME"),
                                        backupRs.getString("TYPE_NAME"), backupRs.getInt("COLUMN_SIZE"));
                                columnList.add(column);
                            }
                        }
                    }

                    // create table object and add to the list of table definitions
                    Table table = new Table(tableName, columnList);
                    tableInfoList.add(table);
                } finally {
                    if (rs != null) {
                        rs.close();
                    }

                    if (backupRs != null) {
                        backupRs.close();
                    }
                }
            }

            return tableInfoList;
        } catch (Exception e) {
            throw new Exception("Could not retrieve database tables and columns.", e);
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    return null;
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseConnectorService.java

public Object invoke(String channelId, String method, Object object, String sessionsId) throws Exception {
    if (method.equals("getInformationSchema")) {
        // method 'getInformationSchema' will return Set<Table>

        Connection connection = null;
        try {//from w w w . j a v  a2s  .com
            DatabaseConnectionInfo databaseConnectionInfo = (DatabaseConnectionInfo) object;
            String driver = databaseConnectionInfo.getDriver();
            String address = replacer.replaceValues(databaseConnectionInfo.getUrl(), channelId);
            String user = replacer.replaceValues(databaseConnectionInfo.getUsername(), channelId);
            String password = replacer.replaceValues(databaseConnectionInfo.getPassword(), channelId);

            // Although these properties are not persisted, they used by the JdbcConnectorService
            String tableNamePatternExp = databaseConnectionInfo.getTableNamePatternExpression();
            String selectLimit = databaseConnectionInfo.getSelectLimit();

            String schema = null;

            Class.forName(driver);
            int oldLoginTimeout = DriverManager.getLoginTimeout();
            DriverManager.setLoginTimeout(30);
            connection = DriverManager.getConnection(address, user, password);
            DriverManager.setLoginTimeout(oldLoginTimeout);
            DatabaseMetaData dbMetaData = connection.getMetaData();

            // the sorted set to hold the table information
            SortedSet<Table> tableInfoList = new TreeSet<Table>();

            // Use a schema if the user name matches one of the schemas.
            // Fix for Oracle: MIRTH-1045
            ResultSet schemasResult = null;
            try {
                schemasResult = dbMetaData.getSchemas();
                while (schemasResult.next()) {
                    String schemaResult = schemasResult.getString(1);
                    if (user.equalsIgnoreCase(schemaResult)) {
                        schema = schemaResult;
                    }
                }
            } finally {
                if (schemasResult != null) {
                    schemasResult.close();
                }
            }

            // based on the table name pattern, attempt to retrieve the table information
            List<String> tablePatternList = translateTableNamePatternExpression(tableNamePatternExp);
            List<String> tableNameList = new ArrayList<String>();

            // go through each possible table name patterns and query for the tables
            for (String tableNamePattern : tablePatternList) {
                ResultSet rs = null;
                try {
                    rs = dbMetaData.getTables(null, schema, tableNamePattern, TABLE_TYPES);

                    // based on the result set, loop through to store the table name so it can be used to
                    // retrieve the table's column information
                    while (rs.next()) {
                        tableNameList.add(rs.getString("TABLE_NAME"));
                    }
                } finally {
                    if (rs != null) {
                        rs.close();
                    }
                }
            }

            // for each table, grab their column information
            for (String tableName : tableNameList) {
                ResultSet rs = null;
                ResultSet backupRs = null;
                boolean fallback = false;
                try {
                    // apparently it's much more efficient to use ResultSetMetaData to retrieve
                    // column information.  So each driver is defined with their own unique SELECT
                    // statement to query the table columns and use ResultSetMetaData to retrieve
                    // the column information.  If driver is not defined with the select statement
                    // then we'll define to the generic method of getting column information, but
                    // this could be extremely slow
                    List<Column> columnList = new ArrayList<Column>();
                    if (StringUtils.isEmpty(selectLimit)) {
                        logger.debug("No select limit is defined, using generic method");
                        rs = dbMetaData.getColumns(null, null, tableName, null);

                        // retrieve all relevant column information                         
                        for (int i = 0; rs.next(); i++) {
                            Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
                                    rs.getInt("COLUMN_SIZE"));
                            columnList.add(column);
                        }
                    } else {
                        logger.debug(
                                "Select limit is defined, using specific select query : '" + selectLimit + "'");

                        // replace the '?' with the appropriate schema.table name, and use ResultSetMetaData to 
                        // retrieve column information 
                        final String schemaTableName = StringUtils.isNotEmpty(schema) ? schema + "." + tableName
                                : tableName;
                        final String queryString = selectLimit.trim().replaceAll("\\?", schemaTableName);
                        Statement statement = connection.createStatement();
                        try {
                            rs = statement.executeQuery(queryString);
                            ResultSetMetaData rsmd = rs.getMetaData();

                            // retrieve all relevant column information
                            for (int i = 1; i < rsmd.getColumnCount() + 1; i++) {
                                Column column = new Column(rsmd.getColumnName(i), rsmd.getColumnTypeName(i),
                                        rsmd.getPrecision(i));
                                columnList.add(column);
                            }
                        } catch (SQLException sqle) {
                            logger.info("Failed to execute '" + queryString
                                    + "', fall back to generic approach to retrieve column information");
                            fallback = true;
                        } finally {
                            if (statement != null) {
                                statement.close();
                            }
                        }

                        // failed to use selectLimit method, so we need to fall back to generic
                        // if this generic approach fails, then there's nothing we can do
                        if (fallback) {
                            // Re-initialize in case some columns were added before failing
                            columnList = new ArrayList<Column>();

                            logger.debug("Using fallback method for retrieving columns");
                            backupRs = dbMetaData.getColumns(null, null, tableName, null);

                            // retrieve all relevant column information                         
                            for (int i = 0; backupRs.next(); i++) {
                                Column column = new Column(backupRs.getString("COLUMN_NAME"),
                                        backupRs.getString("TYPE_NAME"), backupRs.getInt("COLUMN_SIZE"));
                                columnList.add(column);
                            }
                        }
                    }

                    // create table object and add to the list of table definitions
                    Table table = new Table(tableName, columnList);
                    tableInfoList.add(table);
                } finally {
                    if (rs != null) {
                        rs.close();
                    }

                    if (backupRs != null) {
                        backupRs.close();
                    }
                }
            }

            return tableInfoList;
        } catch (Exception e) {
            throw new Exception("Could not retrieve database tables and columns.", e);
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    return null;
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseConnectorServlet.java

@Override
public SortedSet<Table> getTables(String channelId, String channelName, String driver, String url,
        String username, String password, Set<String> tableNamePatterns, String selectLimit,
        Set<String> resourceIds) {
    CustomDriver customDriver = null;//from  w  w w  . ja v a  2  s . c o  m
    Connection connection = null;
    try {
        url = replacer.replaceValues(url, channelId, channelName);
        username = replacer.replaceValues(username, channelId, channelName);
        password = replacer.replaceValues(password, channelId, channelName);

        String schema = null;

        try {
            MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds);

            try {
                ClassLoader isolatedClassLoader = contextFactory.getIsolatedClassLoader();
                if (isolatedClassLoader != null) {
                    customDriver = new CustomDriver(isolatedClassLoader, driver);
                    logger.debug("Custom driver created: " + customDriver.toString() + ", Version "
                            + customDriver.getMajorVersion() + "." + customDriver.getMinorVersion());
                } else {
                    logger.debug("Custom classloader is not being used, defaulting to DriverManager.");
                }
            } catch (Exception e) {
                logger.debug("Error creating custom driver, defaulting to DriverManager.", e);
            }
        } catch (Exception e) {
            logger.debug("Error retrieving context factory, defaulting to DriverManager.", e);
        }

        if (customDriver == null) {
            Class.forName(driver);
        }

        int oldLoginTimeout = DriverManager.getLoginTimeout();
        DriverManager.setLoginTimeout(30);

        if (customDriver != null) {
            connection = customDriver.connect(url, username, password);
        } else {
            connection = DriverManager.getConnection(url, username, password);
        }

        DriverManager.setLoginTimeout(oldLoginTimeout);
        DatabaseMetaData dbMetaData = connection.getMetaData();

        // the sorted set to hold the table information
        SortedSet<Table> tableInfoList = new TreeSet<Table>();

        // Use a schema if the user name matches one of the schemas.
        // Fix for Oracle: MIRTH-1045
        ResultSet schemasResult = null;
        try {
            schemasResult = dbMetaData.getSchemas();
            while (schemasResult.next()) {
                String schemaResult = schemasResult.getString(1);
                if (username.equalsIgnoreCase(schemaResult)) {
                    schema = schemaResult;
                }
            }
        } finally {
            if (schemasResult != null) {
                schemasResult.close();
            }
        }

        // based on the table name pattern, attempt to retrieve the table information
        tableNamePatterns = translateTableNamePatterns(tableNamePatterns);
        List<String> tableNameList = new ArrayList<String>();

        // go through each possible table name patterns and query for the tables
        for (String tableNamePattern : tableNamePatterns) {
            ResultSet rs = null;
            try {
                rs = dbMetaData.getTables(null, schema, tableNamePattern, TABLE_TYPES);

                // based on the result set, loop through to store the table name so it can be used to
                // retrieve the table's column information
                while (rs.next()) {
                    tableNameList.add(rs.getString("TABLE_NAME"));
                }
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        }

        // for each table, grab their column information
        for (String tableName : tableNameList) {
            ResultSet rs = null;
            ResultSet backupRs = null;
            boolean fallback = false;
            try {
                // apparently it's much more efficient to use ResultSetMetaData to retrieve
                // column information.  So each driver is defined with their own unique SELECT
                // statement to query the table columns and use ResultSetMetaData to retrieve
                // the column information.  If driver is not defined with the select statement
                // then we'll define to the generic method of getting column information, but
                // this could be extremely slow
                List<Column> columnList = new ArrayList<Column>();
                if (StringUtils.isEmpty(selectLimit)) {
                    logger.debug("No select limit is defined, using generic method");
                    rs = dbMetaData.getColumns(null, null, tableName, null);

                    // retrieve all relevant column information                         
                    for (int i = 0; rs.next(); i++) {
                        Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
                                rs.getInt("COLUMN_SIZE"));
                        columnList.add(column);
                    }
                } else {
                    logger.debug(
                            "Select limit is defined, using specific select query : '" + selectLimit + "'");

                    // replace the '?' with the appropriate schema.table name, and use ResultSetMetaData to 
                    // retrieve column information 
                    final String schemaTableName = StringUtils.isNotEmpty(schema)
                            ? "\"" + schema + "\".\"" + tableName + "\""
                            : "\"" + tableName + "\"";
                    final String queryString = selectLimit.trim().replaceAll("\\?",
                            Matcher.quoteReplacement(schemaTableName));
                    Statement statement = connection.createStatement();
                    try {
                        rs = statement.executeQuery(queryString);
                        ResultSetMetaData rsmd = rs.getMetaData();

                        // retrieve all relevant column information
                        for (int i = 1; i < rsmd.getColumnCount() + 1; i++) {
                            Column column = new Column(rsmd.getColumnName(i), rsmd.getColumnTypeName(i),
                                    rsmd.getPrecision(i));
                            columnList.add(column);
                        }
                    } catch (SQLException sqle) {
                        logger.info("Failed to execute '" + queryString
                                + "', fall back to generic approach to retrieve column information");
                        fallback = true;
                    } finally {
                        if (statement != null) {
                            statement.close();
                        }
                    }

                    // failed to use selectLimit method, so we need to fall back to generic
                    // if this generic approach fails, then there's nothing we can do
                    if (fallback) {
                        // Re-initialize in case some columns were added before failing
                        columnList = new ArrayList<Column>();

                        logger.debug("Using fallback method for retrieving columns");
                        backupRs = dbMetaData.getColumns(null, null, tableName.replace("/", "//"), null);

                        // retrieve all relevant column information                         
                        while (backupRs.next()) {
                            Column column = new Column(backupRs.getString("COLUMN_NAME"),
                                    backupRs.getString("TYPE_NAME"), backupRs.getInt("COLUMN_SIZE"));
                            columnList.add(column);
                        }
                    }
                }

                // create table object and add to the list of table definitions
                Table table = new Table(tableName, columnList);
                tableInfoList.add(table);
            } finally {
                if (rs != null) {
                    rs.close();
                }

                if (backupRs != null) {
                    backupRs.close();
                }
            }
        }

        return tableInfoList;
    } catch (Exception e) {
        throw new MirthApiException(new Exception("Could not retrieve database tables and columns.", e));
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:de.erdesignerng.dialect.JDBCReverseEngineeringStrategy.java

public List<SchemaEntry> getSchemaEntries(Connection aConnection) throws SQLException {
    List<SchemaEntry> theList = new ArrayList<>();

    DatabaseMetaData theMetadata = aConnection.getMetaData();
    ResultSet theResult = theMetadata.getSchemas();

    while (theResult.next()) {
        String theSchemaName = theResult.getString("TABLE_SCHEM");
        String theCatalogName = theResult.getString("TABLE_CATALOG");

        theList.add(new SchemaEntry(theCatalogName, theSchemaName));
    }/*  www.  j ava2  s.  c o  m*/

    return theList;
}

From source file:net.certifi.audittablegen.GenericDMR.java

@Override
public void setSchema(String unverifiedSchema) {

    this.unverifiedSchema = unverifiedSchema;
    this.verifiedSchema = null;

    if (unverifiedSchema == null) {
        return;//from  www.  j a v a 2  s  .  co m
    }

    try (Connection conn = dataSource.getConnection()) {

        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getSchemas();
        while (rs.next()) {
            if (rs.getString("TABLE_SCHEM").trim().equalsIgnoreCase(unverifiedSchema)) {
                //store value with whatever case sensitivity it is returned as
                verifiedSchema = rs.getString("TABLE_SCHEM").trim();
            }
        }
        rs.close();
    } catch (SQLException e) {
        logger.error("error verifying schema", e);
    }
}

From source file:net.certifi.audittablegen.AuditTableGen.java

/**
 * Examines the DataSource metadata for information pertaining to the
 * driver, catalog, schema and the presence of audit table configuration
 * data./* w w w  .j av  a 2s.c o  m*/
 * 
 * @return String containing datasource information.
 * @throws SQLException 
 */
String getDataSourceInfo() throws SQLException {

    Connection conn = dataSource.getConnection();
    DatabaseMetaData dmd = conn.getMetaData();
    StringBuilder s = new StringBuilder();

    s.append("Driver Name: ").append(dmd.getDriverName()).append("Driver Version: ")
            .append(dmd.getDriverVersion()).append(System.lineSeparator()).append("CatalogSeperator: ")
            .append(dmd.getCatalogSeparator()).append(System.lineSeparator()).append("CatalogTerm: ")
            .append(dmd.getCatalogTerm()).append(System.lineSeparator()).append("SchemaTerm: ")
            .append(dmd.getSchemaTerm()).append(System.lineSeparator()).append("Catalogs: ");

    ResultSet rs = dmd.getCatalogs();
    while (rs.next()) {
        s.append(rs.getString("TABLE_CAT")).append(",");
        logger.debug("Catalog: {}", rs.getString("TABLE_CAT"));
    }
    rs.close();
    s.append(System.lineSeparator());

    s.append("Schemas: ");
    rs = dmd.getSchemas();
    while (rs.next()) {
        logger.debug("Schema: {}", rs.getString("TABLE_SCHEM"));
        s.append("{catalog}:").append(rs.getString("TABLE_CATALOG")).append(" {schema}:")
                .append(rs.getString("TABLE_SCHEM")).append(",");
    }
    rs.close();
    s.append(System.lineSeparator()).append("Target Catalog: ").append(catalog).append(System.lineSeparator())
            .append("Target Schema: ").append(schema).append(System.lineSeparator());

    //       if (dmr.hasAuditConfigTable()){
    //           s.append("Has auditConfigSource table").append(System.lineSeparator());
    //       }

    conn.close();

    return s.toString();

}

From source file:it.eng.spagobi.meta.initializer.PhysicalModelInitializer.java

private void addSchema(DatabaseMetaData dbMeta, PhysicalModel model, String defaultSchema) {
    String schema;//from  w w  w  .  java  2  s .  com
    List<String> schemas;
    ResultSet rs;
    Iterator<String> it;

    schema = null;

    try {
        rs = dbMeta.getSchemas();
        schemas = new ArrayList();
        while (rs.next()) {
            String schemaName = rs.getString(1);
            if (schemaName != null) {
                schemas.add(rs.getString(1));
            }
        }

        if (schemas.size() == 0) {
            log("No schema [" + dbMeta.getSchemaTerm() + "] defined");
        } else if (schemas.size() == 1) {
            schema = schemas.get(1);
        } else {
            String targetSchema = null;
            it = schemas.iterator();
            while (it.hasNext()) {
                String s = it.next();
                if (s.equalsIgnoreCase(defaultSchema)) {
                    targetSchema = defaultSchema;
                    break;
                }
            }
            if (targetSchema == null) {
                throw new RuntimeException("No schema named [" + defaultSchema + "] is available on db");
            }
            schema = targetSchema;
        }
        rs.close();
        model.setSchema(schema);
    } catch (Throwable t) {
        throw new RuntimeException("Impossible to initialize schema metadata", t);
    }
}

From source file:com.netspective.axiom.policy.AnsiDatabasePolicy.java

public void reverseEngineer(Writer writer, Connection conn, String catalog, String schemaPattern)
        throws IOException, SQLException {
    Map dataTypesMap = prepareJdbcTypeInfoMap();
    DatabaseMetaData dbmd = conn.getMetaData();
    TextUtils textUtils = TextUtils.getInstance();

    writer.write("<?xml version=\"1.0\"?>\n\n");
    writer.write("<!-- Reverse engineered by Axiom\n");
    writer.write("     driver: " + dbmd.getDriverName() + "\n");
    writer.write("     driver-version: " + dbmd.getDriverVersion() + "\n");
    writer.write("     product: " + dbmd.getDatabaseProductName() + "\n");
    writer.write("     product-version: " + dbmd.getDatabaseProductVersion() + "\n");

    writer.write("     available catalogs:");
    ResultSet rs = null;//  ww  w.j  a v  a 2s  .c  om
    try {
        rs = dbmd.getCatalogs();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }

    writer.write("\n");

    writer.write("     available schemas:");
    try {
        rs = dbmd.getSchemas();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }
    writer.write("\n");
    writer.write("-->\n\n");

    writer.write("<component xmlns:xdm=\"http://www.netspective.org/Framework/Commons/XMLDataModel\">\n");
    writer.write("    <xdm:include resource=\"com/netspective/axiom/conf/axiom.xml\"/>\n");
    writer.write("    <schema name=\"" + catalog + "." + schemaPattern + "\">\n");

    Map dbmdTypeInfoByName = new HashMap();
    Map dbmdTypeInfoByJdbcType = new HashMap();
    ResultSet typesRS = null;
    try {
        typesRS = dbmd.getTypeInfo();
        while (typesRS.next()) {
            int colCount = typesRS.getMetaData().getColumnCount();
            Object[] typeInfo = new Object[colCount];
            for (int i = 1; i <= colCount; i++)
                typeInfo[i - 1] = typesRS.getObject(i);
            dbmdTypeInfoByName.put(typesRS.getString(1), typeInfo);
            dbmdTypeInfoByJdbcType.put(new Integer(typesRS.getInt(2)), typeInfo);
        }
    } finally {
        if (typesRS != null)
            typesRS.close();
    }

    ResultSet tables = null;
    try {
        tables = dbmd.getTables(catalog, schemaPattern, null, new String[] { "TABLE" });
        while (tables.next()) {
            String tableNameOrig = tables.getString(3);
            String tableName = textUtils.fixupTableNameCase(tableNameOrig);

            writer.write("        <table name=\"" + tableName + "\">\n");

            Map primaryKeys = new HashMap();
            ResultSet pkRS = null;
            try {
                pkRS = dbmd.getPrimaryKeys(null, null, tableNameOrig);
                while (pkRS.next()) {
                    primaryKeys.put(pkRS.getString(4), pkRS.getString(5));
                }

            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (pkRS != null)
                    pkRS.close();
            }

            Map fKeys = new HashMap();
            ResultSet fkRS = null;
            try {
                fkRS = dbmd.getImportedKeys(null, null, tableNameOrig);
                while (fkRS.next()) {
                    fKeys.put(fkRS.getString(8), textUtils.fixupTableNameCase(fkRS.getString(3)) + "."
                            + fkRS.getString(4).toLowerCase());
                }
            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (fkRS != null)
                    fkRS.close();
            }

            // we keep track of processed columns so we don't duplicate them in the XML
            Set processedColsMap = new HashSet();
            ResultSet columns = null;
            try {
                columns = dbmd.getColumns(null, null, tableNameOrig, null);
                while (columns.next()) {
                    String columnNameOrig = columns.getString(4);
                    if (processedColsMap.contains(columnNameOrig))
                        continue;
                    processedColsMap.add(columnNameOrig);

                    String columnName = columnNameOrig.toLowerCase();

                    writer.write("            <column name=\"" + columnName + "\"");
                    try {
                        if (fKeys.containsKey(columnNameOrig))
                            writer.write(" lookup-ref=\"" + fKeys.get(columnNameOrig) + "\"");
                        else {
                            short jdbcType = columns.getShort(5);
                            String dataType = (String) dataTypesMap.get(new Integer(jdbcType));
                            if (dataType == null)
                                dataType = Short.toString(jdbcType);
                            writer.write(" type=\"" + dataType + "\"");
                        }

                        if (primaryKeys.containsKey(columnNameOrig))
                            writer.write(" primary-key=\"yes\"");

                        if (columns.getString(18).equals("NO"))
                            writer.write(" required=\"yes\"");

                        String defaultValue = columns.getString(13);
                        if (defaultValue != null)
                            writer.write(" default=\"" + defaultValue + "\"");

                        String remarks = columns.getString(12);
                        if (remarks != null)
                            writer.write(" descr=\"" + remarks + "\"");

                    } catch (Exception e) {
                    }

                    writer.write("/>\n");
                }
            } finally {
                if (columns != null)
                    columns.close();
            }

            writer.write("        </table>\n");
        }
    } finally {
        tables.close();
    }

    writer.write("    </schema>\n");
    writer.write("</component>");
}