Example usage for java.sql DatabaseMetaData getImportedKeys

List of usage examples for java.sql DatabaseMetaData getImportedKeys

Introduction

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

Prototype

ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException;

Source Link

Document

Retrieves a description of the primary key columns that are referenced by the given table's foreign key columns (the primary keys imported by a table).

Usage

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

private List<String> sortByForeignKeys(final Connection conn, final Set<String> tableNames)
        throws SQLException {

    Set<MultiParentNode<String>> roots = new HashSet<MultiParentNode<String>>();

    final DatabaseMetaData meta = conn.getMetaData();

    final Map<String, MultiParentNode<String>> exploited = new TreeMap<String, MultiParentNode<String>>(
            String.CASE_INSENSITIVE_ORDER);

    final Set<String> pkTableNames = new HashSet<String>();

    for (String tableName : tableNames) {
        MultiParentNode<String> node = exploited.get(tableName);
        if (node == null) {
            node = new MultiParentNode<String>(tableName);
            roots.add(node);//from ww  w. j  a va 2  s.c  o m
            exploited.put(tableName, node);
        }

        pkTableNames.clear();

        ResultSet rs = null;
        try {
            rs = meta.getImportedKeys(conn.getCatalog(), dbSchema, tableName);

            // this is to avoid repetition
            while (rs.next()) {
                pkTableNames.add(rs.getString("PKTABLE_NAME"));
            }
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    LOG.error("While closing tables result set", e);
                }
            }
        }

        for (String pkTableName : pkTableNames) {
            if (!tableName.equalsIgnoreCase(pkTableName)) {
                MultiParentNode<String> pkNode = exploited.get(pkTableName);
                if (pkNode == null) {
                    pkNode = new MultiParentNode<String>(pkTableName);
                    roots.add(pkNode);
                    exploited.put(pkTableName, pkNode);
                }

                pkNode.addChild(node);

                if (roots.contains(node)) {
                    roots.remove(node);
                }
            }
        }
    }

    final List<String> sortedTableNames = new ArrayList<String>(tableNames.size());
    MultiParentNodeOp.traverseTree(roots, sortedTableNames);

    // remove from sortedTableNames any table possibly added during lookup 
    // but matching some item in this.tablePrefixesToBeExcluded
    sortedTableNames.retainAll(tableNames);

    LOG.debug("Tables after retainAll {}", sortedTableNames);

    Collections.reverse(sortedTableNames);

    return sortedTableNames;
}

From source file:org.apache.torque.generator.source.jdbc.JdbcMetadataSource.java

/**
 * Retrieves a list of foreign key columns for a given table.
 *
 * @param dbMeta JDBC metadata.//from  www  .  ja  v  a2  s .co  m
 * @param tableName Table from which to retrieve FK information.
 * @return A list of foreign keys in <code>tableName</code>.
 * @throws SQLException
 */
