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:weave.utils.SQLUtils.java

/**
 * This function is for use with an Oracle connection
 * @param conn An existing Oracle SQL Connection
 * @param schemaName A schema name accessible through the given connection
 * @return A List of sequence names in the given schema
 * @throws SQLException If the query fails.
 *//*from   w  w w  .j  a  v  a2s. c  om*/
private static List<String> getSequences(Connection conn, String schemaName) throws SQLException {
    List<String> sequences = new Vector<String>();
    ResultSet rs = null;
    try {
        DatabaseMetaData md = conn.getMetaData();
        String[] types = new String[] { "SEQUENCE" };

        rs = md.getTables(null, schemaName.toUpperCase(), null, types);

        // use column index instead of name because sometimes the names are lower case, sometimes upper.
        // column indices: 1=sequence_cat,2=sequence_schem,3=sequence_name,4=sequence_type,5=remarks
        while (rs.next())
            sequences.add(rs.getString(3)); // sequence_name

        Collections.sort(sequences, String.CASE_INSENSITIVE_ORDER);
    } finally {
        // close everything in reverse order
        cleanup(rs);
    }
    //System.out.println(sequences);
    return sequences;
}

From source file:org.hsweb.ezorm.rdb.executor.AbstractJdbcSqlExecutor.java

@Override
public boolean tableExists(String tname) throws SQLException {
    Connection connection = getConnection();
    try {/*from  w  w  w  .j  ava  2  s . c  om*/
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet resultSet = metaData.getTables(connection.getCatalog(), null, tname.toUpperCase(), null);
        if (resultSet.next())
            return true;
        else {
            resultSet = metaData.getTables(connection.getCatalog(), null, tname.toLowerCase(), null);
        }
        if (resultSet.next())
            return true;
    } finally {
        releaseConnection(connection);
    }
    return false;
}

From source file:org.apache.syncope.core.util.ContentExporter.java

public void export(final OutputStream os, final String wfTablePrefix)
        throws SAXException, TransformerConfigurationException {

    if (StringUtils.isNotBlank(wfTablePrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(wfTablePrefix);
    }/*w w w  .  j  ava2s .  com*/

    StreamResult streamResult = new StreamResult(os);
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, SyncopeConstants.DEFAULT_ENCODING);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);
        final DatabaseMetaData meta = conn.getMetaData();

        final String schema = dbSchema;

        rs = meta.getTables(null, schema, null, new String[] { "TABLE" });

        final Set<String> tableNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            LOG.debug("Found table {}", tableName);
            if (isTableAllowed(tableName)) {
                tableNames.add(tableName);
            }
        }

        LOG.debug("Tables to be exported {}", tableNames);

        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames)) {
            try {
                doExportTable(handler, conn, tableName, TABLES_TO_BE_FILTERED.get(tableName.toUpperCase()));
            } catch (Exception e) {
                LOG.error("Failure exporting table {}", tableName, e);
            }
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }

        DataSourceUtils.releaseConnection(conn, dataSource);
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                LOG.error("While releasing connection", e);
            }
        }
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}

From source file:com.oltpbenchmark.catalog.Catalog.java

/**
 * Construct the set of Table objects from a given Connection handle
 * @param conn//from  w ww .  j av  a 2s.  c  o  m
 * @return
 * @throws SQLException
 * @see http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html
 */
