Example usage for java.sql SQLException getNextException

List of usage examples for java.sql SQLException getNextException

Introduction

In this page you can find the example usage for java.sql SQLException getNextException.

Prototype

public SQLException getNextException() 

Source Link

Document

Retrieves the exception chained to this SQLException object by setNextException(SQLException ex).

Usage

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();
    }//ww w  . jav 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;
}

From source file:nl.b3p.kaartenbalie.struts.KaartenbalieCrudAction.java

/** Execute method which handles all incoming request.
 *
 * @param mapping action mapping//from w  w  w  .  ja v a  2  s.  c  o m
 * @param dynaForm dyna validator form
 * @param request servlet request
 * @param response servlet response
 *
 * @return ActionForward defined by Apache foundation
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) method.">
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Object identity = null;

    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        ActionForward forward = null;
        String msg = null;

        EntityManager em = getEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();

            forward = super.execute(mapping, form, request, response);

            tx.commit();

            return forward;
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured, rollback", e);

            if (e instanceof org.hibernate.JDBCException) {
                msg = e.toString();
                SQLException sqle = ((org.hibernate.JDBCException) e).getSQLException();
                msg = msg + ": " + sqle;
                SQLException nextSqlE = sqle.getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else if (e instanceof java.sql.SQLException) {
                msg = e.toString();
                SQLException nextSqlE = ((java.sql.SQLException) e).getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else {
                msg = e.toString();
            }

            addAlternateMessage(mapping, request, null, msg);
        }

        try {
            tx.begin();

            prepareMethod((DynaValidatorForm) form, request, LIST, EDIT);

            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured in second session, rollback", e);

            addAlternateMessage(mapping, request, null, e.toString());
        }
    } catch (Throwable e) {
        log.error("Exception occured while getting EntityManager: ", e);
        addAlternateMessage(mapping, request, null, e.toString());

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }

    return getAlternateForward(mapping, request);
}

From source file:org.fornax.cartridges.sculptor.framework.errorhandling.ErrorHandlingAdvice.java

protected void handleDatabaseAccessException(Object target, Exception e) {
    Logger log = LoggerFactory.getLogger(target.getClass());

    // often the wrapped SQLException contains the interesting piece of
    // information
    StringBuilder message = new StringBuilder();
    message.append(e.getClass().getName()).append(": ");
    message.append(excMessage(e));//w w  w .  ja  v  a  2s. c  o m
    SQLException sqlExc = ExceptionHelper.unwrapSQLException(e);
    Throwable realException = sqlExc;
    if (sqlExc != null) {
        message.append(", Caused by: ");
        message.append(sqlExc.getClass().getName()).append(": ");
        message.append(excMessage(sqlExc));
        if (sqlExc.getNextException() != null) {
            message.append(", Next exception: ");
            message.append(sqlExc.getNextException().getClass().getName()).append(": ");
            message.append(excMessage(sqlExc.getNextException()));
            realException = sqlExc.getNextException();
        }
    }

    if (isJmsContext() && !isJmsRedelivered()) {
        LogMessage logMessage = new LogMessage(mapLogCode(DatabaseAccessException.ERROR_CODE),
                message.toString());
        log.info("{}", logMessage);
    } else {
        LogMessage logMmessage = new LogMessage(mapLogCode(DatabaseAccessException.ERROR_CODE),
                message.toString());
        log.error(logMmessage.toString(), e);
    }

    DatabaseAccessException newException = new DatabaseAccessException(message.toString(), realException);
    newException.setLogged(true);
    throw newException;
}

From source file:org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.java

public DataAccessException translate(String task, String sql, SQLException sqlEx) {
    if (task == null) {
        task = "";
    }/*from   ww  w  .  j  a  v a  2s.com*/
    if (sql == null) {
        sql = "";
    }

    String sqlState = sqlEx.getSQLState();
    // Some JDBC drivers nest the actual exception from a batched update: need to get the nested one.
    if (sqlState == null) {
        SQLException nestedEx = sqlEx.getNextException();
        if (nestedEx != null) {
            sqlState = nestedEx.getSQLState();
        }
    }
    if (sqlState != null && sqlState.length() >= 2) {
        String classCode = sqlState.substring(0, 2);
        if (BAD_SQL_CODES.contains(classCode)) {
            return new BadSqlGrammarException(task, sql, sqlEx);
        } else if (INTEGRITY_VIOLATION_CODES.contains(classCode)) {
            return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
        }
    }

    // We couldn't identify it more precisely.
    return new UncategorizedSQLException(task, sql, sqlEx);
}

