List of usage examples for java.sql SQLException getSQLState
public String getSQLState()
SQLException
object. From source file:vitro.vspEngine.service.persistence.DBCommons.java
public DBRegisteredGateway getRegisteredGateway(String pGwId) { DBRegisteredGateway retRegGw = null; if (pGwId != null && !pGwId.isEmpty()) { java.sql.Connection conn = null; try {// w w w .jav a 2s .c om Class.forName(jdbcdriverClassName).newInstance(); conn = DriverManager.getConnection(connString, usrStr, pwdStr); String echomessage = ""; if (!conn.isClosed()) { //echomessage = "Successfully connected to "+ "MySQL server using TCP/IP..."; Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); if (stmt.execute( "SELECT idregisteredgateway, registeredName, friendlyName, friendlyDescription, ip, listeningport, lastadvtimestamp, disabled, FROM_UNIXTIME(lastadvtimestamp, \'%d/%m/%Y %H:%i:%s\') lastdate FROM `" + dbSchemaStr + "`.`registeredgateway` WHERE registeredName=\'" + pGwId + "\'")) { rs = stmt.getResultSet(); } if (rs != null) { while (rs.next()) { int gateId = rs.getInt("idregisteredgateway"); String registeredName = rs.getString("registeredName") == null ? "" : rs.getString("registeredName"); // this is the one used in registration messages String friendlyName = rs.getString("friendlyName") == null ? "" : rs.getString("friendlyName"); String friendlyDescription = rs.getString("friendlyDescription") == null ? "" : rs.getString("friendlyDescription"); String gateIp = rs.getString("ip") == null ? "" : rs.getString("ip"); String gatePort = rs.getString("listeningport") == null ? "" : rs.getString("listeningport"); int lastadvtimestampInt = rs.getInt("lastadvtimestamp"); String lastdate = rs.getString("lastdate") == null ? "N/A" : rs.getString("lastdate"); Boolean status = rs.getBoolean("disabled"); if (!registeredName.isEmpty() && !registeredName.equalsIgnoreCase("")) { retRegGw = new DBRegisteredGateway(gateId, registeredName, friendlyName, friendlyDescription, gateIp, gatePort, lastadvtimestampInt, lastdate, status); } break; // we only need one result, so break here } } } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } finally { // it is a good idea to release // resources in a finally{} block // in reverse-order of their creation // if they are no-longer needed if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { System.out.println("SQLException on rs close(): " + sqlEx.getMessage()); } // ignore rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { System.out.println("SQLException on stmt close(): " + sqlEx.getMessage()); } // ignore stmt = null; } } } else { echomessage = "Error accessing DB server..."; } System.out.println(echomessage); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { } } } return retRegGw; }
From source file:gemlite.core.internal.db.DBSynchronizer.java
/** * Returns an {@link SqlExceptionHandler} for the given {@link SQLException} * ./*from ww w . ja va2s. c om*/ */ protected SqlExceptionHandler handleSQLException(SQLException sqle) { String sqlState = sqle.getSQLState(); // What to do if SQLState is null? Checking through the exception // message for common strings for now but DB specific errorCode and // other // such checks will be better. // Below was due to a bug in wrapper OracleDriver being used and // normally // this can never be null. if (sqlState == null) { // no SQLState so fallback to string matching in the message // for BatchUpdateException it will look at the nextException if (sqle instanceof BatchUpdateException && sqle.getNextException() != null) { // "42Y96" represents an unknown exception but batch exception // will // look at the nextException in any case sqlState = "42Y96"; } else { // if connection has been closed then refresh it try { synchronized (this) { if (this.conn == null || this.conn.isClosed()) { return SqlExceptionHandler.REFRESH; } } } catch (Exception e) { return SqlExceptionHandler.REFRESH; } // treat like a connection failure by default return checkExceptionString(sqle.toString().toLowerCase(), SqlExceptionHandler.REFRESH); } } // check for exception type first SqlExceptionHandler handler = checkExceptionType(sqle); if (handler != null) { return handler; } // next check SQLStates //about SQLStates see http://blog.csdn.net/cangyingaoyou/article/details/7402243 if (sqlState.startsWith("25") || sqlState.startsWith("42")) { // constraint violations can happen in retries, so default action is // to // IGNORE them; when errorFile is provided then it will be logged to // that in XML format in any case return SqlExceptionHandler.IGNORE; } else if (sqlState.startsWith("22") || sqlState.startsWith("23")) { // if numErrorTries is defined, then retry some number of times else // ignore after having logged warning since retry is not likely to // help return this.numErrorTries > 0 ? SqlExceptionHandler.IGNORE_BREAK_LOOP : SqlExceptionHandler.IGNORE; } else if (sqlState.startsWith("08")) { return SqlExceptionHandler.REFRESH; } else if (sqlState.startsWith("40")) { // these are transient transaction/lock exceptions so retry whole // batch return SqlExceptionHandler.IGNORE_BREAK_LOOP; } else { if (sqle instanceof BatchUpdateException && sqle.getNextException() != null) { return handleSQLException(sqle.getNextException()); } // if connection has been closed then refresh it try { synchronized (this) { if (this.conn == null || this.conn.isClosed()) { //return SqlExceptionHandler.REFRESH; //,?,??TODO ?? return SqlExceptionHandler.IGNORE; } } } catch (Exception e) { return SqlExceptionHandler.REFRESH; } return checkExceptionString(sqle.toString().toLowerCase(), SqlExceptionHandler.REFRESH); } }
From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java
private void doTestErrorCase(String sql, String expectedMessage, String expectedSQLState, int expectedErrorCode) throws SQLException { Statement stmt = con.createStatement(); boolean exceptionFound = false; try {//from w w w. j a va2 s. co m stmt.executeQuery(sql); } catch (SQLException e) { assertTrue("Adequate error messaging not found for '" + sql + "': " + e.getMessage(), e.getMessage().contains(expectedMessage)); assertEquals("Expected SQLState not found for '" + sql + "'", expectedSQLState, e.getSQLState()); assertEquals("Expected error code not found for '" + sql + "'", expectedErrorCode, e.getErrorCode()); exceptionFound = true; } assertNotNull("Exception should have been thrown for query: " + sql, exceptionFound); }
From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java
protected void logException(String message, SQLException se) { if (message != null) { log.error(message);// www . ja v a 2 s .com } log.error(" reason: " + se.getMessage()); log.error("state/code: " + se.getSQLState() + "/" + se.getErrorCode()); log.debug(" dump:", se); }
From source file:org.seasar.dbflute.helper.jdbc.sqlfile.DfSqlFileFireMan.java
protected String buildDetailMessage(DfSqlFileFireResult fireResult) { final StringBuilder sb = new StringBuilder(); final List<DfSqlFileRunnerResult> runnerResultList = fireResult.getRunnerResultList(); for (DfSqlFileRunnerResult currentResult : runnerResultList) { final List<ErrorContinuedSql> errorContinuedSqlList = currentResult.getErrorContinuedSqlList(); final String fileName = currentResult.getSqlFile().getName(); final SQLFailureException breakCause = currentResult.getBreakCause(); if (sb.length() > 0) { sb.append(ln());// w ww .j av a2s .co m } if (breakCause != null) { // break by error sb.append("x ").append(fileName); sb.append(ln()).append(" >> (failed: Look at the exception message)"); } else { // normal or error-continued sb.append(errorContinuedSqlList.isEmpty() ? "o " : "x ").append(fileName); for (ErrorContinuedSql errorContinuedSql : errorContinuedSqlList) { final String sql = errorContinuedSql.getSql(); sb.append(ln()).append(sql); final SQLException sqlEx = errorContinuedSql.getSqlEx(); String message = sqlEx.getMessage(); if (sqlEx != null && message != null) { message = message.trim(); final LineToken lineToken = new LineToken(); final LineTokenizingOption lineTokenizingOption = new LineTokenizingOption(); lineTokenizingOption.setDelimiter(ln()); final List<String> tokenizedList = lineToken.tokenize(message, lineTokenizingOption); int elementIndex = 0; for (String element : tokenizedList) { if (elementIndex == 0) { sb.append(ln()).append(" >> ").append(element); } else { sb.append(ln()).append(" ").append(element); } ++elementIndex; } if (isShowSQLState(sqlEx)) { sb.append(ln()); sb.append(" (SQLState=").append(sqlEx.getSQLState()); sb.append(" ErrorCode=").append(sqlEx.getErrorCode()).append(")"); } } } } } return sb.toString(); }
From source file:mom.trd.opentheso.bdd.helper.RelationsHelper.java
/** * Cette fonction permet d'ajouter une relation MT ou domaine un concept * * @param conn// www .j ava 2s.c o m * @param idConcept * @param idGroup * @param idThesaurus * @return boolean */ public boolean setRelationMT(Connection conn, String idConcept, String idGroup, String idThesaurus) { Statement stmt; boolean status = false; String query; Savepoint savepoint = null; try { // Get connection from pool savepoint = conn.setSavepoint(); try { stmt = conn.createStatement(); try { /* if (!new RelationsHelper().addRelationHistorique(conn, idConcept, idThesaurus, idConcept, "TT", idUser, "DEL")) { return false; }*/ query = "UPDATE concept set" + " id_group = '" + idGroup + "'," + " modified = now()" + " WHERE id_concept ='" + idConcept + "'" + " AND id_thesaurus = '" + idThesaurus + "'"; stmt.executeUpdate(query); status = true; } finally { stmt.close(); } } finally { // conn.close(); } } catch (SQLException sqle) { // Log exception if (sqle.getSQLState().equalsIgnoreCase("23505")) { try { if (savepoint != null) { conn.rollback(savepoint); status = true; } } catch (SQLException ex) { Logger.getLogger(RelationsHelper.class.getName()).log(Level.SEVERE, null, ex); } } else { log.error("Error while adding relation MT of Concept : " + idConcept, sqle); } } return status; }
From source file:mom.trd.opentheso.bdd.helper.RelationsHelper.java
/** * Cette fonction permet de rajouter une relation type Groupe ou domaine * un concept/* w w w . jav a2 s . co m*/ * * @param conn * @param idConcept * @param idGroup * @param idThesaurus * @param idUser * @return boolean */ public boolean addRelationMT(Connection conn, String idConcept, String idThesaurus, String idGroup, int idUser) { Statement stmt; boolean status = false; String query; Savepoint savepoint = null; try { // Get connection from pool savepoint = conn.setSavepoint(); try { stmt = conn.createStatement(); try { /* if (!new RelationsHelper().addRelationHistorique(conn, idConcept, idThesaurus, idConcept, "MT", idUser, "ADD")) { return false; }*/ query = "Insert into concept" + "(id_concept, id_thesaurus, id_ark, top_concept, id_group)" + " values (" + "'" + idConcept + "'" + ",'" + idThesaurus + "'" + ",''," + "false" + ",'" + idGroup + "')"; stmt.executeUpdate(query); status = true; } finally { stmt.close(); } } finally { // conn.close(); } } catch (SQLException sqle) { // Log exception if (sqle.getSQLState().equalsIgnoreCase("23505")) { try { if (savepoint != null) { conn.rollback(savepoint); status = true; } } catch (SQLException ex) { Logger.getLogger(RelationsHelper.class.getName()).log(Level.SEVERE, null, ex); } } else { log.error("Error while adding relation MT of Concept : " + idConcept, sqle); } } return status; }
From source file:com.googlecode.fascinator.portal.HouseKeeper.java
/** * Stop the House Keeper. Including stopping the storage and indexer *///from ww w . j a va 2 s .co m @Override public void stop() throws Exception { openLog(); log.info("Stopping House Keeping object..."); timer.cancel(); if (indexer != null) { try { indexer.shutdown(); } catch (PluginException pe) { log.error("Failed to shutdown indexer: {}", pe.getMessage()); closeLog(); throw pe; } } if (storage != null) { try { storage.shutdown(); } catch (PluginException pe) { log.error("Failed to shutdown storage: {}", pe.getMessage()); closeLog(); throw pe; } } if (consumer != null) { try { consumer.close(); } catch (JMSException jmse) { log.warn("Failed to close consumer: {}", jmse.getMessage()); closeLog(); throw jmse; } } if (cSession != null) { try { cSession.close(); } catch (JMSException jmse) { log.warn("Failed to close consumer session: {}", jmse); } } if (pSession != null) { try { pSession.close(); } catch (JMSException jmse) { log.warn("Failed to close consumer session: {}", jmse); } } if (connection != null) { try { connection.close(); } catch (JMSException jmse) { log.warn("Failed to close connection: {}", jmse); } } // Derby can only be shutdown from one thread, // we'll catch errors from the rest. String threadedShutdownMessage = DERBY_DRIVER + " is not registered with the JDBC driver manager"; try { // Tell the database to close DriverManager.getConnection(DERBY_PROTOCOL + ";shutdown=true"); // Shutdown just this database (but not the engine) // DriverManager.getConnection(DERBY_PROTOCOL + SECURITY_DATABASE + // ";shutdown=true"); } catch (SQLException ex) { // These test values are used if the engine is NOT shutdown // if (ex.getErrorCode() == 45000 && // ex.getSQLState().equals("08006")) { // Valid response if (ex.getErrorCode() == 50000 && ex.getSQLState().equals("XJ015")) { // Error response } else { // Make sure we ignore simple thread issues if (!ex.getMessage().equals(threadedShutdownMessage)) { log.warn("Error during database shutdown:", ex); } } } finally { try { // Close our connection if (dbConnection != null) { dbConnection.close(); dbConnection = null; } } catch (SQLException ex) { log.warn("Error closing connection:", ex); } } // Shutdown the scheduler if (scheduler != null) { try { scheduler.shutdown(); } catch (SchedulerException ex) { log.warn("Failed to close connection: {}", ex); } } closeLog(); }
From source file:mom.trd.opentheso.bdd.helper.RelationsHelper.java
/** * Cette fonction permet de rajouter une relation dans l'historique * * @param conn//from www. j av a 2 s.c om * @param idConcept1 * @param idThesaurus * @param idConcept2 * @param role * @param idUser * @param action * @return boolean */ public boolean addRelationHistorique(Connection conn, String idConcept1, String idThesaurus, String idConcept2, String role, int idUser, String action) { Statement stmt; boolean status = false; try { try { stmt = conn.createStatement(); try { String query = "Insert into hierarchical_relationship_historique" + "(id_concept1, id_thesaurus, role, id_concept2, id_user, action)" + " values (" + "'" + idConcept1 + "'" + ",'" + idThesaurus + "'" + ",'" + role + "'" + ",'" + idConcept2 + "'" + ",'" + idUser + "'" + ",'" + action + "')"; stmt.executeUpdate(query); status = true; // System.err.println(query); } finally { stmt.close(); } } finally { // conn.close(); } } catch (SQLException sqle) { // Log exception // if (!sqle.getMessage().contains("duplicate key value violates unique constraint")) { if (!sqle.getSQLState().equalsIgnoreCase("23505")) { log.error("Error while adding relation historique of Concept : " + idConcept1, sqle); } } return status; }
From source file:org.exist.xquery.modules.oracle.ExecuteFunction.java
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { if (args.length == 5 || args.length == 6) { // was a connection and PL/SQL statement specified? if (args[0].isEmpty() || args[1].isEmpty()) { return (Sequence.EMPTY_SEQUENCE); }/*from www . ja v a 2s. c o m*/ // get the Connection long connectionUID = ((IntegerValue) args[0].itemAt(0)).getLong(); Connection connection = SQLModule.retrieveConnection(context, connectionUID); if (connection == null) { return (Sequence.EMPTY_SEQUENCE); } // get the PL/SQL statement String plSql = args[1].getStringValue(); // get the input parameters (if any) Element parameters = null; if (!args[2].isEmpty()) { parameters = (Element) args[2].itemAt(0); } // was a result set position specified? int resultSetPos = 0; if (!args[3].isEmpty()) { resultSetPos = ((IntegerValue) args[3].itemAt(0)).getInt(); } boolean haveReturnCode = false; int plSqlSuccess = 1; // default value of 1 for success if (args.length == 6) { // a return code is expected so what is the value indicating success? plSqlSuccess = ((IntegerValue) args[5].itemAt(0)).getInt(); haveReturnCode = true; } CallableStatement statement = null; ResultSet resultSet = null; try { MemTreeBuilder builder = context.getDocumentBuilder(); int iRow = 0; statement = connection.prepareCall(plSql); if (haveReturnCode) { statement.registerOutParameter(1, Types.NUMERIC); } if (resultSetPos != 0) { statement.registerOutParameter(resultSetPos, OracleTypes.CURSOR); } if (!args[2].isEmpty()) { setParametersOnPreparedStatement(statement, parameters); } statement.execute(); if (haveReturnCode) { int returnCode = statement.getInt(1); if (returnCode != plSqlSuccess) { LOG.error(plSql + " failed [" + returnCode + "]"); return (Sequence.EMPTY_SEQUENCE); } } if (resultSetPos != 0) { // iterate through the result set building an XML document builder.startDocument(); builder.startElement(new QName("result", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); builder.addAttribute(new QName("count", null, null), String.valueOf(-1)); resultSet = (ResultSet) statement.getObject(resultSetPos); ResultSetMetaData rsmd = resultSet.getMetaData(); int iColumns = rsmd.getColumnCount(); while (resultSet.next()) { builder.startElement(new QName("row", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); builder.addAttribute(new QName("index", null, null), String.valueOf(resultSet.getRow())); // get each tuple in the row for (int i = 0; i < iColumns; i++) { String columnName = rsmd.getColumnLabel(i + 1); if (columnName != null) { String colValue = resultSet.getString(i + 1); String colElement = "field"; if (((BooleanValue) args[4].itemAt(0)).effectiveBooleanValue() && columnName.length() > 0) { // use column names as the XML node /** * Spaces in column names are replaced with * underscore's */ colElement = SQLUtils.escapeXmlAttr(columnName.replace(' ', '_')); } builder.startElement( new QName(colElement, OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); if (!((BooleanValue) args[4].itemAt(0)).effectiveBooleanValue() || columnName.length() <= 0) { String name; if (columnName.length() > 0) { name = SQLUtils.escapeXmlAttr(columnName); } else { name = "Column: " + String.valueOf(i + 1); } builder.addAttribute(new QName("name", null, null), name); } builder.addAttribute( new QName("type", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), rsmd.getColumnTypeName(i + 1)); builder.addAttribute(new QName("type", Namespaces.SCHEMA_NS, "xs"), Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1)))); if (resultSet.wasNull()) { // Add a null indicator attribute if the value was SQL Null builder.addAttribute( new QName("null", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), "true"); } if (colValue != null) { builder.characters(SQLUtils.escapeXmlText(colValue)); } builder.endElement(); } } builder.endElement(); iRow++; } builder.endElement(); // Change the root element count attribute to have the correct value NodeValue node = (NodeValue) builder.getDocument().getDocumentElement(); Node count = node.getNode().getAttributes().getNamedItem("count"); if (count != null) { count.setNodeValue(String.valueOf(iRow)); } builder.endDocument(); // return the XML result set return (node); } else { // there was no result set so just return an empty sequence return (Sequence.EMPTY_SEQUENCE); } } catch (SQLException sqle) { LOG.error("oracle:execute() Caught SQLException \"" + sqle.getMessage() + "\" for PL/SQL: \"" + plSql + "\"", sqle); //return details about the SQLException MemTreeBuilder builder = context.getDocumentBuilder(); builder.startDocument(); builder.startElement(new QName("exception", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); boolean recoverable = false; if (sqle instanceof SQLRecoverableException) { recoverable = true; } builder.addAttribute(new QName("recoverable", null, null), String.valueOf(recoverable)); builder.startElement(new QName("state", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); String sqlState = sqle.getSQLState(); if (sqlState != null) { builder.characters(sqle.getSQLState()); } else { builder.characters("null"); } builder.endElement(); builder.startElement(new QName("message", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); builder.characters(sqle.getMessage()); builder.endElement(); builder.startElement(new QName("stack-trace", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); ByteArrayOutputStream bufStackTrace = new ByteArrayOutputStream(); sqle.printStackTrace(new PrintStream(bufStackTrace)); builder.characters(new String(bufStackTrace.toByteArray())); builder.endElement(); builder.startElement(new QName("oracle", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); builder.characters(SQLUtils.escapeXmlText(plSql)); builder.endElement(); int line = getLine(); int column = getColumn(); builder.startElement(new QName("xquery", OracleModule.NAMESPACE_URI, OracleModule.PREFIX), null); builder.addAttribute(new QName("line", null, null), String.valueOf(line)); builder.addAttribute(new QName("column", null, null), String.valueOf(column)); builder.endElement(); builder.endElement(); builder.endDocument(); return (NodeValue) builder.getDocument().getDocumentElement(); } finally { release(connection, statement, resultSet); } } else { throw new XPathException("Invalid number of arguments [" + args.length + "]"); } }