Example usage for java.sql SQLException getSQLState

List of usage examples for java.sql SQLException getSQLState

Introduction

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

Prototype

public String getSQLState() 

Source Link

Document

Retrieves the SQLState for this SQLException object.

Usage

From source file:org.batoo.jpa.jdbc.dbutils.QueryRunner.java

/**
 * Throws a new exception with a more informative error message.
 * /*  w w w . j a v a2s  .c om*/
 * @param cause
 *            The original exception that will be chained to the new exception when it's rethrown.
 * 
 * @param sql
 *            The query that was executing when the exception happened.
 * 
 * @param params
 *            The query replacement parameters; <code>null</code> is a valid value to pass in.
 * @return SQLException if a database access error occurs
 */
private SQLException convertSqlException(SQLException cause, String sql, Object... params) {
    String causeMessage = cause.getMessage();
    if (causeMessage == null) {
        causeMessage = "";
    }

    final StringBuffer msg = new StringBuffer(causeMessage);

    msg.append(" Query: ");
    msg.append(sql);
    msg.append(" Parameters: ");

    if (params == null) {
        msg.append("[]");
    } else {
        msg.append(Arrays.deepToString(params));
    }

    final SQLException e = new SQLException(msg.toString(), cause.getSQLState(), cause.getErrorCode());
    e.setNextException(cause);

    return e;
}

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

public DataAccessException translate(String task, String sql, SQLException sqlEx) {
    if (task == null) {
        task = "";
    }//from   w ww  .j  a v  a2  s .c  o m
    if (sql == null) {
        sql = "";
    }

    // First, try custom translation from overridden method.
    DataAccessException dex = customTranslate(task, sql, sqlEx);
    if (dex != null) {
        return dex;
    }

    // Check SQLErrorCodes with corresponding error code, if available.
    if (this.sqlErrorCodes != null) {
        String errorCode = null;
        if (this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            errorCode = sqlEx.getSQLState();
        } else {
            errorCode = Integer.toString(sqlEx.getErrorCode());
        }

        if (errorCode != null) {

            // Look for defined custom translations first.
            CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations();
            if (customTranslations != null) {
                for (int i = 0; i < customTranslations.length; i++) {
                    CustomSQLErrorCodesTranslation customTranslation = customTranslations[i];
                    if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) {
                        if (customTranslation.getExceptionClass() != null) {
                            DataAccessException customException = createCustomException(task, sql, sqlEx,
                                    customTranslation.getExceptionClass());
                            if (customException != null) {
                                logTranslation(task, sql, sqlEx, true);
                                return customException;
                            }
                        }
                    }
                }
            }

            // Next, look for grouped error codes.
            if (Arrays.binarySearch(this.sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new BadSqlGrammarException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getInvalidResultSetAccessCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new InvalidResultSetAccessException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataAccessResourceFailureCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataAccessResourceFailureException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataIntegrityViolationCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotAcquireLockCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotAcquireLockException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDeadlockLoserCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DeadlockLoserDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotSerializeTransactionCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotSerializeTransactionException(buildMessage(task, sql, sqlEx), sqlEx);
            }
        }
    }

    // We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator.
    if (logger.isDebugEnabled()) {
        logger.debug("Unable to translate SQLException with errorCode '" + sqlEx.getErrorCode()
                + "', will now try the fallback translator");
    }
    return this.fallbackTranslator.translate(task, sql, sqlEx);
}

From source file:org.seasar.dbflute.helper.jdbc.sqlfile.DfSqlFileRunnerBase.java

protected void throwSQLFailureException(String sql, SQLException e) {
    final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
    br.addNotice("Failed to execute the SQL!");
    br.addItem("SQL File");
    br.addElement(_sqlFile);/*from  w  w  w.ja  va 2  s  .  c  o  m*/
    br.addItem("Executed SQL");
    br.addElement(sql);
    br.addItem("SQLState");
    br.addElement(e.getSQLState());
    br.addItem("ErrorCode");
    br.addElement(e.getErrorCode());
    br.addItem("SQLException");
    br.addElement(e.getClass().getName());
    br.addElement(extractMessage(e));
    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));
        }
    }
    final String msg = br.buildExceptionMessage();
    throw new SQLFailureException(msg, e);
}