Collection<ForeignKeyMetadata> getForeignKeys(DatabaseMetaData dbMeta, String tableName, String schemaName)
        throws SQLException {
    Map<String, ForeignKeyMetadata> foreignKeys = new HashMap<String, ForeignKeyMetadata>();
    ResultSet resultSet = null;
    try {
        resultSet = dbMeta.getImportedKeys(null, schemaName, tableName);
        while (resultSet.next()) {
            String refTableName = resultSet.getString(TABLE_NAME_POS_IN_FOREIGN_KEY_METADATA);
            String fkName = resultSet.getString(FOREIGN_KEY_NAME_POS_IN_FOREIGN_KEY_METADATA);
            // if FK has no name - make it up (use tablename instead)
            if (fkName == null) {
                fkName = refTableName;
            }
            ForeignKeyMetadata fk = foreignKeys.get(fkName);
            if (fk == null) {
                fk = new ForeignKeyMetadata();
                fk.setReferencedTable(refTableName);
                fk.setForeignKeyName(fkName);
                foreignKeys.put(fkName, fk);
            }
            fk.getLocalColumns().add(resultSet.getString(LOCAL_COLUMN_NAME_POS_IN_FOREIGN_KEY_METADATA));
            fk.getForeignColumns().add(resultSet.getString(FOREIGN_COLUMN_NAME_POS_IN_FOREIGN_KEY_METADATA));
        }
    } catch (SQLException e) {
        // this seems to be happening in some db drivers (sybase)
        // when retrieving foreign keys from views.
        log.warn("WARN: Could not read foreign keys for Table " + tableName + " : " + e.getMessage());
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
    return foreignKeys.values();
}

From source file:org.batoo.jpa.core.jdbc.adapter.JdbcTable.java

private void readForeignKeys(DatabaseMetaData dbMetadata, ResultSet metadata) throws SQLException {
    ResultSet rs = null;/*from w w w .  ja  v  a2  s  . c  o m*/
    try {
        rs = dbMetadata.getImportedKeys(this.catalog, this.schema, this.name);
        while (rs.next()) {
            final String name = rs.getString(JdbcTable.FK_NAME);
            JdbcForeignKey foreignKey = this.getForeignKey(name);
            if (foreignKey == null) {
                foreignKey = new JdbcForeignKey(rs);
                this.foreignKeys.put(rs.getString(JdbcTable.FK_NAME).toUpperCase(), foreignKey);
            }

            foreignKey.addColumn(rs);
        }
    } finally {
        DbUtils.closeQuietly(rs);
    }
}

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

/**
 * Returns the columns of the specified database object.
 *
 * @param catalog the table catalog name
 * @param schema the table schema name/*from   w ww.j a  v a 2s. c  o m*/
 * @param table the database object name
 * @return the columns
 */
public List<DatabaseColumn> getColumns(String catalog, String schema, String table) throws DataSourceException {

    ResultSet rs = null;

    List<DatabaseColumn> columns = new ArrayList<DatabaseColumn>();

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

        // retrieve the base column info
        rs = dmd.getColumns(_catalog, _schema, table, null);

        /*
        if (Log.isDebugEnabled()) {
                
        Log.debug("Meta data on columns for table - " + table);
                
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        for (int i = 0; i < columnCount; i++) {
                    
            Log.debug("Column: [ " + (i + 1) + " ] " + metaData.getColumnName(i + 1));                    
        }
        }
        */

        while (rs.next()) {

            DefaultDatabaseColumn column = new DefaultDatabaseColumn();
            column.setCatalogName(catalog);
            column.setSchemaName(schema);
            column.setName(rs.getString(4));
            column.setTypeInt(rs.getInt(5));
            column.setTypeName(rs.getString(6));
            column.setColumnSize(rs.getInt(7));
            column.setColumnScale(rs.getInt(9));
            column.setRequired(rs.getInt(11) == DatabaseMetaData.columnNoNulls);
            column.setRemarks(rs.getString(12));
            column.setDefaultValue(rs.getString(13));
            columns.add(column);
        }
        releaseResources(rs);

        int columnCount = columns.size();
        if (columnCount > 0) {

            // check for primary keys
            rs = dmd.getPrimaryKeys(_catalog, _schema, table);
            while (rs.next()) {

                String pkColumn = rs.getString(4);

                // find the pk column in the previous list
                for (int i = 0; i < columnCount; i++) {

                    DatabaseColumn column = columns.get(i);
                    String columnName = column.getName();

                    if (columnName.equalsIgnoreCase(pkColumn)) {
                        ((DefaultDatabaseColumn) column).setPrimaryKey(true);
                        break;
                    }

                }

            }
            releaseResources(rs);

            // check for foreign keys
            rs = dmd.getImportedKeys(_catalog, _schema, table);
            while (rs.next()) {
                String fkColumn = rs.getString(8);

                // find the fk column in the previous list
                for (int i = 0; i < columnCount; i++) {
                    DatabaseColumn column = columns.get(i);
                    String columnName = column.getName();
                    if (columnName.equalsIgnoreCase(fkColumn)) {
                        ((DefaultDatabaseColumn) column).setForeignKey(true);
                        break;
                    }
                }

            }

        }

        return columns;

    } catch (SQLException e) {

        if (Log.isDebugEnabled()) {

            Log.error("Error retrieving column data for table " + table + " using connection "
                    + getDatabaseConnection(), e);
        }

        return columns;

        //            throw new DataSourceException(e);

    } finally {

        releaseResources(rs);
    }

}

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