protected void init() throws SQLException {
    // Load the database's DDL
    this.benchmark.createDatabase(DB_TYPE, this.conn);

    // TableName -> ColumnName -> <FkeyTable, FKeyColumn>
    Map<String, Map<String, Pair<String, String>>> foreignKeys = new HashMap<String, Map<String, Pair<String, String>>>();

    DatabaseMetaData md = conn.getMetaData();
    ResultSet table_rs = md.getTables(null, null, null, new String[] { "TABLE" });
    while (table_rs.next()) {
        if (LOG.isDebugEnabled())
            LOG.debug(SQLUtil.debug(table_rs));
        String internal_table_name = table_rs.getString(3);
        String table_name = origTableNames.get(table_rs.getString(3).toUpperCase());
        assert (table_name != null) : "Unexpected table '" + table_rs.getString(3) + "' from catalog";
        LOG.debug(String.format("ORIG:%s -> CATALOG:%s", internal_table_name, table_name));

        String table_type = table_rs.getString(4);
        if (table_type.equalsIgnoreCase("TABLE") == false)
            continue;
        Table catalog_tbl = new Table(table_name);

        // COLUMNS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving COLUMN information for " + table_name);
        ResultSet col_rs = md.getColumns(null, null, internal_table_name, null);
        while (col_rs.next()) {
            if (LOG.isTraceEnabled())
                LOG.trace(SQLUtil.debug(col_rs));
            String col_name = col_rs.getString(4);
            int col_type = col_rs.getInt(5);
            String col_typename = col_rs.getString(6);
            Integer col_size = col_rs.getInt(7);
            String col_defaultValue = col_rs.getString(13);
            boolean col_nullable = col_rs.getString(18).equalsIgnoreCase("YES");
            boolean col_autoinc = false; // FIXME col_rs.getString(22).toUpperCase().equals("YES");

            Column catalog_col = new Column(catalog_tbl, col_name, col_type, col_typename, col_size);
            catalog_col.setDefaultValue(col_defaultValue);
            catalog_col.setAutoincrement(col_autoinc);
            catalog_col.setNullable(col_nullable);
            // FIXME col_catalog.setSigned();

            if (LOG.isDebugEnabled())
                LOG.debug(
                        String.format("Adding %s.%s [%s / %d]", table_name, col_name, col_typename, col_type));
            catalog_tbl.addColumn(catalog_col);
        } // WHILE
        col_rs.close();

        // PRIMARY KEYS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving PRIMARY KEY information for " + table_name);
        ResultSet pkey_rs = md.getPrimaryKeys(null, null, internal_table_name);
        SortedMap<Integer, String> pkey_cols = new TreeMap<Integer, String>();
        while (pkey_rs.next()) {
            String col_name = pkey_rs.getString(4);
            assert (catalog_tbl.getColumnByName(col_name) != null) : String
                    .format("Unexpected primary key column %s.%s", table_name, col_name);
            int col_idx = pkey_rs.getShort(5);
            // HACK: SQLite doesn't return the KEY_SEQ, so if we get back
            //       a zero for this value, then we'll just length of the pkey_cols map
            if (col_idx == 0)
                col_idx = pkey_cols.size();
            LOG.debug(String.format("PKEY[%02d]: %s.%s", col_idx, table_name, col_name));
            assert (pkey_cols.containsKey(col_idx) == false);
            pkey_cols.put(col_idx, col_name);
        } // WHILE
        pkey_rs.close();
        catalog_tbl.setPrimaryKeyColumns(pkey_cols.values());

        // INDEXES
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving INDEX information for " + table_name);
        ResultSet idx_rs = md.getIndexInfo(null, null, internal_table_name, false, false);
        while (idx_rs.next()) {
            if (LOG.isDebugEnabled())
                LOG.debug(SQLUtil.debug(idx_rs));
            boolean idx_unique = (idx_rs.getBoolean(4) == false);
            String idx_name = idx_rs.getString(6);
            int idx_type = idx_rs.getShort(7);
            int idx_col_pos = idx_rs.getInt(8) - 1;
            String idx_col_name = idx_rs.getString(9);
            String sort = idx_rs.getString(10);
            SortDirectionType idx_direction;
            if (sort != null) {
                idx_direction = sort.equalsIgnoreCase("A") ? SortDirectionType.ASC : SortDirectionType.DESC;
            } else
                idx_direction = null;

            Index catalog_idx = catalog_tbl.getIndex(idx_name);
            if (catalog_idx == null) {
                catalog_idx = new Index(catalog_tbl, idx_name, idx_type, idx_unique);
                catalog_tbl.addIndex(catalog_idx);
            }
            assert (catalog_idx != null);
            catalog_idx.addColumn(idx_col_name, idx_direction, idx_col_pos);
        } // WHILE
        idx_rs.close();

        // FOREIGN KEYS
        if (LOG.isDebugEnabled())
            LOG.debug("Retrieving FOREIGN KEY information for " + table_name);
        ResultSet fk_rs = md.getImportedKeys(null, null, internal_table_name);
        foreignKeys.put(table_name, new HashMap<String, Pair<String, String>>());
        while (fk_rs.next()) {
            if (LOG.isDebugEnabled())
                LOG.debug(table_name + " => " + SQLUtil.debug(fk_rs));
            assert (fk_rs.getString(7).equalsIgnoreCase(table_name));

            String colName = fk_rs.getString(8);
            String fk_tableName = origTableNames.get(fk_rs.getString(3).toUpperCase());
            String fk_colName = fk_rs.getString(4);

            foreignKeys.get(table_name).put(colName, Pair.of(fk_tableName, fk_colName));
        } // WHILE
        fk_rs.close();

        tables.put(table_name, catalog_tbl);
    } // WHILE
    table_rs.close();

    // FOREIGN KEYS
    if (LOG.isDebugEnabled())
        LOG.debug("Foreign Key Mappings:\n" + StringUtil.formatMaps(foreignKeys));
    for (Table catalog_tbl : tables.values()) {
        Map<String, Pair<String, String>> fk = foreignKeys.get(catalog_tbl.getName());
        for (Entry<String, Pair<String, String>> e : fk.entrySet()) {
            String colName = e.getKey();
            Column catalog_col = catalog_tbl.getColumnByName(colName);
            assert (catalog_col != null);

            Pair<String, String> fkey = e.getValue();
            assert (fkey != null);

            Table fkey_tbl = tables.get(fkey.first);
            if (fkey_tbl == null) {
                throw new RuntimeException("Unexpected foreign key parent table " + fkey);
            }
            Column fkey_col = fkey_tbl.getColumnByName(fkey.second);
            if (fkey_col == null) {
                throw new RuntimeException("Unexpected foreign key parent column " + fkey);
            }

            if (LOG.isDebugEnabled())
                LOG.debug(catalog_col.fullName() + " -> " + fkey_col.fullName());
            catalog_col.setForeignKey(fkey_col);
        } // FOR
    } // FOR

    return;
}

