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.apache.openmeetings.web.pages.install.TestInstall.java

public static void resetDerbyHome() {
    try {/*from  w  w  w.j a v a2 s.com*/
        DriverManager.getConnection("jdbc:derby:;shutdown=true");
    } catch (SQLException e) {
        if ("XJ015".equals(e.getSQLState()) && 50000 == e.getErrorCode()) {
            log.info("Derby shutdown successfully");
        } else {
            log.error("Fail to shutdown Derby", e);
        }
    }
    System.getProperties().remove(DERBY_HOME);
}

From source file:org.bibsonomy.util.ExceptionUtils.java

/**
 * Like the name suggests this method logs an error and throws a
 * RuntimeException attached with the initial exception.
 * @param log the logger instance to use
 * @param ex the exception to log an rethrow wrapped
 * @param error message of the new RuntimeException
 * @throws RuntimeException the resulting exception
 *//*from   ww w. j a  v  a  2s .c o m*/
public static void logErrorAndThrowRuntimeException(final Log log, final Exception ex, final String error)
        throws RuntimeException {
    log.error(error + " - throwing RuntimeException" + ((ex != null) ? ("\n" + ex.toString()) : ""), ex);
    /*
     * Inserted to get more information (e.g., on "java.sql.SQLException: Unknown error" messages)
     * FIXME: it's probably not the best place to handle SQL stuff
     */
    if (ex != null && ex.getCause() != null && ex.getCause().getClass().equals(SQLException.class)) {
        final SQLException sqlException = ((SQLException) ex);
        log.error("SQL error code: " + sqlException.getErrorCode() + ", SQL state: "
                + sqlException.getSQLState());
    }
    throw new RuntimeException(error, ex);
}

From source file:org.apache.hadoop.vertica.AllTests.java

public static void configure() {
    if (run_tests) {
        return;//from   w ww  .  j  ava  2 s.com
    }

    Properties properties = System.getProperties();

    String test_setup = properties.getProperty("vertica.test_setup", "vertica_test.sql");
    hostname = properties.getProperty("vertica.hostname", VERTICA_HOSTNAME);
    username = properties.getProperty("vertica.username", VERTICA_USERNAME);
    password = properties.getProperty("vertica.password", VERTICA_PASSWORD);
    database = properties.getProperty("vertica.database", VERTICA_DATABASE);

    LOG.info("Inititializing database with " + test_setup);
    try {
        Class.forName(VerticaConfiguration.VERTICA_DRIVER_CLASS);
        String url = "jdbc:vertica://" + hostname + ":5433/" + database + "?user=" + username + "&password="
                + password;
        LOG.info("Conencting to " + url);
        Connection conn = DriverManager.getConnection(url);
        Statement stmt = conn.createStatement();

        InputStream strm_cmds = new FileInputStream(test_setup);

        if (strm_cmds != null) {
            byte[] b = new byte[strm_cmds.available()];
            strm_cmds.read(b);
            String[] cmds = new String(b).split("\n");

            StringBuffer no_comment = new StringBuffer();
            for (String cmd : cmds) {
                if (!cmd.startsWith("--"))
                    no_comment.append(cmd).append("\n");
            }

            for (String cmd : no_comment.toString().split(";")) {
                LOG.debug(cmd);
                try {
                    stmt.execute(cmd);
                } catch (SQLException e) {
                    LOG.debug(e.getSQLState() + " : " + e.getMessage());
                    if (e.getSQLState().equals("42V01"))
                        continue;
                    else
                        throw new RuntimeException(e);
                }

            }

            run_tests = true;
        }
    } catch (ClassNotFoundException e) {
        LOG.warn("No vertica driver found: " + e.getMessage() + " - skipping vertica tests");
    } catch (SQLException e) {
        LOG.warn("Could not connect to vertica database: " + e.getMessage() + " - skipping vertica tests");
    } catch (IOException e) {
        LOG.warn("Missing vertica test setup file " + test_setup + ": " + e.getMessage()
                + " - skipping vertica tests");
    }
}

From source file:info.extensiblecatalog.OAIToolkit.db.DButil.java

private static void logException(SQLException sqlex, String sql) {
    prglog.error("[PRG] SQLException with " + "SQLState='" + sqlex.getSQLState() + "' and " + "errorCode="
            + sqlex.getErrorCode() + " and " + "message=" + sqlex.getMessage() + "; sql was '" + sql + "'"
            + " open/total: " + connectionCounter + "/" + connectionCounterTotal);
}