/**
 * Returns the columns of this table./*w w  w . j a v a  2 s.  c  o  m*/
 *
 * @return the columns
 */
public List<DatabaseColumn> getColumns() throws DataSourceException {

    if (!isMarkedForReload() && columns != null) {

        return columns;
    }

    // otherwise cleanup existing references
    if (columns != null) {

        columns.clear();
        columns = null;
    }

    DatabaseHost host = getHost();
    if (host != null) {

        ResultSet rs = null;
        try {

            List<DatabaseColumn> _columns = host.getColumns(getCatalogName(), getSchemaName(), getName());

            if (_columns != null) {

                columns = databaseColumnListWithSize(_columns.size());
                for (DatabaseColumn i : _columns) {

                    columns.add(new DatabaseTableColumn(this, i));
                }

                // reload and define the constraints
                String _catalog = host.getCatalogNameForQueries(getCatalogName());
                String _schema = host.getSchemaNameForQueries(getSchemaName());
                DatabaseMetaData dmd = host.getDatabaseMetaData();

                rs = dmd.getPrimaryKeys(_catalog, _schema, getName());
                while (rs.next()) {

                    String pkColumn = rs.getString(4);
                    for (DatabaseColumn i : columns) {

                        if (i.getName().equalsIgnoreCase(pkColumn)) {

                            DatabaseTableColumn column = (DatabaseTableColumn) i;
                            TableColumnConstraint constraint = new TableColumnConstraint(column,
                                    ColumnConstraint.PRIMARY_KEY);

                            constraint.setName(rs.getString(6));
                            constraint.setMetaData(resultSetRowToMap(rs));
                            column.addConstraint(constraint);
                            break;

                        }
                    }
                }
                rs.close();

                try {

                    // TODO: XXX

                    // sapdb amd maxdb dump on imported/exported keys
                    // surround with try/catch hack to get at least a columns list

                    rs = dmd.getImportedKeys(_catalog, _schema, getName());
                    while (rs.next()) {

                        String fkColumn = rs.getString(8);

                        for (DatabaseColumn i : columns) {

                            if (i.getName().equalsIgnoreCase(fkColumn)) {

                                DatabaseTableColumn column = (DatabaseTableColumn) i;

                                TableColumnConstraint constraint = new TableColumnConstraint(column,
                                        ColumnConstraint.FOREIGN_KEY);
                                constraint.setReferencedCatalog(rs.getString(1));
                                constraint.setReferencedSchema(rs.getString(2));
                                constraint.setReferencedTable(rs.getString(3));
                                constraint.setReferencedColumn(rs.getString(4));
                                constraint.setUpdateRule(rs.getShort(10));
                                constraint.setDeleteRule(rs.getShort(11));
                                constraint.setName(rs.getString(12));
                                constraint.setDeferrability(rs.getShort(14));
                                constraint.setMetaData(resultSetRowToMap(rs));
                                column.addConstraint(constraint);
                                break;

                            }
                        }
                    }

                } catch (SQLException e) {
                }
            }

        } catch (DataSourceException e) {

            // catch and re-throw here to create
            // an empty column list so we don't
            // keep hitting the same error
            columns = databaseColumnListWithSize(0);
            throw e;

        } catch (SQLException e) {

            // catch and re-throw here to create
            // an empty column list so we don't
            // keep hitting the same error
            columns = databaseColumnListWithSize(0);
            throw new DataSourceException(e);

        } finally {

            releaseResources(rs);
            setMarkedForReload(false);
        }

    }
    return columns;
}

From source file:org.kuali.core.db.torque.KualiTorqueJDBCTransformTask.java

/**
 * Retrieves a list of foreign key columns for a given table.
 *
 * @param dbMeta JDBC metadata./*www.  ja va 2s . c o  m*/
 * @param tableName Table from which to retrieve FK information.
 * @return A list of foreign keys in <code>tableName</code>.
 * @throws SQLException
 */