From source file:broadwick.data.readers.DataFileReader.java

/**
 * Execute a command to create a table./*ww w . ja v  a 2s.  c  o m*/
 * @param tableName          the name of the table to be created.
 * @param createTableCommand the command to create the table.
 * @param connection         the database connection to use to create the table.
 * @throws SQLException if a SQL error has been encountered.
 */
protected final void createTable(final String tableName, final String createTableCommand,
        final Connection connection) throws SQLException {

    final DatabaseMetaData dbm = connection.getMetaData();

    // First check if the table already exists, some databases do not support
    // CREATE TABLE ??? IF NOT EXISTS
    // so we have to look at the database schema
    try (ResultSet resultSet = dbm.getTables(null, null, "%", null)) {
        boolean tableExists = false;
        while (resultSet.next()) {
            if (tableName.equalsIgnoreCase(resultSet.getString("TABLE_NAME"))) {
                log.debug("Table {} already exists, ignoring", tableName);
                tableExists = true;
            }
        }

        if (!tableExists) {
            try (Statement stmt = connection.createStatement()) {
                final String[] commands = createTableCommand.split(";");
                for (int i = 0; i < commands.length; i++) {
                    log.trace("Creating table {}", commands[i]);
                    stmt.execute(commands[i]);
                }
            } catch (SQLException sqle) {
                connection.rollback();
                log.error("Error while creating the table '{}'. {}", createTableCommand,
                        Throwables.getStackTraceAsString(sqle));
                throw sqle;
            }
        }

        //        } catch (Exception e) {
        //            log.error("Could not create database {}", Throwables.getStackTraceAsString(e));
    }

    connection.commit();
}

From source file:yelpproject.DatabaseConnection.java