From source file:it.itis.pertini.falessi.tunes.services.AbstractService.java

protected static ErrorMessage toErrorMessage(SQLException e) {
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.setErrorCode(e.getErrorCode());
    errorMessage.setSqlState(e.getSQLState());

    StringWriter stringWriter = new StringWriter();
    e.printStackTrace(new PrintWriter(stringWriter));
    errorMessage.setStackTrace(stringWriter.toString());

    return errorMessage;
}

From source file:com.google.gerrit.server.schema.H2AccountPatchReviewStore.java

private static String getSQLState(SQLException err) {
    String ec;/*  w  w  w . j a v a  2  s.  c  o  m*/
    SQLException next = err;
    do {
        ec = next.getSQLState();
        next = next.getNextException();
    } while (ec == null && next != null);
    return ec;
}

From source file:io.cloudslang.content.database.utils.SQLUtils.java

public static String toString(SQLException e) {
    String curr = exceptionToString(e) + "\nstate:" + e.getSQLState();
    while ((e = e.getNextException()) != null)
        curr += "\n\n" + exceptionToString(e) + "\nstate:" + e.getSQLState();
    return curr;//from   w  ww  . j  av a2 s .com
}

From source file:io.cloudslang.content.database.utils.SQLUtils.java

/**
 * Some databases (Sybase) throw exceptions during a database restore. This function processes that exception, and if it is that type, builds up the output of the command
 *
 * @param e The exception to analyze//from ww w . j a va  2s  .  co  m
 * @return The output of the dump command
 * @throws java.sql.SQLException If it was not a successful load command's exception.
 */
public static String processLoadException(SQLException e) throws SQLException {
    final String sqlState = e.getSQLState();
    if (sqlState != null && StringUtils.equalsIgnoreCase(sqlState, "s1000")) {
        SQLException f = e;
        StringBuilder s = new StringBuilder();
        s.append(f.getMessage());
        while ((f = f.getNextException()) != null)
            s.append("\n").append(f.getMessage());
        String str = s.toString();
        if (StringUtils.containsIgnoreCase(str, "load is complete"))
            return str;
    }
    throw e;
}

From source file:org.rti.zcore.dar.dao.PatientSearchDAO.java

/**
 * provides search results to Home page search using jstl ResultSupport.toResult(rs);
 * displays only the first 25 rows - no paging.
 * @param conn/*from  w  ww  .j a  va2  s  .  co  m*/
 * @param site
 * @param searchString
 * @param offset
 * @param maxRows
 * @param searchType - if searchType = "firstSurname", do search on first letters of surname; otherwise, searchtype is "keyword" and perform keyword search.
 * @param filter - display only patients in labour. Uses filterflow sql, below.
 * @param username
 * @return
 * @throws ServletException
 */