public Map<String, Object[]> getForeignKeys(DatabaseMetaData dbMeta, String tableName) throws SQLException {
    TreeMap<String, Object[]> fks = new TreeMap<String, Object[]>();
    ResultSet foreignKeys = null;
    try {
        foreignKeys = dbMeta.getImportedKeys(null, dbSchema, tableName);
        while (foreignKeys.next()) {
            String refTableName = foreignKeys.getString(3);
            String fkName = foreignKeys.getString(12);
            int deleteRule = foreignKeys.getInt(11);
            String onDelete = "none";
            if (deleteRule == DatabaseMetaData.importedKeyCascade) {
                onDelete = "cascade";
            } else if (deleteRule == DatabaseMetaData.importedKeyRestrict) {
                onDelete = "restrict";
            } else if (deleteRule == DatabaseMetaData.importedKeySetNull) {
                onDelete = "setnull";
            }
            // if FK has no name - make it up (use tablename instead)
            if (fkName == null) {
                fkName = refTableName;
            }
            Object[] fk = (Object[]) fks.get(fkName);
            List<String[]> refs;
            if (fk == null) {
                fk = new Object[3];
                fk[0] = refTableName; //referenced table name
                refs = new ArrayList<String[]>();
                fk[1] = refs;
                fks.put(fkName, fk);
                fk[2] = onDelete;
            } else {
                refs = (ArrayList<String[]>) fk[1];
            }
            String[] ref = new String[2];
            ref[0] = foreignKeys.getString(8); //local column
            ref[1] = foreignKeys.getString(4); //foreign column
            refs.add(ref);
        }
    } catch (SQLException e) {
        // this seems to be happening in some db drivers (sybase)
        // when retrieving foreign keys from views.
        log("WARN: Could not read foreign keys for Table " + tableName + " : " + e.getMessage(),
                Project.MSG_WARN);
    } finally {
        if (foreignKeys != null) {
            foreignKeys.close();
        }
    }
    return fks;
}

From source file:org.kuali.test.ui.components.sqlquerypanel.DatabasePanel.java

private void loadTableRelationships(DatabaseConnection dbconn, DatabaseMetaData dmd, TableData td,
        int currentDepth, SqlQueryNode parentNode) throws Exception {
    ResultSet res = null;//w ww.  ja va 2s.com

    try {
        td.setTreeNode(parentNode);
        String ikdkey = (td.getSchema() + "." + td.getName());

        List<ImportedKeyData> ikdlist = importedKeysData.get(ikdkey);

        if (ikdlist == null) {
            ikdlist = new ArrayList<ImportedKeyData>();
            res = dmd.getImportedKeys(null, td.getSchema(), td.getName());

            while (res.next()) {
                ImportedKeyData ikd = new ImportedKeyData(res);

                Table t = additionalDbInfo.get(ikd.getPkTable());
                if ((t != null) || !dbconn.getConfiguredTablesOnly()) {
                    ikdlist.add(ikd);
                }
            }

            importedKeysData.put(ikdkey, ikdlist);
        }

        currentDepth++;

        Map<String, TableData> map = new HashMap<String, TableData>();

        for (ImportedKeyData ikd : ikdlist) {
            String schema = ikd.getPkSchema();
            String tname = ikd.getPkTable();

            String pkcname = ikd.getPkColumn();
            String fkcname = ikd.getFkColumn();
            String fkname = ikd.getFkName();

            String key = fkname;

            if (StringUtils.isBlank(key)) {
                key = (td.getName() + "-" + tname);
            }

            TableData tdata = map.get(key);

            if (tdata == null) {
                Table t = additionalDbInfo.get(tname);

                if ((t != null) && dbconn.getConfiguredTablesOnly()) {
                    map.put(key, tdata = new TableData(schema, tname, t.getDisplayName()));
                } else {
                    map.put(key, tdata = new TableData(schema, tname, tname));
                }

                tdata.setForeignKeyName(fkname);
            }

            tdata.getLinkColumns().add(new String[] { fkcname, pkcname });
        }

        CustomForeignKey[] customForeignKeys = getCustomForeignKeys(td);

        if (customForeignKeys != null) {
            for (CustomForeignKey cfk : customForeignKeys) {
                TableData tdata = new TableData(td.getSchema(), cfk.getPrimaryTableName(),
                        getTableDisplayName(cfk.getPrimaryTableName()));
                tdata.setForeignKeyName(cfk.getName());

                map.put(cfk.getPrimaryTableName() + "-" + cfk.getName(), tdata);

                td.getRelatedTables().add(tdata);
                if (cfk.getForeignKeyColumnPairArray() != null) {
                    for (ForeignKeyColumnPair fk : cfk.getForeignKeyColumnPairArray()) {
                        tdata.getLinkColumns()
                                .add(new String[] { fk.getForeignColumn(), fk.getPrimaryColumn() });
                    }
                }
            }
        }

        List<TableData> l = new ArrayList(map.values());

        Collections.sort(l);

        for (TableData tdata : l) {
            td.getRelatedTables().add(tdata);
            SqlQueryNode curnode = new SqlQueryNode(getMainframe().getConfiguration(), tdata);

            parentNode.add(curnode);

            if (currentDepth < Constants.MAX_TABLE_RELATIONSHIP_DEPTH) {
                // only move down the tree if this is not a circular relationship
                if (!isCircularReference(curnode)) {
                    loadTableRelationships(dbconn, dmd, tdata, currentDepth, curnode);
                } else {
                    tdata.setTreeNode(curnode);
                    loadTableColumns(dbconn, dmd, curnode);
                }
            }
        }

        loadTableColumns(dbconn, dmd, parentNode);
    }

    finally {
        Utils.closeDatabaseResources(null, null, res);
    }
}