public void createTable() throws SQLException {

    Statement stmt1 = null;/*from   ww w .jav a2s.c o m*/

    String sql1 = "create table " + "REVIEW(votes varchar(100),user_id varchar(30),review_id varchar(30) "
            + "PRIMARY KEY, stars number(10), type varchar(10), text clob, "
            + "business_id varchar(30),date_review DATE)";

    String sql2 = "create table "
            + "CHECKIN(business_id VARCHAR(1000), type VARCHAR(100), checkin_day NUMBER(10), checkin_hour NUMBER(10), "
            + "checkin_value NUMBER(10))";

    String sql3 = "create table " + "YELP_USER "
            + "(yelping_since DATE,votes VARCHAR(100),name VARCHAR(50), review_count NUMBER(20),"
            + "user_id VARCHAR(30) PRIMARY KEY, friends NUMBER(10),"
            + "fans NUMBER(20),average_stars NUMBER(20),type VARCHAR(10),compliments VARCHAR(1000),elite VARCHAR(100))";

    String sql5 = "create table BUSINESS " + "(business_id VARCHAR(1000) PRIMARY KEY,"
            + "categories VARCHAR(3999),review_count NUMBER(20)," + "name VARCHAR(100),stars VARCHAR(20))";

    String sql6 = "create table " + "BUSINESS_CATEGORY " + "(business_category VARCHAR(100))";

    String sql7 = "create table BUSINESS_SUBCATEGORY" + "(business_subcategory VARCHAR(200))";

    try {
        connection = getDBConnection();

        DatabaseMetaData dbm1 = connection.getMetaData();
        ResultSet rs1 = dbm1.getTables(null, null, "REVIEW", null);
        if (rs1.next()) {
            System.out.println("Table already exists. Not creating.");
            //stmt = connection.createStatement();
            //stmt.executeUpdate(sql2);
        } else {
            System.out.println("Table created REVIEW");
            stmt1 = connection.createStatement();
            stmt1.executeUpdate(sql1);
        }

        DatabaseMetaData dbm2 = connection.getMetaData();
        ResultSet rs2 = dbm2.getTables(null, null, "CHECKIN", null);
        if (rs2.next()) {
            System.out.println("Table already exists. Not creating.");
            //stmt = connection.createStatement();
            //stmt.executeUpdate(sql2);
        } else {
            System.out.println("Table created. CHECKIN");
            stmt1 = connection.createStatement();
            stmt1.executeUpdate(sql2);
        }

        DatabaseMetaData dbm3 = connection.getMetaData();
        ResultSet rs3 = dbm3.getTables(null, null, "YELP_USER", null);
        if (rs3.next()) {
            System.out.println("Table already exists. Not creating.");
            //stmt = connection.createStatement();
            //stmt.executeUpdate(sql2);
        } else {
            System.out.println("Table created." + " Yelp user");
            stmt1 = connection.createStatement();
            stmt1.executeUpdate(sql3);
        }

        DatabaseMetaData dbm5 = connection.getMetaData();
        ResultSet rs5 = dbm5.getTables(null, null, "BUSINESS", null);
        if (rs5.next()) {
            System.out.println("Table already exists. Not creating.");
            //stmt = connection.createStatement();
            //stmt.executeUpdate(sql2);
        } else {
            System.out.println("Table created. BUSINESS");
            stmt1 = connection.createStatement();
            stmt1.executeUpdate(sql5);
        }

        DatabaseMetaData dbm6 = connection.getMetaData();
        ResultSet rs6 = dbm6.getTables(null, null, "BUSINESS_CATEGORY", null);
        if (rs6.next()) {
            System.out.println("Table already exists. Not creating.");
            //stmt = connection.createStatement();
            //stmt.executeUpdate(sql2);
        } else {
            System.out.println("Table created. BUSINESS_CATEGORY");
            stmt1 = connection.createStatement();
            stmt1.executeUpdate(sql6);
        }

        DatabaseMetaData dbm7 = connection.getMetaData();
        ResultSet rs7 = dbm7.getTables(null, null, "BUSINESS_SUBCATEGORY", null);
        if (rs7.next()) {
            System.out.println("Table already exists. Not creating.");
            //stmt = connection.createStatement();
            //stmt.executeUpdate(sql2);
        } else {
            System.out.println("Table created. BUSINESS_SUBCATEGORY");
            stmt1 = connection.createStatement();
            stmt1.executeUpdate(sql7);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stmt1 != null) {
            stmt1.close();
        }
    }
}