From source file:org.forgerock.openidm.repo.jdbc.impl.query.TableQueries.java

public Integer command(final String type, Map<String, Object> params, Connection con) throws ResourceException {

    Integer result = null;//from   w w  w . ja  v a  2s  .c om
    params.put(ServerConstants.RESOURCE_NAME, type);

    String queryExpression = (String) params.get("commandExpression");
    String queryId = (String) params.get("commandId");
    if (queryId == null && queryExpression == null) {
        throw new BadRequestException("Either " + "commandId" + " or " + "commandExpression"
                + " to identify/define a query must be passed in the parameters. " + params);
    }
    final PreparedStatement foundQuery;
    try {
        if (queryExpression != null) {
            foundQuery = resolveInlineQuery(con, queryExpression, params);
        } else if (commands.queryIdExists(queryId)) {
            foundQuery = commands.getQuery(con, queryId, type, params);
        } else {
            throw new BadRequestException("The passed command identifier " + queryId
                    + " does not match any configured commands on the JDBC repository service.");
        }
    } catch (SQLException ex) {
        throw new InternalServerErrorException("DB reported failure preparing command: "
                + (queryExpression != null ? queryExpression : commands.getQueryInfo(queryId).getQueryString())
                + " with params: " + params + " error code: " + ex.getErrorCode() + " sqlstate: "
                + ex.getSQLState() + " message: " + ex.getMessage(), ex);
    }

    Name eventName = getEventName(queryId);
    EventEntry measure = Publisher.start(eventName, foundQuery, null);
    ResultSet rs = null;
    try {
        result = foundQuery.executeUpdate();
        measure.setResult(result);
    } catch (SQLException ex) {
        throw new InternalServerErrorException("DB reported failure executing query " + foundQuery.toString()
                + " with params: " + params + " error code: " + ex.getErrorCode() + " sqlstate: "
                + ex.getSQLState() + " message: " + ex.getMessage(), ex);
    } finally {
        CleanupHelper.loggedClose(rs);
        CleanupHelper.loggedClose(foundQuery);
        measure.end();
    }
    return result;
}

From source file:org.wso2.andes.store.rdbms.RDBMSStoreUtils.java

public AndesException convertSQLException(String message, SQLException sqlException) {

    // try using SQLException subclasses (works for mysql)
    AndesException convertedException = convertBySQLException(message, sqlException);

    if (null == convertedException) {
        // trying using sql state flags ( works for jtds, mssql etc)
        convertedException = convertBySQLState(message, sqlException);
    }//from  www.  j a v a 2s .c  o m

    if (null == convertedException) {
        // if unable to determine exact error then throw a generic exception.
        convertedException = new AndesException(message, sqlException.getSQLState(), sqlException);
    }

    return convertedException;

}

From source file:org.kepler.util.sql.HSQL.java

/** Get a connection to the database. */
@Override/*  ww w. jav  a2s .  c  o  m*/
protected Connection _getConnection(String jdbcURL) throws SQLException {
    try {
        Connection connection = DriverManager.getConnection(jdbcURL);
        _updateConnectionReferenceCount(connection, jdbcURL);
        return connection;
    } catch (SQLException e) {
        String sqlState = e.getSQLState();

        if (_isDebugging) {
            _log.debug("failed = " + sqlState);
        }

        // see if the server is not running
        if (sqlState.equals(_SERVER_NOT_RUNNING_SQL_STATE)) {
            // attempt to find the path, alias, and port in the jdbc url
            Matcher matcher = _jdbcURLPattern.matcher(jdbcURL);
            if (!matcher.matches()) {
                throw new SQLException(
                        "Could not parse JDBC URL " + jdbcURL + "\n" + "JDBC URL must be in form of: "
                                + "jdbc:hsqldb:hsql://hostname:port/alias;filepath=hsqldb:path");
            }

            String pathStr = matcher.group(3);
            String aliasStr = matcher.group(2);
            String dbPort = matcher.group(1);

            // start a server
            int serverState = _launchDBServer(pathStr, aliasStr, dbPort);
            if (serverState != ServerConstants.SERVER_STATE_ONLINE) {
                throw new SQLException("Unable to start HSQL server for " + jdbcURL);
            }

            try {
                Connection retval = DriverManager.getConnection(jdbcURL);

                //System.out.println("new conn " + URL + " is " + conn);
                _serverConnectionSet.add(retval);
                _initializeNewURL(retval);
                return retval;
            } catch (SQLException e2) {
                throw new SQLException("Unable to start HSQL server for " + jdbcURL);
            }
        } else {
            throw e;
        }
    }
}