From source file:org.lockss.db.DbMigrator.java

/**
 * Extracts the metadata of the tables of a database schema.
 * /*ww  w. ja va2s .  c o m*/
 * @param conn
 *          A Connection with the database connection to be used.
 * @param schema
 *          A String with the database schema.
 * 
 * @return a Map<String, DbTable> with the metadata of the tables.
 * @throws DbMigratorException
 *           if there are problems extracting the metadata.
 */
private Map<String, DbTable> extractDbMetadata(Connection conn, String schema) throws DbMigratorException {
    final String DEBUG_HEADER = "populateDbMetadata(): ";
    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "schema = " + schema);

    if (conn == null) {
        throw new DbMigratorException("Null connection");
    }

    Map<String, DbTable> tableMap = new HashMap<String, DbTable>();

    ResultSet tableResultSet = null;
    String tableName = null;
    ResultSet columnResultSet = null;
    ResultSet pkResultSet = null;
    ResultSet fkResultSet = null;

    try {
        DatabaseMetaData metadata = DbManagerSql.getMetadata(conn);

        // Get the database schema table data.
        tableResultSet = DbManagerSql.getStandardTables(conn, null, schema, null);

        // Loop through all the schema tables.
        while (tableResultSet.next()) {
            tableName = tableResultSet.getString("TABLE_NAME");
            log.debug2(DEBUG_HEADER + "TABLE_NAME = " + tableName);

            String tableType = tableResultSet.getString("TABLE_TYPE");
            log.debug2(DEBUG_HEADER + "TABLE_TYPE = " + tableType);
            log.debug2(DEBUG_HEADER + "");

            // Check that this is not a view, etc.
            if ("TABLE".equals(tableType)) {
                // Yes: Get the table column metadata.
                DbTable table = new DbTable(tableName.toLowerCase());
                DbRow row = new DbRow(tableName.toLowerCase());
                table.setRow(row);
                List<DbColumn> columns = row.getColumns();
                columnResultSet = metadata.getColumns(null, schema, tableName, null);

                // Loop through each table column.
                while (columnResultSet.next()) {
                    String columnName = columnResultSet.getString("COLUMN_NAME").toLowerCase();
                    log.debug2(DEBUG_HEADER + "columnName = '" + columnName + "'.");

                    int columnType = columnResultSet.getInt("DATA_TYPE");
                    log.debug2(DEBUG_HEADER + "columnType = '" + columnType + "'.");

                    int position = columnResultSet.getInt("ORDINAL_POSITION");
                    log.debug2(DEBUG_HEADER + "position = '" + position + "'.");

                    DbColumn column = new DbColumn(columnName, columnType, position);
                    columns.add(column);
                }

                // Remember any primary key the table may have.
                pkResultSet = metadata.getPrimaryKeys(null, schema, tableName);

                if (pkResultSet.next()) {
                    String pkColumnName = pkResultSet.getString("COLUMN_NAME").toLowerCase();
                    log.debug2(DEBUG_HEADER + "pkColumnName = '" + pkColumnName + "'.");

                    for (DbColumn column : columns) {
                        if (pkColumnName.equals(column.getName())) {
                            column.setPk(true);
                            break;
                        }
                    }
                }

                // Remember any foreign keys the table may have.
                fkResultSet = metadata.getImportedKeys(null, schema, tableName);

                while (fkResultSet.next()) {
                    String fkColumnName = fkResultSet.getString("FKCOLUMN_NAME").toLowerCase();
                    log.debug2(DEBUG_HEADER + "fkColumnName = '" + fkColumnName + "'.");

                    String fkTableName = fkResultSet.getString("PKTABLE_NAME").toLowerCase();
                    log.debug2(DEBUG_HEADER + "fkTableName = '" + fkTableName + "'.");

                    for (DbColumn column : columns) {
                        if (fkColumnName.equals(column.getName())) {
                            column.setFkTable(fkTableName);
                            break;
                        }
                    }
                }

                // Sort the columns by their ordinal position.
                Collections.sort(columns);

                if (log.isDebug3()) {
                    for (DbColumn column : columns) {
                        log.debug3(DEBUG_HEADER + "column = '" + column + "'.");
                    }
                }

                // Add  the table to the result.
                tableMap.put(tableName.toLowerCase(), table);
            }
        }
    } catch (SQLException sqle) {
        String message = "Cannot populate DB metadata.";
        log.error(message);
        log.error("TABLE_NAME = " + tableName);
        throw new DbMigratorException(message, sqle);
    } catch (RuntimeException re) {
        String message = "Cannot populate DB metadata.";
        log.error(message);
        log.error("TABLE_NAME = " + tableName);
        throw new DbMigratorException(message, re);
    } finally {
        DbManagerSql.safeCloseResultSet(fkResultSet);
        DbManagerSql.safeCloseResultSet(pkResultSet);
        DbManagerSql.safeCloseResultSet(columnResultSet);
        DbManagerSql.safeCloseResultSet(tableResultSet);

        try {
            DbManagerSql.rollback(conn, log);
        } catch (SQLException sqle) {
            throw new DbMigratorException(sqle);
        } catch (RuntimeException re) {
            throw new DbMigratorException(re);
        }
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "tableMap.size() = " + tableMap.size());
    return tableMap;
}