From source file:com.mmnaseri.dragonfly.dialect.impl.Mysql5Dialect.java

@Override
public <E> boolean hasTable(DatabaseMetaData databaseMetadata, TableMetadata<E> tableMetadata) {
    try {// ww w.  ja v a 2  s  .  co  m
        String schema = tableMetadata.getSchema() != null && !tableMetadata.getSchema().isEmpty()
                ? tableMetadata.getSchema()
                : databaseMetadata.getConnection().getCatalog();
        return databaseMetadata.getTables(schema, null, tableMetadata.getName(), new String[] { "TABLE" })
                .next();
    } catch (SQLException e) {
        throw new MetadataCollectionError("Failed to recognize database metadata", e);
    }
}

From source file:databaseadapter.GenerateMojo.java

protected Collection<Table> collectTables() throws MojoExecutionException {
    ResultSet rstables = null;/*from   ww  w. j  a v  a 2 s .c  om*/
    try {
        List<Table> tables = new LinkedList<Table>();
        DatabaseMetaData metaData = connection.getMetaData();
        rstables = metaData.getTables(null, schemaPattern, "%", new String[] { "TABLE" });
        while (rstables.next()) {
            String schema = rstables.getString("TABLE_SCHEM");
            String table = rstables.getString("TABLE_NAME");
            String type = rstables.getString("TABLE_TYPE");
            String remarks = rstables.getString("REMARKS");
            getLog().debug("... found table " + schema + "." + table + " (" + type + ")...");
            if (isToInclude(table)) {
                if (!isToExclude(table)) {
                    getLog().debug("... processing...");
                    Table t = new Table(table, remarks);
                    tables.add(t);

                } else {
                    getLog().debug("... skipping due to 'excludes' pattern(s)");
                }
            } else {
                getLog().debug("... skipping due to 'includes' pattern(s)");
            }
        }

        getLog().info("... found to process " + tables.size() + " tables: " + tables);
        return tables;
    } catch (SQLException e) {
        throw new MojoExecutionException("Unable to generate database adapter due to a '"
                + e.getClass().getName() + "' with message '" + e.getMessage() + "'", e);
    } finally {
        if (rstables != null) {
            try {
                rstables.close();
            } catch (SQLException ignore) {
            }
        }
    }
}

From source file:org.kuali.rice.test.ClearDatabaseLifecycle.java