From source file:org.openconcerto.sql.model.SQLBase.java

Map<String, String> getFwkMetadata(final Collection<String> schemas, final String name) {
    if (schemas.isEmpty())
        return Collections.emptyMap();
    final Map<String, String> res = new LinkedHashMap<String, String>();
    CollectionUtils.fillMap(res, schemas);
    final ResultSetHandler rsh = new ResultSetHandler() {
        @Override//from w  w w.j a  va 2  s.c om
        public Object handle(ResultSet rs) throws SQLException {
            while (rs.next()) {
                res.put(rs.getString(1), rs.getString(2));
            }
            return null;
        }
    };
    try {
        if (this.getDataSource().getTransactionPoint() == null) {
            exec(schemas, name, rsh);
        } else {
            // If already in a transaction, don't risk aborting it if a table doesn't exist.
            // (it's not strictly required for H2 and MySQL, since the transaction is *not*
            // aborted)
            SQLUtils.executeAtomic(this.getDataSource(), new ConnectionHandlerNoSetup<Object, SQLException>() {
                @Override
                public Object handle(SQLDataSource ds) throws SQLException {
                    exec(schemas, name, rsh);
                    return null;
                }
            }, false);
        }
    } catch (Exception exn) {
        final SQLException sqlExn = SQLUtils.findWithSQLState(exn);
        final boolean tableNotFound = sqlExn != null
                && (sqlExn.getSQLState().equals("42S02") || sqlExn.getSQLState().equals("42P01"));
        if (!tableNotFound)
            throw new IllegalStateException("Not a missing table exception", sqlExn);

        // The following fall back should not currently be needed since the table is created
        // by JDBCStructureSource.getNames(). Even without that most DB should contain the
        // metadata tables.

        // if only one schema, there's no ambiguity : just return null value
        // otherwise retry with each single schema to find out which ones are missing
        if (schemas.size() > 1) {
            // this won't loop indefinetly since schemas.size() will be 1
            for (final String schema : schemas)
                res.put(schema, this.getFwkMetadata(schema, name));
        }
    }
    return res;
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#retrieve(String)
 *//*from  w ww .  j  av  a2s . c  o m*/
@SuppressWarnings("unchecked")
public Mail retrieve(String key) throws MessagingException {
    if (DEEP_DEBUG) {
        System.err.println("retrieving " + key);
    }
    Connection conn = null;
    PreparedStatement retrieveMessage = null;
    ResultSet rsMessage = null;
    try {
        conn = datasource.getConnection();
        if (DEEP_DEBUG) {
            System.err.println("got a conn " + key);
        }

        retrieveMessage = conn.prepareStatement(sqlQueries.getSqlString("retrieveMessageSQL", true));
        retrieveMessage.setString(1, key);
        retrieveMessage.setString(2, repositoryName);
        rsMessage = retrieveMessage.executeQuery();
        if (DEEP_DEBUG) {
            System.err.println("ran the query " + key);
        }
        if (!rsMessage.next()) {
            if (getLogger().isDebugEnabled()) {
                String debugBuffer = "Did not find a record " + key + " in " + repositoryName;
                getLogger().debug(debugBuffer);
            }
            return null;
        }
        // Determine whether attributes are used and retrieve them
        PreparedStatement retrieveMessageAttr = null;
        HashMap<String, Object> attributes = null;
        if (jdbcMailAttributesReady) {
            String retrieveMessageAttrSql = sqlQueries.getSqlString("retrieveMessageAttributesSQL", false);
            ResultSet rsMessageAttr = null;
            try {
                retrieveMessageAttr = conn.prepareStatement(retrieveMessageAttrSql);

                retrieveMessageAttr.setString(1, key);
                retrieveMessageAttr.setString(2, repositoryName);
                rsMessageAttr = retrieveMessageAttr.executeQuery();

                if (rsMessageAttr.next()) {
                    try {
                        byte[] serialized_attr;
                        String getAttributesOption = sqlQueries.getDbOption("getAttributes");
                        if (getAttributesOption != null && (getAttributesOption.equalsIgnoreCase("useBlob")
                                || getAttributesOption.equalsIgnoreCase("useBinaryStream"))) {
                            Blob b = rsMessageAttr.getBlob(1);
                            serialized_attr = b.getBytes(1, (int) b.length());
                        } else {
                            serialized_attr = rsMessageAttr.getBytes(1);
                        }
                        // this check is for better backwards compatibility
                        if (serialized_attr != null) {
                            ByteArrayInputStream bais = new ByteArrayInputStream(serialized_attr);
                            ObjectInputStream ois = new ObjectInputStream(bais);
                            attributes = (HashMap<String, Object>) ois.readObject();
                            ois.close();
                        }
                    } catch (IOException ioe) {
                        if (getLogger().isDebugEnabled()) {
                            String debugBuffer = "Exception reading attributes " + key + " in "
                                    + repositoryName;
                            getLogger().debug(debugBuffer, ioe);
                        }
                    }
                } else {
                    if (getLogger().isDebugEnabled()) {
                        String debugBuffer = "Did not find a record (attributes) " + key + " in "
                                + repositoryName;
                        getLogger().debug(debugBuffer);
                    }
                }
            } catch (SQLException sqle) {
                String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                        + sqle.getSQLState() + sqle.getNextException();
                getLogger().error(errorBuffer);
            } finally {
                theJDBCUtil.closeJDBCResultSet(rsMessageAttr);
                theJDBCUtil.closeJDBCStatement(retrieveMessageAttr);
            }
        }

        MailImpl mc = new MailImpl();
        mc.setAttributesRaw(attributes);
        mc.setName(key);
        mc.setState(rsMessage.getString(1));
        mc.setErrorMessage(rsMessage.getString(2));
        String sender = rsMessage.getString(3);
        if (sender == null) {
            mc.setSender(null);
        } else {
            mc.setSender(new MailAddress(sender));
        }
        StringTokenizer st = new StringTokenizer(rsMessage.getString(4), "\r\n", false);
        Set<MailAddress> recipients = new HashSet<MailAddress>();
        while (st.hasMoreTokens()) {
            recipients.add(new MailAddress(st.nextToken()));
        }
        mc.setRecipients(recipients);
        mc.setRemoteHost(rsMessage.getString(5));
        mc.setRemoteAddr(rsMessage.getString(6));
        mc.setLastUpdated(rsMessage.getTimestamp(7));

        MimeMessageJDBCSource source = new MimeMessageJDBCSource(this, key, sr);
        MimeMessageCopyOnWriteProxy message = new MimeMessageCopyOnWriteProxy(source);
        mc.setMessage(message);
        return mc;
    } catch (SQLException sqle) {
        String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                + sqle.getSQLState() + sqle.getNextException();
        getLogger().error(errorBuffer);
        getLogger().debug("Failed to retrieve mail", sqle);
        throw new MessagingException("Exception while retrieving mail: " + sqle.getMessage(), sqle);
    } catch (Exception me) {
        throw new MessagingException("Exception while retrieving mail: " + me.getMessage(), me);
    } finally {
        theJDBCUtil.closeJDBCResultSet(rsMessage);
        theJDBCUtil.closeJDBCStatement(retrieveMessage);
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:com.yahoo.dba.perf.myperf.springmvc.InnoController.java

@Override
protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    int status = Constants.STATUS_OK;
    String message = "OK";

    String group = req.getParameter("group");
    String host = req.getParameter("host");
    QueryParameters qps = new QueryParameters();
    qps.setGroup(group);//w  w  w . j a v  a2 s  .co m
    qps.setHost(host);
    qps.setSql("mysql_innodb_engine_status");

    ResultList rList = null;
    LinkedHashMap<String, ResultList> listMap = new LinkedHashMap<String, ResultList>();
    DBInstanceInfo dbinfo = null;
    DBConnectionWrapper connWrapper = null;
    try {
        dbinfo = this.frameworkContext.getDbInfoManager().findDB(group, host).copy();
        connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo);
        if (connWrapper == null) {
            status = Constants.STATUS_BAD;
            message = "failed to connect to target db (" + dbinfo + ")";
        } else {
            rList = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper,
                    qps.getMaxRows());
            logger.info("Done query " + qps.getSql() + " with " + (rList != null ? rList.getRows().size() : 0)
                    + " records.");
            if (rList != null && rList.getRows().size() > 0) {
                logger.info(rList.getRows().get(0).getColumns()
                        .get(rList.getRows().get(0).getColumns().size() - 1));
                listMap = parse(rList.getRows().get(0).getColumns()
                        .get(rList.getRows().get(0).getColumns().size() - 1));
            }
            WebAppUtil.closeDBConnection(req, connWrapper, false);
        }
    } catch (Throwable th) {
        logger.log(Level.SEVERE, "Exception", th);
        if (th instanceof SQLException) {
            SQLException sqlEx = SQLException.class.cast(th);
            String msg = th.getMessage();
            logger.info(sqlEx.getSQLState() + ", " + sqlEx.getErrorCode() + ", " + msg);
            //check if the connection is still good
            if (!DBUtils.checkConnection(connWrapper.getConnection())) {
                WebAppUtil.closeDBConnection(req, connWrapper, true);
            } else
                WebAppUtil.closeDBConnection(req, connWrapper, true);
        } else {
            if (connWrapper != null)
                WebAppUtil.closeDBConnection(req, connWrapper, false);
        }
        status = Constants.STATUS_BAD;
        message = "Exception: " + th.getMessage();
    } finally {
    }

    ModelAndView mv = new ModelAndView(this.jsonView);
    if (req.getParameter("callback") != null && req.getParameter("callback").trim().length() > 0)
        mv.addObject("callback", req.getParameter("callback"));//YUI datasource binding
    mv = new ModelAndView(this.jsonView);
    mv.addObject("json_result", ResultListUtil.toMultiListJSONStringUpper(listMap, qps, status, message));
    return mv;
}

