Example usage for java.sql DatabaseMetaData getTables

List of usage examples for java.sql DatabaseMetaData getTables

Introduction

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

Prototype

ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[])
        throws SQLException;

Source Link

Document

Retrieves a description of the tables available in the given catalog.

Usage

From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * Checks if the required schema objects exist and creates them if they
 * don't exist yet./*  w  w  w.j av  a2 s.co  m*/
 *
 * @throws Exception if an error occurs
 */
protected void checkSchema() throws Exception {
    DatabaseMetaData metaData = con.getMetaData();
    String tableName = schemaObjectPrefix + "NODE";
    if (metaData.storesLowerCaseIdentifiers()) {
        tableName = tableName.toLowerCase();
    } else if (metaData.storesUpperCaseIdentifiers()) {
        tableName = tableName.toUpperCase();
    }

    ResultSet rs = metaData.getTables(null, null, tableName, null);
    boolean schemaExists;
    try {
        schemaExists = rs.next();
    } finally {
        rs.close();
    }

    if (!schemaExists) {
        // read ddl from resources
        InputStream in = getSchemaDDL();
        if (in == null) {
            String msg = "Configuration error: unknown schema '" + schema + "'";
            log.debug(msg);
            throw new RepositoryException(msg);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        Statement stmt = con.createStatement();
        try {
            String sql = reader.readLine();
            while (sql != null) {
                // Skip comments and empty lines
                if (!sql.startsWith("#") && sql.length() > 0) {
                    // replace prefix variable
                    sql = createSchemaSql(sql);
                    // execute sql stmt
                    stmt.executeUpdate(sql);
                }
                // read next sql stmt
                sql = reader.readLine();
            }
            // commit the changes
            con.commit();
        } finally {
            IOUtils.closeQuietly(in);
            closeStatement(stmt);
        }
    }
}

From source file:org.executequery.databaseobjects.impl.DefaultDatabaseHost.java

/**
 * Returns the tables hosted by this host of the specified type and
 * belonging to the specified catalog and schema.
 *
 * @param catalog the table catalog name
 * @param schema the table schema name//from  w  w  w  .  ja  va2 s.com
 * @param type the table type
 * @return the hosted tables
 */
public List<NamedObject> getTables(String catalog, String schema, String type) throws DataSourceException {

    ResultSet rs = null;
    try {
        String _catalog = getCatalogNameForQueries(catalog);
        String _schema = getSchemaNameForQueries(schema);
        DatabaseMetaData dmd = getDatabaseMetaData();

        String tableName = null;
        String typeName = null;

        List<NamedObject> tables = new ArrayList<NamedObject>();

        String[] types = null;
        if (type != null) {

            types = new String[] { type };
        }

        rs = dmd.getTables(_catalog, _schema, null, types);

        // make sure type isn't null for compare
        if (type == null) {
            type = "";
        }

        while (rs.next()) {

            tableName = rs.getString(3);
            typeName = rs.getString(4);

            // only include if the returned reported type matches
            if (type.equalsIgnoreCase(typeName)) {

                DefaultDatabaseObject object = new DefaultDatabaseObject(this, type);
                object.setCatalogName(catalog);
                object.setSchemaName(schema);
                object.setName(tableName);
                object.setRemarks(rs.getString(5));
                tables.add(object);
            }

        }

        return tables;

    } catch (SQLException e) {

        if (Log.isDebugEnabled()) {

            Log.error("Tables not available for type " + type + " - driver returned: " + e.getMessage());
        }

        return new ArrayList<NamedObject>(0);

    } finally {

        releaseResources(rs);
    }

}

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

/**
 * Get tables and columns names that are present in the database but not in the passed physical model
 * //from  www.  j  a  va 2s . c  om
 * @param connection
 *            jdbc connection to the database
 * @param physicalModel
 *            physical model to check
 */
public List<String> getRemovedTablesAndColumnsNames(Connection connection, PhysicalModel physicalModel) {
    try {
        DatabaseMetaData dbMeta = connection.getMetaData();

        List<String> tablesOnDatabase = new ArrayList<String>();
        List<String> tablesRemoved = new ArrayList<String>();
        List<String> columnsRemoved = new ArrayList<String>();

        ResultSet tableRs = dbMeta.getTables(physicalModel.getCatalog(), physicalModel.getSchema(), null,
                new String[] { "TABLE", "VIEW" });

        while (tableRs.next()) {
            String tableName = tableRs.getString("TABLE_NAME");
            tablesOnDatabase.add(tableName);
        }
        tableRs.close();

        EList<PhysicalTable> originalTables = physicalModel.getTables();

        Iterator<PhysicalTable> physicalTablesIterator = originalTables.iterator();
        // 1- Check table existence
        while (physicalTablesIterator.hasNext()) {
            PhysicalTable originalTable = physicalTablesIterator.next();
            String tableToFind = originalTable.getName();
            if (!tablesOnDatabase.contains(tableToFind)) {
                // tables not found on database -> removed
                tablesRemoved.add(tableToFind);
            } else {
                // 2 - Check columns existence
                List<PhysicalColumn> physicalColumns = originalTable.getColumns();
                ResultSet rs = dbMeta.getColumns(physicalModel.getCatalog(), physicalModel.getSchema(),
                        originalTable.getName(), null);
                List<String> columnsNamesOnDb = new ArrayList<String>();
                while (rs.next()) {
                    String columnName = rs.getString("COLUMN_NAME");
                    columnsNamesOnDb.add(columnName);
                }
                for (PhysicalColumn physicalColumn : physicalColumns) {
                    if (!columnsNamesOnDb.contains(physicalColumn.getName())) {
                        // column not found on database -> removed
                        columnsRemoved.add(originalTable.getName() + "." + physicalColumn.getName());
                    }
                }

            }
        }

        // merge two list
        tablesRemoved.addAll(columnsRemoved);

        return tablesRemoved;

    } catch (SQLException e) {
        throw new RuntimeException("Physical Model - Impossible to get missing tables names", e);

    }
}

From source file:org.batoo.jpa.jdbc.adapter.JdbcAdaptor.java

private JdbcTable getTableMetadata(DataSource datasource, String catalog, String schema, String table)
        throws SQLException {
    final Connection connection = datasource.getConnection();

    ResultSet tables = null;//from w  ww  .j  av a 2s  .  co m
    try {
        final DatabaseMetaData dbMetadata = connection.getMetaData();
        if (StringUtils.isBlank(catalog)) {
            catalog = null;
        }
        if (StringUtils.isBlank(schema)) {
            schema = null;
        }

        if (dbMetadata.storesUpperCaseIdentifiers()) {
            tables = dbMetadata.getTables(//
                    BatooUtils.upper(catalog), //
                    BatooUtils.upper(schema), //
                    BatooUtils.upper(table), //
                    JdbcAdaptor.TABLE_OR_VIEW);
        } else if (dbMetadata.storesLowerCaseIdentifiers()) {
            tables = dbMetadata.getTables(//
                    BatooUtils.lower(catalog), //
                    BatooUtils.lower(schema), //
                    BatooUtils.lower(table), //
                    JdbcAdaptor.TABLE_OR_VIEW);
        } else {
            tables = dbMetadata.getTables(catalog, schema, table, JdbcAdaptor.TABLE_OR_VIEW);
        }

        if (tables.next()) {
            final String tableName = tables.getString(JdbcAdaptor.TABLE_NAME);
            if (table.equalsIgnoreCase(tableName)) {
                return new JdbcTable(dbMetadata, tables);
            }
        }
    } finally {
        DbUtils.closeQuietly(connection);
        DbUtils.closeQuietly(tables);
    }

    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;//ww  w.  jav a  2 s  .c om
    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:org.nuclos.server.masterdata.ejb3.MetaDataFacadeBean.java

/**
 * @return Script (with results if selected)
 *//*  w  w  w .j  av a 2  s .c  o m*/
@Override
@RolesAllowed("Login")
public List<String> getTablesFromSchema(String url, String user, String password, String schema) {
    List<String> lstTables = new ArrayList<String>();
    Connection connect = null;
    try {
        connect = DriverManager.getConnection(url, user, password);
        DatabaseMetaData dbmeta = connect.getMetaData();
        ResultSet rsTables = dbmeta.getTables(null, schema.toUpperCase(), "%", new String[] { "TABLE" });
        while (rsTables.next()) {
            lstTables.add(rsTables.getString("TABLE_NAME"));
        }
        rsTables.close();
    } catch (SQLException e) {
        throw new CommonFatalException(e);
    } finally {
        if (connect != null)
            try {
                connect.close();
            } catch (SQLException e) {
                // do noting here
                LOG.info("getTablesFromSchema: " + e);
            }
    }

    return lstTables;
}

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 {/*from   w w w . j a  va2 s .  c om*/
            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.jav a  2s  .c  o m*/
            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:net.sf.farrago.namespace.jdbc.MedJdbcDataServer.java

private void createSchemaMaps(DatabaseMetaData databaseMetaData, String key, String value) throws SQLException {
    if ((key == null) || (value == null)) {
        return;// ww  w  . ja  v  a  2s  .  c o m
    }

    if (!key.equals("") && !value.equals("")) {
        Map<String, String> h = new HashMap<String, String>();
        if (schemaMaps.get(value) != null) {
            h = schemaMaps.get(value);
        }
        ResultSet resultSet = null;
        try {
            resultSet = databaseMetaData.getTables(catalogName, key, null, tableTypes);
            if (resultSet == null) {
                return;
            }
            while (resultSet.next()) {
                h.put(resultSet.getString(3), key);
            }
            schemaMaps.put(value, h);
        } catch (Throwable ex) {
            // assume unsupported
            return;
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
        }
    }
}

From source file:it.unibas.spicy.persistence.relational.DAORelational.java

@SuppressWarnings("unchecked")
public void loadInstanceSample(AccessConfiguration accessConfiguration, IDataSourceProxy dataSource,
        DBFragmentDescription dataDescription, IConnectionFactory dataSourceDB, String rootLabel,
        boolean translated) throws DAOException {
    String catalog = null;/*from w  w  w  .  j  a v  a2 s.  c  o  m*/
    INode root = null;
    String schemaName = accessConfiguration.getSchemaName();
    DatabaseMetaData databaseMetaData = null;
    Connection connection = dataSourceDB.getConnection(accessConfiguration);
    try {
        databaseMetaData = connection.getMetaData();
        catalog = connection.getCatalog();
        if (catalog == null) {
            catalog = accessConfiguration.getUri();
            if (logger.isDebugEnabled())
                logger.debug("Catalog is null. Catalog name will be: " + catalog);
        }
        if (logger.isDebugEnabled())
            logger.debug("Catalog: " + catalog);
        if (rootLabel == null) {
            root = new TupleNode(DAORelationalUtility.getNode(catalog).getLabel(), getOID());
        } else {
            this.dataDescription = dataDescription;
            root = new TupleNode(rootLabel, getOID());
        }
        root.setRoot(true);
        String[] tableTypes = new String[] { "TABLE" };
        ResultSet tableResultSet = databaseMetaData.getTables(catalog, schemaName, null, tableTypes);
        while (tableResultSet.next()) {
            String tableName = tableResultSet.getString("TABLE_NAME");
            if (!this.dataDescription.checkLoadTable(tableName)) {
                continue;
            }
            SetNode setTable = new SetNode(DAORelationalUtility.getNode(tableName).getLabel(), getOID());
            ////INode setTable = new SetNode(tableName, getOID());
            //keep the number of instances as information on the Set node
            String tablePath;
            //mysql driver
            if (accessConfiguration.getDriver().equalsIgnoreCase(SpicyEngineConstants.MYSQL_DRIVER)) {
                tablePath = catalog + "." + tableName;
            } else {
                tablePath = "\"" + schemaName + "\".\"" + tableName + "\"";
            }
            Statement statement = connection.createStatement();
            ResultSet countResult = statement
                    .executeQuery("SELECT COUNT(*) AS instancesCount FROM " + tablePath + ";");
            int noOfRows = 0;
            while (countResult.next()) {
                noOfRows = countResult.getInt("instancesCount");
            }
            setTable.setFullSize(noOfRows);
            countResult.close();

            if (logger.isDebugEnabled())
                logger.debug("extracting value for table " + tableName + " ....");
            getInstanceByTable(dataSourceDB, connection, schemaName, tableName, setTable, dataSource,
                    translated);
            root.addChild(setTable);
        }
        int childrenNo = 0;
        for (INode setnode : root.getChildren()) {
            childrenNo = childrenNo + setnode.getChildren().size();
        }
        //if there are any instances
        if (childrenNo > 0) {
            //load only a sample of the instances to memory to show on MIPMap interface
            dataSource.addInstanceWithCheck(root);
        }
    } catch (SQLException | DAOException ex) {
        logger.error(ex);
        throw new DAOException(ex.getMessage());
    } finally {
        if (connection != null)
            dataSourceDB.close(connection);
    }
}