From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java

/**
 * Insert text into PostgreSQL/*  www  .  j  a  va 2  s.c om*/
 * 
 * @param files 
 *           List of Strings of text to insert
 * 
 * @return number of rows affected
 * 
 * @throws Exception TODO describe exception
 */
public int addFile(String action_number, String make, String model, String year, String compname,
        String mfr_name, String odate, String cdate, String campno, String subject, String summary)
        throws Exception {

    String sql = "INSERT INTO reportedErrors (action_number, make, model, year, compname, mfr_name, odate, cdate, campno, subject, summary) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,)";
    Connection connection = null;
    PreparedStatement statement = null;

    try {
        connection = getConnection();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(sql);

        statement.setString(1, action_number);
        statement.setString(2, make);
        statement.setString(3, model);
        statement.setString(4, year);
        statement.setString(5, compname);
        statement.setString(6, mfr_name);
        statement.setString(7, odate);
        statement.setString(8, cdate);
        statement.setString(9, campno);
        statement.setString(10, subject);
        statement.setString(11, summary);

        statement.addBatch();

        int[] rows = statement.executeBatch();
        connection.commit();

        return rows.length;

    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

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

From source file:com.fer.hr.olap.discover.OlapMetaExplorer.java

private boolean isMondrian(Cube cube) {
    OlapConnection con = cube.getSchema().getCatalog().getDatabase().getOlapConnection();
    try {/*from  w  w w.  j  ava 2  s. c om*/
        return con.isWrapperFor(RolapConnection.class);
    } catch (SQLException e) {
        log.error("SQLException", e.getNextException());
    }
    return false;
}

From source file:org.seasar.dbflute.exception.handler.SQLExceptionHandler.java

protected void setupSQLExceptionElement(ExceptionMessageBuilder br, SQLException e) {
    br.addItem("SQLException");
    br.addElement(e.getClass().getName());
    br.addElement(extractMessage(e));//from   ww  w  .  ja  v a  2  s.c  o  m
    final SQLException nextEx = e.getNextException();
    if (nextEx != null) {
        br.addItem("NextException");
        br.addElement(nextEx.getClass().getName());
        br.addElement(extractMessage(nextEx));
        final SQLException nextNextEx = nextEx.getNextException();
        if (nextNextEx != null) {
            br.addItem("NextNextException");
            br.addElement(nextNextEx.getClass().getName());
            br.addElement(extractMessage(nextNextEx));
        }
    }
}

From source file:org.j2free.error.HoptoadNotifier.java

/**
 * Looks up and returns the root cause of an exception. If none is found, returns
 * supplied Throwable object unchanged. If root is found, recursively "unwraps" it,
 * and returns the result to the user./*from  w w  w  . ja  v a2 s  .  c  o  m*/
 */
private Throwable unwindException(Throwable thrown) {
    if (thrown instanceof SAXException) {
        SAXException saxe = (SAXException) thrown;
        if (saxe.getException() != null)
            return unwindException(saxe.getException());
    } else if (thrown instanceof SQLException) {
        SQLException sqle = (SQLException) thrown;
        if (sqle.getNextException() != null)
            return unwindException(sqle.getNextException());
    } else if (thrown.getCause() != null)
        return unwindException(thrown.getCause());

    return thrown;
}

From source file:org.seasar.dbflute.exception.handler.SQLExceptionHandler.java

protected String extractSQLState(SQLException e) {
    String sqlState = e.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }/*from   w  ww .j a va 2 s  . c  o m*/

    // Next
    SQLException nextEx = e.getNextException();
    if (nextEx == null) {
        return null;
    }
    sqlState = nextEx.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }

    // Next Next
    SQLException nextNextEx = nextEx.getNextException();
    if (nextNextEx == null) {
        return null;
    }
    sqlState = nextNextEx.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }

    // Next Next Next
    SQLException nextNextNextEx = nextNextEx.getNextException();
    if (nextNextNextEx == null) {
        return null;
    }
    sqlState = nextNextNextEx.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }

    // It doesn't use recursive call by design because JDBC is unpredictable fellow.
    return null;
}

From source file:org.apache.openjpa.jdbc.sql.SybaseDictionary.java

public boolean isFatalException(int subtype, SQLException ex) {
    if (subtype == StoreException.LOCK) {
        SQLException next = ex.getNextException();
        if ("JZ0TO".equals(next.getSQLState())) {
            return false; // query timeout
        }/*from www.jav  a2 s .  c  o m*/
    }
    return super.isFatalException(subtype, ex);
}