From source file:org.cerberus.crud.dao.impl.TestCaseCountryPropertiesDAO.java

@Override
public Answer create(TestCaseCountryProperties object) {
    MessageEvent msg = null;/*w  w w .j a va2s.  c om*/
    StringBuilder query = new StringBuilder();
    query.append(
            "INSERT INTO testcasecountryproperties (`Test`,`TestCase`,`Country`,`Property`,`Description`,`Type`");
    query.append(",`Database`,`Value1`,`Value2`,`Length`,`RowLimit`,`Nature`,`RetryNb`,`RetryPeriod`) ");
    query.append("VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

    // Debug message on SQL.
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL : " + query.toString());
    }

    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            preStat.setString(1, object.getTest());
            preStat.setString(2, object.getTestCase());
            preStat.setString(3, object.getCountry());
            preStat.setString(4, object.getProperty());
            preStat.setString(5, object.getDescription());
            preStat.setString(6, object.getType());
            preStat.setString(7, object.getDatabase());
            preStat.setString(8, object.getValue1());
            preStat.setString(9, object.getValue2());
            preStat.setInt(10, object.getLength());
            preStat.setInt(11, object.getRowLimit());
            preStat.setString(12, object.getNature());
            preStat.setInt(13, object.getRetryNb());
            preStat.setInt(14, object.getRetryPeriod());

            preStat.executeUpdate();
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(
                    msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "INSERT"));

        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());

            if (exception.getSQLState().equals(SQL_DUPLICATED_CODE)) { //23000 is the sql state for duplicate entries
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_DUPLICATE);
                msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME)
                        .replace("%OPERATION%", "INSERT").replace("%REASON%", exception.toString()));
            } else {
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
            }
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException exception) {
            LOG.error("Unable to close connection : " + exception.toString());
        }
    }
    return new Answer(msg);
}