public static List getResults(Connection conn, String site, String searchString, int offset, int maxRows,
        String searchType, int filter, String username) throws ServletException {

    /*ResultSet rs = null;
    Result results = null;*/
    List results = null;
    ArrayList values = new ArrayList();
    String sql = "";
    //String ageCalc = DatabaseCompatability.ageCalc();
    String ageCalc = "integer(floor({fn TIMESTAMPDIFF(SQL_TSI_YEAR, birthdate, CURRENT_DATE)}))";
    // some names have a "'" in them; also prevent bad chars from messing up the sql.
    String filteredString = StringManipulation.escapeString(searchString);

    sql = "SELECT p.id, p.first_name AS firstName,p.surname,\n"
            + "p.district_patient_id AS districtPatientid, p.last_modified_by AS lastModifiedBy, "
            + "p.last_modified AS lastModified, p.site_id AS siteId, p.age_at_first_visit AS ageAtFirstVisit, "
            + "s.site_name AS siteName, " + ageCalc
            + " AS age, pr.STREET_ADDRESS_1 AS address1, pr.STREET_ADDRESS_2 AS address2,\n"
            + "pr.age_category AS sequenceNumber\n";
    sql = sql + "FROM patient p\n";
    sql = sql + "LEFT JOIN (encounter e) ON (e.patient_id = p.id AND e.form_id=1)\n"
            + "LEFT JOIN (patientregistration pr) ON (pr.id = e.id)\n" +
            // "JOIN (patient_status ps) ON (ps.id = p.id)\n" +
            // "LEFT JOIN (" + Constants.USERINFO_TABLE + " u) ON (u." + Constants.USERINFO_USERNAME +" = ps.last_modified_by)\n" +
            "LEFT JOIN (site s) ON (s.id= p.site_id)\n";

    if (!site.equals("all")) {
        /*sql = sql + "WHERE s.id = " + site + "\n";
        if (filter == 1) {
        sql = sql + filterFlow;
        }*/
        sql = sql + "WHERE p.site_id = ?\n";
        //sql = sql + "WHERE p.site_id = " + site + "\n";
        Long siteId = Long.valueOf(site);
        values.add(siteId);
    }
    if (searchType.equals("firstSurname") & site.equals("all")) {
        sql = sql + "WHERE ";
    } else if (searchType.equals("firstSurname") & !site.equals("all")) {
        sql = sql + "AND ";
    }
    if (searchType.equals("firstSurname")) {
        sql = sql + "    p.surname like '" + filteredString + "%' \n";
        sql = sql + "ORDER BY p.surname, p.first_name\n";
    } else {
        if (!filteredString.equals("") & site.equals("all")) {
            sql = sql + "WHERE ";
        } else if (!filteredString.equals("") & !site.equals("all")) {
            sql = sql + "AND ";
        }
        if (!filteredString.equals("")) {
            sql = sql + " (LOWER(p.surname) like ?\n" + "    OR LOWER(p.first_name) like ?\n"
                    + "    OR LOWER(p.district_patient_id) like ?)\n";
            values.add("%" + filteredString + "%");
            values.add("%" + filteredString + "%");
            values.add("%" + filteredString + "%");
        }

        if (filteredString.equals("")) {
            sql = sql + "ORDER BY p.last_modified DESC \n";
        } else {
            sql = sql + "ORDER BY p.surname, p.first_name \n";
        }
    }
    //sql = sql +  "LIMIT " + offset + "," + rowCount +";";
    sql = sql + " OFFSET " + offset + " ROWS FETCH NEXT " + maxRows + " ROWS ONLY";

    /*try {
    Statement s = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    s.setMaxRows(200);
            
    //s.setFetchSize(offset);
    rs = s.executeQuery(sql);
    results = ResultSupport.toResult(rs);
    rs.close();
    }  catch (Exception ex) {
    log.info("Search sql: " + sql);
    log.error(ex);
    throw new ServletException("Cannot retrieve results:", ex);
    }*/

    try {
        //results = DatabaseUtils.getList(conn, Patient.class, sql, values, 20);
        results = DatabaseUtils.getList(conn, Patient.class, sql, values);
    } catch (SQLException ex) {
        log.info("Search sql: " + sql);
        log.info("SQL State: " + ex.getSQLState());
        log.info("Error Code: " + ex.getErrorCode());
        log.error(ex);
        String mmessage = "SQL State: " + ex.getSQLState() + " Error Code: " + ex.getErrorCode();
        throw new ServletException("Cannot retrieve results. SQL errors: " + mmessage, ex);
    } catch (Exception ex) {
        log.info("Search sql: " + sql);
        log.error(ex);
        throw new ServletException("Cannot retrieve results:", ex);
    }
    return results;
}

From source file:ch.systemsx.cisd.openbis.generic.server.business.bo.DataAccessExceptionTranslator.java

private final static void throwExceptionWithMsg(final DataAccessException exception, final String subject,
        final EntityKind entityKindOrNull) throws UserFailureException {
    assert exception != null : "DataAccessException not specified.";
    final SQLException sqlException = SQLStateUtils.tryGetNextExceptionWithNonNullState(exception);
    Throwable throwable = exception;
    if (sqlException != null) {
        final String sqlState = sqlException.getSQLState();
        assert sqlState != null : "SQL state is null";
        if (SQLStateUtils.isUniqueViolation(sqlState)) {
            throw new UserFailureException(String.format(UNIQUE_VIOLATION_FORMAT, subject), exception);
        } else if (SQLStateUtils.isForeignKeyViolation(sqlState)) {
            throwForeignKeyViolationException(subject, entityKindOrNull, exception);
        } else {//from  w ww. j a  v  a2 s .c o m
            throwable = sqlException;
        }
    }
    throw new UserFailureException(throwable.getMessage(), exception);
}