protected void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource) {
    Assert.assertNotNull("DataSource could not be located.", dataSource);
    try {//  w  ww  . ja  v  a  2 s  .  c o  m
        StopWatch s = new StopWatch();
        s.start();
        new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
            public Object doInTransaction(final TransactionStatus status) {
                verifyTestEnvironment(dataSource);
                return new JdbcTemplate(dataSource).execute(new StatementCallback() {
                    public Object doInStatement(Statement statement) throws SQLException {
                        String schemaName = statement.getConnection().getMetaData().getUserName().toUpperCase();
                        LOG.info("Clearing tables for schema " + schemaName);
                        if (StringUtils.isBlank(schemaName)) {
                            Assert.fail("Empty schema name given");
                        }
                        final List<String> reEnableConstraints = new ArrayList<String>();
                        DatabaseMetaData metaData = statement.getConnection().getMetaData();
                        Map<String, List<String[]>> exportedKeys = indexExportedKeys(metaData, schemaName);
                        final ResultSet resultSet = metaData.getTables(null, schemaName, null,
                                new String[] { "TABLE" });
                        final StringBuilder logStatements = new StringBuilder();
                        while (resultSet.next()) {
                            String tableName = resultSet.getString("TABLE_NAME");
                            if (shouldTableBeCleared(tableName)) {
                                if (!isUsingDerby(metaData) && isUsingOracle(metaData)) {
                                    List<String[]> exportedKeyNames = exportedKeys.get(tableName);
                                    if (exportedKeyNames != null) {
                                        for (String[] exportedKeyName : exportedKeyNames) {
                                            final String fkName = exportedKeyName[0];
                                            final String fkTableName = exportedKeyName[1];
                                            final String disableConstraint = "ALTER TABLE " + fkTableName
                                                    + " DISABLE CONSTRAINT " + fkName;
                                            logStatements.append("Disabling constraints using statement ->"
                                                    + disableConstraint + "<-\n");
                                            statement.addBatch(disableConstraint);
                                            reEnableConstraints.add("ALTER TABLE " + fkTableName
                                                    + " ENABLE CONSTRAINT " + fkName);
                                        }
                                    }
                                } else if (isUsingMySQL(metaData)) {
                                    statement.addBatch("SET FOREIGN_KEY_CHECKS = 0");
                                }
                                String deleteStatement = "DELETE FROM " + tableName;
                                logStatements.append(
                                        "Clearing contents using statement ->" + deleteStatement + "<-\n");
                                statement.addBatch(deleteStatement);
                            }
                        }
                        for (final String constraint : reEnableConstraints) {
                            logStatements
                                    .append("Enabling constraints using statement ->" + constraint + "<-\n");
                            statement.addBatch(constraint);
                        }
                        if (isUsingMySQL(metaData)) {
                            statement.addBatch("SET FOREIGN_KEY_CHECKS = 1");
                        }
                        LOG.info(logStatements);

                        int[] results = statement.executeBatch();
                        for (int index = 0; index < results.length; index++) {
                            if (results[index] == Statement.EXECUTE_FAILED) {
                                Assert.fail("Execution of database clear statement failed.");
                            }

                        }
                        resultSet.close();
                        LOG.info("Tables successfully cleared for schema " + schemaName);
                        return null;
                    }
                });
            }
        });
        s.stop();
        LOG.info("Time to clear tables: " + DurationFormatUtils.formatDurationHMS(s.getTime()));
    } catch (Exception e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java

@Override
public void export(final String domain, final OutputStream os, final String uwfPrefix, final String gwfPrefix,
        final String awfPrefix) throws SAXException, TransformerConfigurationException {

    if (StringUtils.isNotBlank(uwfPrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(uwfPrefix);
    }//www. j a v a2  s.c o m
    if (StringUtils.isNotBlank(gwfPrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(gwfPrefix);
    }
    if (StringUtils.isNotBlank(awfPrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(awfPrefix);
    }

    StreamResult streamResult = new StreamResult(os);
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();
    transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    DataSource dataSource = domainsHolder.getDomains().get(domain);
    if (dataSource == null) {
        throw new IllegalArgumentException("Could not find DataSource for domain " + domain);
    }

    String dbSchema = ApplicationContextProvider.getBeanFactory().getBean(domain + "DatabaseSchema",
            String.class);

    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);
        final DatabaseMetaData meta = conn.getMetaData();

        rs = meta.getTables(null, StringUtils.isBlank(dbSchema) ? null : dbSchema, null,
                new String[] { "TABLE" });

        final Set<String> tableNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            LOG.debug("Found table {}", tableName);
            if (isTableAllowed(tableName)) {
                tableNames.add(tableName);
            }
        }

        LOG.debug("Tables to be exported {}", tableNames);

        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(dbSchema, conn, tableNames)) {
            try {
                doExportTable(handler, dbSchema, conn, tableName,
                        TABLES_TO_BE_FILTERED.get(tableName.toUpperCase()));
            } catch (Exception e) {
                LOG.error("Failure exporting table {}", tableName, e);
            }
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }

        DataSourceUtils.releaseConnection(conn, dataSource);
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                LOG.error("While releasing connection", e);
            }
        }
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}