Example usage for java.sql DatabaseMetaData getCatalogs

List of usage examples for java.sql DatabaseMetaData getCatalogs

Introduction

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

Prototype

ResultSet getCatalogs() throws SQLException;

Source Link

Document

Retrieves the catalog names available in this database.

Usage

From source file:org.beangle.webapp.database.action.DatasourceAction.java

public String test() {
    Long datasourceId = getEntityId("datasource");
    DataSource dataSource = datasourceService.getDatasource(datasourceId);
    Map<String, String> driverinfo = CollectUtils.newHashMap();
    Map<String, Object> dbinfo = CollectUtils.newHashMap();
    Map<String, Object> jdbcinfo = CollectUtils.newHashMap();
    Connection con = null;//from   w  ww .j av  a2s  .  c  o  m
    try {
        con = dataSource.getConnection();
        if (con != null) {
            java.sql.DatabaseMetaData dm = con.getMetaData();
            driverinfo.put("Driver Name", dm.getDriverName());
            driverinfo.put("Driver Version", dm.getDriverVersion());
            dbinfo.put("Database Name", dm.getDatabaseProductName());
            dbinfo.put("Database Version", dm.getDatabaseProductVersion());
            jdbcinfo.put("JDBC Version", dm.getJDBCMajorVersion() + "." + dm.getJDBCMinorVersion());
            StringBuilder catelogs = new StringBuilder();
            dbinfo.put("Avalilable Catalogs", catelogs);
            java.sql.ResultSet rs = dm.getCatalogs();
            while (rs.next()) {
                catelogs.append(rs.getString(1));
                if (rs.next())
                    catelogs.append(',');
            }
            rs.close();
        }
    } catch (Exception e) {
        put("exceptionStack", ExceptionUtils.getFullStackTrace(e));
    } finally {
        try {
            if (con != null)
                con.close();
            con = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    put("driverinfo", driverinfo);
    put("dbinfo", dbinfo);
    put("jdbcinfo", jdbcinfo);
    return forward();
}

From source file:org.easyrec.utils.spring.store.dao.impl.DBRootDAOMysqlImpl.java

@SuppressWarnings({ "unchecked" })
public boolean existsDatabase(String databaseName) {
    // get the list of all databases from the db server
    List<String> dbNames;
    DatabaseMetaDataCallback callback = new DatabaseMetaDataCallback() {
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            List<String> ret = new LinkedList<String>();
            ResultSet rs = dbmd.getCatalogs();
            while (rs.next()) {
                ret.add(rs.getString(1));
            }// w  ww.jav  a  2 s . c  om
            return ret;
        }
    };
    try {
        dbNames = (List<String>) JdbcUtils.extractDatabaseMetaData(getDataSource(), callback);
    } catch (Exception e) {
        throw new RuntimeException("unable to read database metadata", e);
    }

    return dbNames.contains(databaseName);
}

From source file:org.executequery.databasemediators.spi.DefaultStatementExecutor.java

/** <p>Retrieves a description of the specified table using
 *  the connection's <code>DatabaseMetaData</code> object
 *  and the method <code>getColumns(...)</code>.
 *
 *  @param  the table name to describe//from   w ww.  ja  v  a2s.  com
 *  @return the query result
 */
private SqlStatementResult getTableDescription(String tableName) throws SQLException {

    if (!prepared()) {

        return statementResult;
    }

    DatabaseHost host = null;
    try {

        /* -------------------------------------------------
         * Database meta data values can be case-sensitive.
         * search for a match and use as returned from dmd.
         * -------------------------------------------------
         */

        String name = tableName;
        String catalog = null;
        String schema = null;

        host = new DatabaseObjectFactoryImpl().createDatabaseHost(databaseConnection);

        int nameDelim = tableName.indexOf('.');
        if (nameDelim != -1) {

            name = tableName.substring(nameDelim + 1);
            String value = tableName.substring(0, nameDelim);
            DatabaseMetaData databaseMetaData = host.getDatabaseMetaData();

            if (host.supportsCatalogsInTableDefinitions()) {

                ResultSet resultSet = databaseMetaData.getCatalogs();
                while (resultSet.next()) {

                    String _catalog = resultSet.getString(1);
                    if (value.equalsIgnoreCase(_catalog)) {

                        catalog = _catalog;
                        break;
                    }
                }

                resultSet.close();

            } else if (host.supportsSchemasInTableDefinitions()) {

                ResultSet resultSet = databaseMetaData.getCatalogs();
                while (resultSet.next()) {

                    String _schema = resultSet.getString(1);
                    if (value.equalsIgnoreCase(_schema)) {

                        schema = _schema;
                        break;
                    }
                }

                resultSet.close();
            }

        }

        DatabaseMetaData databaseMetaData = host.getDatabaseMetaData();
        ResultSet resultSet = databaseMetaData.getTables(catalog, schema, null, null);

        String nameToSearchOn = null;
        while (resultSet.next()) {

            String _tableName = resultSet.getString(3);
            if (_tableName.equalsIgnoreCase(name)) {

                nameToSearchOn = _tableName;
                break;
            }

        }
        resultSet.close();

        if (StringUtils.isNotBlank(nameToSearchOn)) {

            databaseMetaData = conn.getMetaData();
            resultSet = databaseMetaData.getColumns(catalog, schema, nameToSearchOn, null);
            statementResult.setResultSet(resultSet);

        } else {

            statementResult.setMessage("Invalid table name");
        }

    } catch (SQLException e) {

        statementResult.setSqlException(e);
        finished();

    } catch (OutOfMemoryError e) {

        statementResult.setMessage(e.getMessage());
        releaseResources();

    } finally {

        if (host != null) {

            host.close();
        }

    }

    return statementResult;
}

From source file:org.jumpmind.db.platform.AbstractJdbcDdlReader.java

public List<String> getCatalogNames() {
    JdbcSqlTemplate sqlTemplate = (JdbcSqlTemplate) platform.getSqlTemplate();
    return sqlTemplate.execute(new IConnectionCallback<List<String>>() {
        public List<String> execute(Connection connection) throws SQLException {
            ArrayList<String> catalogs = new ArrayList<String>();
            DatabaseMetaData meta = connection.getMetaData();
            ResultSet rs = null;/*from ww  w.  j  ava 2s  . c o m*/
            try {
                rs = meta.getCatalogs();
                while (rs.next()) {
                    catalogs.add(rs.getString(1));
                }
                return catalogs;
            } finally {
                JdbcSqlTemplate.close(rs);
            }
        }
    });
}

From source file:org.ralasafe.db.DBView.java

public static String[] getAllSchemasFromDB(String dsName) {
    Connection conn = null;/*from   w  w  w. j a  v a  2 s  .c om*/
    ResultSet rs = null;

    try {
        conn = DBPower.getConnection(dsName);

        DatabaseMetaData metaData = conn.getMetaData();

        String databaseProductName = DBUtil.getDatabaseProductName(conn);
        if (databaseProductName == DBUtil.MYSQL || databaseProductName == DBUtil.SQLSERVER) {
            rs = metaData.getCatalogs();
        } else {
            rs = metaData.getSchemas();
        }

        List result = new LinkedList();
        while (rs.next()) {
            String name = rs.getString(1);
            result.add(name);
        }

        String[] names = new String[result.size()];
        Iterator itr = result.iterator();
        for (int i = 0; i < names.length; i++) {
            names[i] = (String) itr.next();
        }
        return names;
    } catch (SQLException e) {
        log.error("", e);
        throw new DBLevelException(e);
    } finally {
        DBUtil.close(rs);
        DBUtil.close(conn);
    }
}

From source file:org.ramadda.repository.database.DatabaseManager.java

/**
 * _more_/*ww w  .  j  a  v  a2s. c  o  m*/
 *
 * @param os _more_
 * @param all _more_
 *
 * @throws Exception _more_
 */
public void makeDatabaseCopyxxx(OutputStream os, boolean all) throws Exception {

    Connection connection = getConnection();
    try {
        DatabaseMetaData dbmd = connection.getMetaData();
        ResultSet catalogs = dbmd.getCatalogs();
        ResultSet tables = dbmd.getTables(null, null, null, new String[] { "TABLE" });

        ResultSetMetaData rsmd = tables.getMetaData();
        for (int col = 1; col <= rsmd.getColumnCount(); col++) {
            System.err.println(rsmd.getColumnName(col));
        }
        int totalRowCnt = 0;
        while (tables.next()) {
            //                String tableName = tables.getString("Tables.NAME.NAME");
            //                String tableType = tables.getString("Tables.TYPE.NAME");
            String tableName = tables.getString("TABLE_NAME");
            String tableType = tables.getString("TABLE_TYPE");
            if ((tableType == null) || Misc.equals(tableType, "INDEX") || tableType.startsWith("SYSTEM")) {
                continue;
            }

            String tn = tableName.toLowerCase();
            if (!all) {
                if (tn.equals(Tables.GLOBALS.NAME) || tn.equals(Tables.USERS.NAME)
                        || tn.equals(Tables.PERMISSIONS.NAME) || tn.equals(Tables.HARVESTERS.NAME)
                        || tn.equals(Tables.USERROLES.NAME)) {
                    continue;
                }
            }

            ResultSet cols = dbmd.getColumns(null, null, tableName, null);

            int colCnt = 0;

            String colNames = null;
            List types = new ArrayList();
            while (cols.next()) {
                String colName = cols.getString("COLUMN_NAME");
                if (colNames == null) {
                    colNames = " (";
                } else {
                    colNames += ",";
                }
                colNames += colName;
                int type = cols.getInt("DATA_TYPE");
                types.add(type);
                colCnt++;
            }
            colNames += ") ";

            Statement statement = execute("select * from " + tableName, 10000000, 0);
            SqlUtil.Iterator iter = getIterator(statement);
            ResultSet results;
            int rowCnt = 0;
            List valueList = new ArrayList();
            boolean didDelete = false;
            while ((results = iter.getNext()) != null) {
                if (!didDelete) {
                    didDelete = true;
                    IOUtil.write(os, "delete from  " + tableName.toLowerCase() + ";\n");
                }
                totalRowCnt++;
                rowCnt++;
                StringBuffer value = new StringBuffer("(");
                for (int i = 1; i <= colCnt; i++) {
                    int type = ((Integer) types.get(i - 1)).intValue();
                    if (i > 1) {
                        value.append(",");
                    }
                    if (type == java.sql.Types.TIMESTAMP) {
                        Timestamp ts = results.getTimestamp(i);
                        //                            sb.append(SqlUtil.format(new Date(ts.getTime())));
                        if (ts == null) {
                            value.append("null");
                        } else {
                            value.append(HtmlUtils.squote(ts.toString()));
                        }

                    } else if (type == java.sql.Types.VARCHAR) {
                        String s = results.getString(i);
                        if (s != null) {
                            //If the target isn't mysql:
                            //s = s.replace("'", "''");
                            //If the target is mysql:
                            s = s.replace("'", "\\'");
                            s = s.replace("\r", "\\r");
                            s = s.replace("\n", "\\n");
                            value.append("'" + s + "'");
                        } else {
                            value.append("null");
                        }
                    } else {
                        String s = results.getString(i);
                        value.append(s);
                    }
                }
                value.append(")");
                valueList.add(value.toString());
                if (valueList.size() > 50) {
                    IOUtil.write(os, "insert into " + tableName.toLowerCase() + colNames + " values ");
                    IOUtil.write(os, StringUtil.join(",", valueList));
                    IOUtil.write(os, ";\n");
                    valueList = new ArrayList();
                }
            }
            if (valueList.size() > 0) {
                if (!didDelete) {
                    didDelete = true;
                    IOUtil.write(os, "delete from  " + tableName.toLowerCase() + ";\n");
                }
                IOUtil.write(os, "insert into " + tableName.toLowerCase() + colNames + " values ");
                IOUtil.write(os, StringUtil.join(",", valueList));
                IOUtil.write(os, ";\n");
            }
        }
    } finally {
        closeConnection(connection);
    }

}

From source file:org.ramadda.repository.database.DatabaseManager.java

/**
 * Actually write the tables// w  w  w .  j  ava 2  s.  c om
 *
 * @param pw What to write to
 * @param packageName Tables.java package name
 * @param what _more_
 *
 * @throws Exception on badness
 */

private void writeTables(PrintWriter pw, String packageName, String[] what) throws Exception {

    String sp1 = "    ";
    String sp2 = sp1 + sp1;
    String sp3 = sp1 + sp1 + sp1;

    pw.append(
            "/**Generated by running: java org.unavco.projects.gsac.repository.UnavcoGsacDatabaseManager**/\n\n");
    pw.append("package " + packageName + ";\n\n");
    pw.append("import org.ramadda.sql.SqlUtil;\n\n");
    pw.append("//J-\n");
    pw.append("public abstract class Tables {\n");
    pw.append(sp1 + "public abstract String getName();\n");
    pw.append(sp1 + "public abstract String getColumns();\n");
    Connection connection = getConnection();
    DatabaseMetaData dbmd = connection.getMetaData();
    ResultSet catalogs = dbmd.getCatalogs();
    ResultSet tables = dbmd.getTables(null, null, null, what);

    HashSet seenTables = new HashSet();
    while (tables.next()) {
        String tableName = tables.getString("TABLE_NAME");
        //            System.err.println ("NAME:" + tableName);
        String TABLENAME = tableName.toUpperCase();
        if (seenTables.contains(TABLENAME)) {
            continue;
        }
        seenTables.add(TABLENAME);
        String tableType = tables.getString("TABLE_TYPE");
        if (Misc.equals(tableType, "INDEX")) {
            continue;
        }
        if (tableName.indexOf("$") >= 0) {
            continue;
        }

        if (tableType == null) {
            continue;
        }

        if ((tableType != null) && tableType.startsWith("SYSTEM")) {
            continue;
        }

        ResultSet columns = dbmd.getColumns(null, null, tableName, null);

        List colNames = new ArrayList();
        pw.append("\n\n");
        pw.append(sp1 + "public static class " + TABLENAME + " extends Tables {\n");

        pw.append(sp2 + "public static final String NAME = \"" + tableName.toLowerCase() + "\";\n");
        pw.append("\n");
        pw.append(sp2 + "public String getName() {return NAME;}\n");
        pw.append(sp2 + "public String getColumns() {return COLUMNS;}\n");
        System.out.println("processing table:" + TABLENAME);

        String tableVar = null;
        List colVars = new ArrayList();
        HashSet seen = new HashSet();
        while (columns.next()) {
            String colName = columns.getString("COLUMN_NAME").toLowerCase();
            String colSize = columns.getString("COLUMN_SIZE");
            String COLNAME = colName.toUpperCase();
            if (seen.contains(COLNAME)) {
                continue;
            }
            seen.add(COLNAME);
            COLNAME = COLNAME.replace("#", "");
            colNames.add("COL_" + COLNAME);
            pw.append(sp2 + "public static final String COL_" + COLNAME + " =  NAME + \"." + colName + "\";\n");

            pw.append(sp2 + "public static final String COL_NODOT_" + COLNAME + " =   \"" + colName + "\";\n");
            /*
            pw.append(sp2 + "public static final String ORA_" + COLNAME
                  + " =  \"" + colName + "\";\n");
            */
        }

        pw.append("\n");
        pw.append(sp2 + "public static final String[] ARRAY = new String[] {\n");
        pw.append(sp3 + StringUtil.join(",", colNames));
        pw.append("\n");
        pw.append(sp2 + "};\n");
        pw.append(sp2 + "public static final String COLUMNS = SqlUtil.comma(ARRAY);\n");
        pw.append(sp2 + "public static final String NODOT_COLUMNS = SqlUtil.commaNoDot(ARRAY);\n");

        pw.append(sp2 + "public static final String INSERT =" + "SqlUtil.makeInsert(NAME, NODOT_COLUMNS,"
                + "SqlUtil.getQuestionMarks(ARRAY.length));\n");

        pw.append(sp1 + "public static final " + TABLENAME + " table  = new  " + TABLENAME + "();\n");
        pw.append(sp1 + "}\n\n");

    }

    pw.append("\n\n}\n");

}

From source file:org.talend.core.model.metadata.DBConnectionFillerImplTest.java

/**
     * Test filling catalogs for odbc teredata .
     * {@link org.talend.metadata.managment.model.DBConnectionFillerImpl#fillCatalogs(Connection, DatabaseMetaData, IMetadataConnection, List)
     * @throws SQLException/*from   www .  java2 s . c  om*/
     */
@Test
public void testFillCatalogs_AS400() throws SQLException {
    // mock ReturnCode sql.Connection
    java.sql.Connection mockSqlConn = Mockito.mock(java.sql.Connection.class);
    Mockito.when(mockSqlConn.getCatalog()).thenReturn("tbi"); //$NON-NLS-1$
    // ~mock
    // mock ResultSet
    ResultSet mockCatalogResults = Mockito.mock(ResultSet.class);
    Mockito.when(mockCatalogResults.next()).thenReturn(true, false);
    Mockito.when(mockCatalogResults.getString(MetaDataConstants.TABLE_CAT.name())).thenReturn("tbi"); //$NON-NLS-1$
    ResultSet mockSchemaResults = Mockito.mock(ResultSet.class);
    Mockito.when(mockSchemaResults.next()).thenReturn(true, false);
    Mockito.when(mockSchemaResults.getString(MetaDataConstants.TABLE_SCHEM.name())).thenReturn("dbo"); //$NON-NLS-1$
    // ~Result
    // mock JDBC Metadata
    DatabaseMetaData dbJDBCMetadata = mock(DatabaseMetaData.class);
    Mockito.when(dbJDBCMetadata.getDatabaseProductName()).thenReturn(EDatabaseTypeName.AS400.getProduct());
    Mockito.when(dbJDBCMetadata.getDriverName()).thenReturn("com.ibm.as400.access.AS400JDBCDriver"); //$NON-NLS-1$
    Mockito.when(dbJDBCMetadata.getCatalogs()).thenReturn(mockCatalogResults);
    Mockito.when(dbJDBCMetadata.getConnection()).thenReturn(mockSqlConn);

    Mockito.when(dbJDBCMetadata.getSchemas()).thenReturn(mockSchemaResults);
    // ~JDBC Metadata
    //        stub(method(ConnectionUtils.class, "isOdbcTeradata", DatabaseMetaData.class)).toReturn(true); //$NON-NLS-1$
    // mock DatabaseConnection
    List<String> catalogFilter = new ArrayList<String>();
    DatabaseConnection dbConnection = mock(DatabaseConnection.class);
    Mockito.when(dbConnection.getSID()).thenReturn(""); //$NON-NLS-1$
    Mockito.when(dbConnection.getDatabaseType()).thenReturn(EDatabaseTypeName.AS400.getDisplayName());
    Mockito.when(dbConnection.getUiSchema()).thenReturn(""); //$NON-NLS-1$
    // ~DatabaseConnection

    // mock MetadataConnection
    IMetadataConnection metadaConnection = Mockito.mock(MetadataConnection.class);
    Mockito.when(metadaConnection.getDatabase()).thenReturn(""); //$NON-NLS-1$
    // ~MetadataConnection

    // mock ConvertionHelper
    PowerMockito.mockStatic(ConvertionHelper.class);
    Mockito.when(ConvertionHelper.convert(dbConnection)).thenReturn(metadaConnection);
    // Mockito.when(ExtractMetaDataUtils.getDatabaseMetaData(mockSqlConn, EDatabaseTypeName.IBMDB2ZOS.getXmlName(),
    // false, ""))
    // .thenCallRealMethod();
    // ~ConvertionHelper
    // mock ConnectionHelper
    PowerMockito.mockStatic(ConnectionHelper.class);
    Mockito.when(ConnectionHelper.getTables(dbConnection)).thenReturn(new HashSet<MetadataTable>());
    // Mockito.when(ExtractMetaDataUtils.getDatabaseMetaData(mockSqlConn, EDatabaseTypeName.IBMDB2ZOS.getXmlName(),
    // false, ""))
    // .thenCallRealMethod();
    // ~ConnectionHelper

    when(dbConnection.isContextMode()).thenReturn(false);
    List<Catalog> fillCatalogs = this.dBConnectionFillerImpl.fillCatalogs(dbConnection, dbJDBCMetadata, null,
            catalogFilter);
    assertTrue(fillCatalogs.size() == 1);
    assertTrue("tbi".equals(fillCatalogs.get(0).getName()));
    List<Schema> schemas = CatalogHelper.getSchemas(fillCatalogs.get(0));
    assertTrue(schemas.size() == 1);
    assertTrue("dbo".equals(schemas.get(0).getName()));

}

From source file:org.talend.metadata.managment.model.DBConnectionFillerImpl.java

@Override
public List<Catalog> fillCatalogs(DatabaseConnection dbConn, DatabaseMetaData dbJDBCMetadata,
        IMetadataConnection metaConnection, List<String> catalogFilter) {
    List<Catalog> catalogList = new ArrayList<Catalog>();
    if (dbJDBCMetadata == null) {
        return null;
    }//from   w ww . j  a va2 s .c om

    if (ConnectionUtils.isPostgresql(dbJDBCMetadata)) {
        return fillPostgresqlCatalogs(metaConnection, dbConn, dbJDBCMetadata, catalogList);
    }

    // TDI-17172 : if the catalog is not fill, as the db context model, should clear "catalogFilter" .
    if (dbConn != null && dbConn.isContextMode()) {
        if (EDatabaseTypeName.MYSQL.getProduct().equals(dbConn.getProductId())
                || EDatabaseTypeName.MSSQL.getProduct().equals(dbConn.getProductId())
                || EDatabaseTypeName.MSSQL05_08.getProduct().equals(dbConn.getProductId())) {
            IMetadataConnection iMetadataCon = metaConnection;
            if (iMetadataCon == null) {
                iMetadataCon = ConvertionHelper.convert(dbConn);
            }
            if (iMetadataCon != null) {
                String catalogTemp = iMetadataCon.getDatabase();
                if ("".equals(catalogTemp)) { //$NON-NLS-1$
                    catalogFilter.clear();
                }
            }
        }
    }

    try {
        if (!isDbSupportCatalogNames(dbJDBCMetadata)) {
            return catalogList;
        }
        if (!isDbHasCatalogs(dbJDBCMetadata)) {
            ConnectionHelper.removeAllPackages(dbConn);
            return catalogList;
        }
        ResultSet catalogNames = null;
        if (dbJDBCMetadata instanceof SybaseDatabaseMetaData) {
            catalogNames = ((SybaseDatabaseMetaData) dbJDBCMetadata).getCatalogs(dbConn.getUsername());
        } else {
            catalogNames = dbJDBCMetadata.getCatalogs();
        }
        // this filter is for filter schema later
        List<String> schemaFilterList = new ArrayList<String>();
        if (catalogNames != null) {
            boolean isHive = MetadataConnectionUtils.isHive(dbJDBCMetadata);
            boolean isSybase = MetadataConnectionUtils.isSybase(dbJDBCMetadata);
            // else DB support getCatalogs() method
            while (catalogNames.next()) {
                // MOD xqliu 2009-11-03 bug 9841
                String catalogName = null;
                try {
                    String temp = null;
                    // since hive don't support some methods
                    if (isHive) {
                        temp = MetaDataConstants.TABLE_CAT.name();
                    } else {
                        temp = MetadataConnectionUtils.isOdbcPostgresql(dbJDBCMetadata)
                                ? DatabaseConstant.ODBC_POSTGRESQL_CATALOG_NAME
                                : MetaDataConstants.TABLE_CAT.name();
                    }
                    catalogName = catalogNames.getString(temp);
                    // MOD zshen filter ODBC catalog
                    // FIXME isODBCCatalog is not a good name
                    if (!isHive && !MetadataConnectionUtils.isODBCCatalog(catalogName, dbJDBCMetadata)) {
                        continue;
                    }
                } catch (Exception e) {
                    log.warn(e, e);
                    if (dbJDBCMetadata.getDatabaseProductName() != null
                            && dbJDBCMetadata.getDatabaseProductName().toLowerCase()
                                    .indexOf(DatabaseConstant.POSTGRESQL_PRODUCT_NAME) > -1) {
                        catalogName = ""; //$NON-NLS-1$
                    }
                }
                // Changed by Marvin Wang on Jan. 6, 2012 for bug TDI-24222. I haved discussed with Shen Ze about
                // the fix,it is okay for them. What we did is to avoid creating a new catalog when catalogName is
                // "null" for DB2.
                if (catalogName != null) {
                    // MOD xqliu 2010-03-03 feature 11412

                    if (!isNullSID(dbConn) && dbConn != null
                            && !dbConn.getDatabaseType().equals(EDatabaseTypeName.AS400.getDisplayName())
                            && !dbConn.getDatabaseType()
                                    .equals(EDatabaseTypeName.HSQLDB_IN_PROGRESS.getDisplayName())
                            && !dbConn.getDatabaseType()
                                    .equals(EDatabaseTypeName.HSQLDB_SERVER.getDisplayName())
                            && !dbConn.getDatabaseType()
                                    .equals(EDatabaseTypeName.HSQLDB_WEBSERVER.getDisplayName())) {
                        String databaseOnConnWizard = getDatabaseName(dbConn);

                        // If the SID on ui is not empty, the catalog name should be same to this SID name.
                        postFillCatalog(catalogList, catalogFilter, schemaFilterList,
                                TalendCWMService.getReadableName(dbConn, databaseOnConnWizard), dbConn);
                        break;
                    } else if (isCreateElement(catalogFilter, catalogName)) {
                        postFillCatalog(catalogList, catalogFilter, schemaFilterList, catalogName, dbConn);
                    }
                }
                // ~11412
            }
            // --- release the result set.
            catalogNames.close();
            if (!isHive) {
                List<Catalog> removeCatalogList = new ArrayList<Catalog>();
                for (Catalog catalog : catalogList) {
                    List<Schema> schemaList = new ArrayList<Schema>();
                    try {
                        schemaList = fillSchemaToCatalog(dbConn, dbJDBCMetadata, catalog, schemaFilterList);
                        if (!schemaList.isEmpty() && schemaList.size() > 0) {
                            CatalogHelper.addSchemas(schemaList, catalog);
                        }
                    } catch (Throwable e) {
                        removeCatalogList.add(catalog);
                    }
                }
                // TDQ-1625
                if (isSybase && catalogFilter != null && !catalogFilter.isEmpty() && catalogFilter.size() > 0
                        && catalogList.isEmpty() && catalogList.size() == 0) {
                    catalogFilter.clear();
                    return fillCatalogs(dbConn, dbJDBCMetadata, catalogFilter);
                }
                catalogList.removeAll(removeCatalogList);
            }

            Set<MetadataTable> tableSet = ConnectionHelper.getTables(dbConn);
            // replaceCatalogs is use for record tables when click finish, then set to current connection.
            List<Catalog> replaceCatalogs = new ArrayList<Catalog>();
            List<String> catalogName = new ArrayList<String>();
            for (MetadataTable table : tableSet) {
                EObject eContainer = table.eContainer();
                if (eContainer != null) {
                    if (eContainer instanceof Catalog) {
                        Catalog c = (Catalog) eContainer;
                        String name = c.getName();
                        if (!catalogName.contains(name)) {
                            replaceCatalogs.add(c);
                            catalogName.add(name);
                        }
                    } else if (eContainer instanceof Schema) {
                        EObject parent = eContainer.eContainer();
                        if (parent != null && parent instanceof Catalog) {
                            Catalog c = (Catalog) parent;
                            String name = c.getName();
                            if (!catalogName.contains(name)) {
                                List<Schema> filterSchemas = new ArrayList<Schema>();
                                List<String> schemaName = new ArrayList<String>();
                                List<Schema> schemas = CatalogHelper.getSchemas(c);
                                for (Schema schema : schemas) {
                                    if (schemaFilterList != null) {
                                        if (schemaFilterList.contains(schema.getName())) {
                                            filterSchemas.add(schema);
                                            schemaName.add(schema.getName());
                                        } else if (schema.getOwnedElement() != null
                                                && !schema.getOwnedElement().isEmpty()) {
                                            filterSchemas.add(schema);
                                            schemaName.add(schema.getName());
                                        }
                                    }
                                }
                                // get schema in current connection
                                for (Catalog catalog : catalogList) {
                                    if (catalog.getName().equals(name)) {
                                        boolean added = false;
                                        for (Schema schema : CatalogHelper.getSchemas(catalog)) {
                                            if (!schemaName.contains(schema.getName())) {
                                                filterSchemas.add(schema);
                                                added = true;
                                            }
                                        }
                                        if (added) {
                                            break;
                                        }
                                    }
                                }

                                c.getOwnedElement().clear();
                                CatalogHelper.addSchemas(filterSchemas, c);
                                replaceCatalogs.add(c);
                                catalogName.add(name);
                            }
                        }
                    }
                }
            }
            if (this.isLinked() && !catalogList.isEmpty()) {
                ConnectionHelper.addCatalogs(catalogList, dbConn);
            }
            // if have same schema in current connection,need to fill tables.
            for (Catalog catalog : replaceCatalogs) {
                List<Catalog> list = new ArrayList<Catalog>();
                String name = catalog.getName();
                Catalog c = (Catalog) ConnectionHelper.getPackage(name, dbConn, Catalog.class);
                if (c != null) {
                    list.add(c);
                    ConnectionHelper.removeCatalogs(list, dbConn);
                    ConnectionHelper.addCatalog(catalog, dbConn);
                } else {
                    ConnectionHelper.addCatalog(catalog, dbConn);
                }
            }
        }
    } catch (SQLException e) {
        log.warn("JDBC getCatalogs() method is not available with this driver.", e); //$NON-NLS-1$
    }

    return catalogList;
}

From source file:weave.utils.SQLUtils.java

/**
 * @param conn An existing SQL Connection
 * @return A List of schema names// w  ww  .  j  ava 2 s  .c o m
 * @throws SQLException If the query fails.
 */
public static List<String> getSchemas(Connection conn) throws SQLException {
    List<String> schemas = new Vector<String>();
    ResultSet rs = null;
    try {
        DatabaseMetaData md = conn.getMetaData();

        // MySQL "doesn't support schemas," so use catalogs.
        if (conn.getMetaData().getDatabaseProductName().equalsIgnoreCase(MYSQL)) {
            rs = md.getCatalogs();
            // use column index instead of name because sometimes the names are lower case, sometimes upper.
            while (rs.next())
                schemas.add(rs.getString(1)); // table_catalog
        } else {
            rs = md.getSchemas();
            // use column index instead of name because sometimes the names are lower case, sometimes upper.
            while (rs.next())
                schemas.add(rs.getString(1)); // table_schem
        }

        Collections.sort(schemas, String.CASE_INSENSITIVE_ORDER);
    } finally {
        SQLUtils.cleanup(rs);
    }
    return schemas;
}