From source file:org.nextframework.persistence.exception.FirebirdSQLErrorCodesTranslator.java

@Override
protected DataAccessException customTranslate(String task, String sql, SQLException sqlEx) {
    //TODO ARRUMAR (FAZER HIGH COHESION.. LOW COUPLING)
    //System.out.println(task+" - "+sql);
    if (sqlEx.getErrorCode() == 335544466) {
        //exceo de FK
        Matcher matcher = pattern.matcher(sqlEx.getMessage());
        matcher.find();/* w w w.j a va2  s. c  o  m*/
        String fk_name = matcher.group(1);
        String fk_table_name = matcher.group(2).toUpperCase();
        String pk_table_name = null;
        String fkTableDisplayName = null;
        String pkTableDisplayName = null;
        try {
            DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
            ResultSet importedKeys = metaData.getImportedKeys(null, null, fk_table_name);

            while (importedKeys.next()) {
                if (importedKeys.getString("FK_NAME").equals(fk_name)) {
                    pk_table_name = importedKeys.getString("PKTABLE_NAME");
                    if (pk_table_name != null) {
                        pk_table_name = pk_table_name.toUpperCase();
                    }
                }
            }
        } catch (SQLException e) {
            //se nao conseguir o metadata .. vazar
            log.warn("No foi possvel conseguir o metadata do banco para ler informacoes de FK.");
            return null;
        }

        Class<?>[] entities = ClassManagerFactory.getClassManager().getClassesWithAnnotation(Entity.class);
        pkTableDisplayName = pk_table_name;
        fkTableDisplayName = fk_table_name;
        for (Class<?> entityClass : entities) {
            String tableName = getTableName(entityClass);
            if (tableName.equals(pk_table_name)) {
                pkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
            if (tableName.equals(fk_table_name)) {
                fkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
        }

        String mensagem = null;
        if (sql.toLowerCase().trim().startsWith("delete")) {
            mensagem = "No foi possvel remover " + pkTableDisplayName
                    + ". Existe(m) registro(s) vinculado(s) em " + fkTableDisplayName + ".";
        } else if (sql.toLowerCase().trim().startsWith("update")) {
            mensagem = "No foi possvel atualizar " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        } else if (sql.toLowerCase().trim().startsWith("insert")) {
            mensagem = "No foi possvel inserir " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        }
        return new ForeignKeyException(mensagem);
    }
    return null;
}

From source file:org.nextframework.persistence.exception.OracleSQLErrorCodeSQLExceptionTranslator.java

@Override
protected DataAccessException customTranslate(String task, String sql, SQLException sqlEx) {
    //TODO ARRUMAR (FAZER HIGH COHESION.. LOW COUPLING)
    //System.out.println(task+" - "+sql);
    if (sqlEx.getNextException() != null) {
        sqlEx = sqlEx.getNextException();
    }/*from w  ww.  ja  v a  2 s  .  c  o  m*/
    String errorMessage = sqlEx.getMessage();
    Matcher matcher = pattern.matcher(errorMessage);
    Matcher matcherIngles = patternIngles.matcher(errorMessage);
    //System.out.println(">>> "+errorMessage);
    if (!matcher.find()) {
        matcher = matcherIngles;
    } else {
        matcher.reset();
    }
    if (matcher.find()) {
        //exceo de FK
        String fk_name = matcher.group(1);
        if (fk_name.contains(".")) {
            fk_name = fk_name.substring(fk_name.indexOf('.') + 1, fk_name.length());
        }

        String fk_table_name = matcher.group(1).toUpperCase();
        String pk_table_name = matcher.group(1).toUpperCase();
        String fkTableDisplayName = null;
        String pkTableDisplayName = null;
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet importedKeys = metaData.getImportedKeys(null, null, null);

            while (importedKeys.next()) {
                System.out.println(importedKeys.getString("FK_NAME"));
                if (importedKeys.getString("FK_NAME").equals(fk_name)) {
                    pk_table_name = importedKeys.getString("PKTABLE_NAME");
                    if (pk_table_name != null) {
                        pk_table_name = pk_table_name.toUpperCase();
                    }

                    fk_table_name = importedKeys.getString("FKTABLE_NAME");
                    if (fk_table_name != null) {
                        fk_table_name = fk_table_name.toUpperCase();
                    }
                }
            }
        } catch (SQLException e) {
            //se nao conseguir o metadata .. vazar
            log.warn("No foi possvel conseguir o metadata do banco para ler informacoes de FK.");
            return null;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {

                }
            }
        }

        Class<?>[] entities = ClassManagerFactory.getClassManager().getClassesWithAnnotation(Entity.class);
        pkTableDisplayName = pk_table_name;
        fkTableDisplayName = fk_table_name;
        for (Class<?> entityClass : entities) {
            String tableName = getTableName(entityClass);
            if (tableName.equals(pk_table_name)) {
                pkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
            if (tableName.equals(fk_table_name)) {
                fkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
        }

        String mensagem = null;
        if (sql.toLowerCase().trim().startsWith("delete")) {
            mensagem = "No foi possvel remover " + pkTableDisplayName
                    + ". Existe(m) registro(s) vinculado(s) em " + fkTableDisplayName + ".";
        } else if (sql.toLowerCase().trim().startsWith("update")) {
            mensagem = "No foi possvel atualizar " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        } else if (sql.toLowerCase().trim().startsWith("insert")) {
            mensagem = "No foi possvel inserir " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        }
        return new ForeignKeyException(mensagem);
    } else {
        int indexOf = errorMessage.indexOf("APP");
        if (indexOf > 0) {
            errorMessage = errorMessage.substring(indexOf + 3);
            return new ApplicationDatabaseException(errorMessage);
        }
    }
    return null;
}