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:it.cnr.icar.eric.server.container.DerbyHelper.java

/**
 * Log appropriate information about a SQLException.  In some cases,
 * the exception may be a normal consequence of connecting to the
 * shutdown URL.  Logs something (message.stoppedDatabase at least) in
 * all cases./*w  w  w.ja v  a  2s.  c  o m*/
 *
 * @param sqlException the {@link java.sql.SQLException} which should
 * be discarded (as normal) or logged
 */
protected void logDatabaseException(SQLException sqlException) {
    // In general, we do not know much about what these exceptions mean
    if (log.isDebugEnabled()) {
        while (null != sqlException) {
            // ??? add a message for unrecognized SQL exceptions
            log.error(sqlException);
            log.debug("Error Code: " + sqlException.getErrorCode());
            log.debug("SQL State: " + sqlException.getSQLState());
            sqlException = sqlException.getNextException();
        }
    } else {
        // ??? add a message for unrecognized SQL exceptions
        log.error(sqlException);
    }
}

From source file:org.finra.dm.service.helper.DmErrorInformationExceptionHandler.java

/**
 * Returns {@code true} if the given throwable is or is not caused by a database constraint violation.
 *
 * @param exception - throwable to check.
 *
 * @return {@code true} if is constraint violation, {@code false} otherwise.
 *//*from   ww  w. j  a  v  a2 s  .c om*/
private boolean isCausedByConstraintViolationException(Exception exception) {
    // some databases will throw ConstraintViolationException
    boolean isConstraintViolation = ExceptionUtils.indexOfThrowable(exception,
            ConstraintViolationException.class) != -1;

    // other databases will not throw a nice exception
    if (!isConstraintViolation) {
        // We must manually check the error codes
        Throwable rootThrowable = getRootCause(exception);
        if (rootThrowable instanceof SQLException) {
            SQLException sqlException = (SQLException) rootThrowable;
            isConstraintViolation = POSTGRES_SQL_STATE_CODE_FOREIGN_KEY_VIOLATION
                    .equals(sqlException.getSQLState());
        }
    }
    return isConstraintViolation;
}

From source file:com.googlecode.fascinator.sequences.SequenceService.java

/**
 * Shuts down the plugin//w  w w. java2  s  .  c om
 * 
 * @throws AccessControlException
 *             if there was an error during shutdown
 */
public void shutdown() throws SQLException {
    // 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.error("Error during database shutdown:", ex);
                throw new SQLException("Error during database shutdown:", ex);
            }
        }
    } finally {
        try {
            // Close our connection
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException ex) {
            log.error("Error closing connection:", ex);
        }
    }
}

From source file:org.opendaylight.vtn.javaapi.resources.openstack.RoutesResource.java

/**
 * Handler method for POST operation of Route
 * //w ww . j a  v  a  2s. co m
 * @see org.opendaylight.vtn.javaapi.resources.AbstractResource#post(com
 *      .google.gson.JsonObject)
 */
@Override
public int post(JsonObject requestBody) {
    LOG.trace("Start RoutesResource#post()");

    int errorCode = UncResultCode.UNC_SERVER_ERROR.getValue();

    boolean isCommitRequired = false;
    String generatedRouteId = null;
    Connection connection = null;

    try {
        connection = VtnServiceInitManager.getDbConnectionPoolMap().getConnection();

        /*
         * Check for instances that they exists or not, if not then return
         * 404 error
         */
        if (checkForNotFoundResources(connection)) {

            generatedRouteId = convertRouteId(requestBody);

            StaticRouteBean staticRouteBean = new StaticRouteBean();
            staticRouteBean.setVtnName(getTenantId());
            staticRouteBean.setVrtName(getRouterId());
            staticRouteBean.setRouteName(generatedRouteId);

            StaticRouteDao stRouteDao = new StaticRouteDao();
            final int status = stRouteDao.insert(connection, staticRouteBean);
            if (status == 1) {
                LOG.info("Resource insertion successful at database operation.");

                final RestResource restResource = new RestResource();

                errorCode = createStaticRoute(requestBody, restResource);

                if (errorCode == UncCommonEnum.UncResultCode.UNC_SUCCESS.getValue()) {
                    LOG.info("static-route is successful at UNC.");
                    isCommitRequired = true;
                    final JsonObject response = new JsonObject();
                    response.addProperty(VtnServiceOpenStackConsts.ID, generatedRouteId);
                    setInfo(response);
                } else {
                    LOG.error("static-route creation is failed at UNC.");
                }
                checkForSpecificErrors(restResource.getInfo());
            } else {
                LOG.error("Resource insertion failed at database operation.");
            }
        } else {
            LOG.error("Resource not found error.");
        }

        /*
         * If all processing are OK, the commit all the database transaction
         * made for current connection. Otherwise do the roll-back
         */
        if (isCommitRequired) {
            // connection.commit();
            setOpenStackConnection(connection);
            LOG.info("Resource insertion successful in database.");
        } else {
            connection.rollback();
            LOG.info("Resource insertion is roll-backed.");
        }

        /*
         * set response, if it is not set during processing for create
         * tenant
         */
        if (errorCode != UncResultCode.UNC_SUCCESS.getValue()) {
            if (getInfo() == null) {
                createErrorInfo(UncResultCode.UNC_INTERNAL_SERVER_ERROR.getValue());
            }
        }
    } catch (final SQLException exception) {
        LOG.error(exception, "Internal server error : " + exception);
        errorCode = UncResultCode.UNC_SERVER_ERROR.getValue();
        if (exception.getSQLState().equalsIgnoreCase(VtnServiceOpenStackConsts.CONFLICT_SQL_STATE)) {
            LOG.error("Conflict found during creation of resource");
            createErrorInfo(UncResultCode.UNC_CONFLICT_FOUND.getValue(),
                    getCutomErrorMessage(UncResultCode.UNC_CONFLICT_FOUND.getMessage(),
                            VtnServiceOpenStackConsts.ROUTE_ID, generatedRouteId));
        } else {
            createErrorInfo(UncResultCode.UNC_INTERNAL_SERVER_ERROR.getValue());
        }
    } finally {
        if (connection != null && !isCommitRequired) {
            try {
                connection.rollback();
                LOG.info("roll-back successful.");
            } catch (final SQLException e) {
                LOG.error(e, "Rollback error : " + e);
            }
            LOG.info("Free connection...");
            VtnServiceInitManager.getDbConnectionPoolMap().freeConnection(connection);
        }
    }
    LOG.trace("Complete RoutesResource#post()");
    return errorCode;
}

From source file:seava.j4e.web.controller.AbstractBaseController.java

/**
 * Exception/*  ww w . j  a  va2s.c  o  m*/
 * 
 * @param e
 * @param response
 * @return
 * @throws IOException
 */
@ResponseBody
protected String handleManagedException(IErrorCode errorCode, Exception e, HttpServletResponse response,
        String outputType) throws IOException {

    IErrorCode err = errorCode;
    Map<String, String> result = new HashMap<String, String>();

    if (!(e instanceof BusinessException)) {
        e.printStackTrace();
    }
    if (err == null) {
        err = ErrorCode.G_RUNTIME_ERROR;
    }

    // if (e instanceof BusinessException) {
    // err = ((BusinessException) e).getErrorCode();
    // } else {
    // if (e.getCause() != null) {
    // Throwable t = e;
    // while (t.getCause() != null) {
    // t = t.getCause();
    // if (t instanceof BusinessException) {
    // err = ((BusinessException) t).getErrorCode();
    // break;
    // }
    // }
    // }
    // }

    result.put("err_group", err.getErrGroup());
    result.put("err_no", err.getErrNo() + "");
    result.put("err_msg", err.getErrMsg());

    // --------------------

    if (e.getCause() != null) {
        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
        }

        if (t instanceof SQLException) {
            SQLException sqlException = (SQLException) t;
            result.put("msg", sqlException.getErrorCode() + " - " + sqlException.getSQLState() + " - "
                    + sqlException.getLocalizedMessage());

        } else {
            result.put("msg", t.getMessage());
        }

    }

    // ---------------------

    if (!result.containsKey("msg")) {
        result.put("msg", e.getMessage());
    } else {
        result.put("details", e.getMessage());
    }

    StringBuffer sb = new StringBuffer();

    if (outputType.matches("txt")) {
        sb.append(result.get("err_group") + "-" + result.get("err_no") + "\n||\n");
        sb.append(result.get("err_msg") + "\n||\n");
        sb.append(result.get("msg") + "\n||\n");
        sb.append(result.get("details") + "\n||\n");
    } else if (outputType.matches("html")) {
        sb.append("<html><body><div>" + result.get("msg") + "</div></body></html>");
    }

    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    response.getOutputStream().print(sb.toString());
    return null;
}

From source file:com.splicemachine.derby.impl.load.HdfsUnsafeImportIT.java

@Test
public void testConstaintsImportNullBadDir() throws Exception {
    // DB-5017: When bad record dir is null or empty, the input file dir becomes the bad record dir
    String inputFileName = "constraintViolation.csv";
    String inputFileOrigin = getResourceDirectory() + inputFileName;
    // copy the given input file under a temp folder so that it will get cleaned up
    // this used to go under the "target/test-classes" folder but doesn't work when we execute test from
    // a different location.
    File newImportFile = tempFolder.newFile(inputFileName);
    FileUtils.copyFile(new File(inputFileOrigin), newImportFile);
    assertTrue("Import file copy failed: " + newImportFile.getCanonicalPath(), newImportFile.exists());
    String badFileName = newImportFile.getParent() + "/" + inputFileName + ".bad";

    PreparedStatement ps = methodWatcher
            .prepareStatement(format("call SYSCS_UTIL.IMPORT_DATA_UNSAFE(" + "'%s'," + // schema name
                    "'%s'," + // table name
                    "null," + // insert column list
                    "'%s'," + // file path
                    "','," + // column delimiter
                    "null," + // character delimiter
                    "null," + // timestamp format
                    "null," + // date format
                    "null," + // time format
                    "%d," + // max bad records
                    "null," + // bad record dir
                    "null," + // has one line records
                    "null)", // char set
                    spliceSchemaWatcher.schemaName, TABLE_20, newImportFile.getCanonicalPath(), 0));
    try {//from   w w w .  j a v a  2s .  c om
        ps.execute();
        fail("Too many bad records.");
    } catch (SQLException e) {
        assertEquals("Expected too many bad records, but got: " + e.getLocalizedMessage(), "SE009",
                e.getSQLState());
    }
    boolean exists = existsBadFile(new File(newImportFile.getParent()), inputFileName + ".bad");
    assertTrue("Bad file " + badFileName + " does not exist.", exists);
}

From source file:com.feedzai.commons.sql.abstraction.engine.impl.H2Engine.java

@Override
protected void dropTable(DbEntity entity) throws DatabaseEngineException {
    Statement drop = null;/* www .ja  va2 s.  c  om*/
    try {
        drop = conn.createStatement();
        final String query = format("DROP TABLE %s CASCADE", quotize(entity.getName()));
        logger.trace(query);
        drop.executeUpdate(query);
    } catch (SQLException ex) {
        if (ex.getSQLState().startsWith(TABLE_OR_VIEW_DOES_NOT_EXIST)) {
            logger.debug(dev, "Table '{}' does not exist", entity.getName());
            handleOperation(new OperationFault(entity.getName(), OperationFault.Type.TABLE_DOES_NOT_EXIST), ex);
        } else {
            throw new DatabaseEngineException("Error dropping table", ex);
        }
    } finally {
        try {
            if (drop != null) {
                drop.close();
            }
        } catch (Exception e) {
            logger.trace("Error closing statement.", e);
        }
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.impl.H2Engine.java

@Override
protected void dropColumn(DbEntity entity, String... columns) throws DatabaseEngineException {
    Statement drop = null;//from   w  w w  .  j  a v  a2  s .  c  o m

    try {
        drop = conn.createStatement();
        for (String column : columns) {
            final String query = format("ALTER TABLE %s DROP COLUMN %s", quotize(entity.getName()),
                    quotize(column));
            logger.trace(query);
            drop.executeUpdate(query);
        }
    } catch (SQLException ex) {
        if (ex.getSQLState().startsWith(TABLE_OR_VIEW_DOES_NOT_EXIST)) {
            logger.debug(dev, "Table '{}' does not exist", entity.getName());
            handleOperation(new OperationFault(entity.getName(), OperationFault.Type.COLUMN_DOES_NOT_EXIST),
                    ex);
        } else {
            throw new DatabaseEngineException("Error dropping column", ex);
        }
    } finally {
        try {
            if (drop != null) {
                drop.close();
            }
        } catch (Exception e) {
            logger.trace("Error closing statement.", e);
        }
    }

}

From source file:org.openbmp.db_rest.resources.Orr.java

/**
 * Run query to get the IGP for the given peer/routerId
 *
 * @param peerHashId      BGP peer hash id
 * @param routerId         Router ID (IPv4 or IPv6) printed form
 * @param protocol         Either 'ospf' or 'isis'
 * @param max_age         Maximum allowable age for cached IGP SPF
 *
 *
 * @returns Results are returned as a Map list of column definitions
 *       NULL will be returned if there was an error getting the RIB.
 *///from  w w w . j  a  v a  2  s .c  o m
Map<String, List<DbColumnDef>> getIGPRib(String peerHashId, String routerId, String protocol, int max_age) {

    String tableName = null;
    String spfProc = null;
    String route_type_field = "";

    if (protocol.equalsIgnoreCase("ospf")) {
        tableName = "igp_ospf_" + routerId.replace('.', '_');
        spfProc = "{call ls_ospf_spf(?, ?, ?,?)}";
        route_type_field = "ospf_route_type";
    } else if (protocol.equalsIgnoreCase("isis")) {
        tableName = "igp_isis_" + routerId.replace('.', '_');
        spfProc = "{call ls_isis_spf(?, ?, ?,?)}";
        route_type_field = "isis_type";
    }

    StringBuilder query = new StringBuilder();

    // first call stored procedure to generate the IGP/SPF table.
    Connection conn = null;
    CallableStatement cs = null;

    try {
        conn = mysql_ds.getConnection();
        cs = conn.prepareCall(spfProc);
        cs.setString(1, peerHashId);
        cs.setString(2, routerId);
        cs.setInt(3, max_age);
        cs.registerOutParameter(4, Types.INTEGER);

        cs.execute();

        System.out.println(" SPF iterations = " + cs.getInt(3));

        // WARNING: If changing the order or adding/removing columns to the below, make sure
        //    to update getIgpPrefixMetric() and mergeIgpWithBgp() - they expect column 6 to be the metric

        query.append("select igp.prefix as prefix,igp.prefix_len,\n");
        query.append("          concat('" + protocol + "') as protocol,\n");
        query.append("          l.neighbor_addr as NH,\n");
        query.append("          concat('') as ORR,\n");
        query.append(
                "           " + route_type_field + " as Type,igp.metric,n.igp_router_id as src_router_id,\n");
        query.append("           nei.igp_router_id as nei_router_id,\n");
        query.append("           igp.path_router_ids,igp.path_hash_ids,\n");
        query.append("           l.neighbor_addr as neighbor_addr,\n");
        query.append("           igp.peer_hash_id,p.router_hash_id\n");
        query.append("    FROM " + tableName + " igp JOIN ls_nodes n ON (igp.src_node_hash_id = n.hash_id)\n");
        query.append("            JOIN bgp_peers p ON (igp.peer_hash_id = p.hash_id)\n");
        query.append(
                "            JOIN ls_nodes nei ON (igp.nh_node_hash_id = nei.hash_id and nei.peer_hash_id = '"
                        + peerHashId + "')\n");
        query.append("            LEFT JOIN ls_links l ON (igp.nh_node_hash_id = l.remote_node_hash_id and\n");
        query.append(
                "                           igp.root_node_hash_id = l.local_node_hash_id and l.peer_hash_id = '"
                        + peerHashId + "')\n");
        query.append("    WHERE best = TRUE ");
        query.append("    GROUP BY igp.prefix,igp.prefix_len,l.neighbor_addr\n");

        System.out.println("QUERY: \n" + query.toString() + "\n");

    } catch (SQLException e) {
        if (e.getSQLState().equals("45000")) {
            System.out.println("Procedure returned error " + e.getErrorCode() + " : " + e.getMessage());
        } else {
            System.out.println("Error in query " + e.getErrorCode() + " : " + e.getMessage());
            e.printStackTrace();
        }
    } finally {
        try {
            if (cs != null)
                cs.close();
            if (conn != null)
                conn.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return DbUtils.select_DbToMap(mysql_ds, query.toString());
}

From source file:com.feedzai.commons.sql.abstraction.engine.impl.H2Engine.java

@Override
protected void addPrimaryKey(final DbEntity entity) throws DatabaseEngineException {
    if (entity.getPkFields().size() == 0) {
        return;/*from   w  w  w  . ja v a 2s.  c o m*/
    }

    List<String> pks = new ArrayList<String>();
    for (String pk : entity.getPkFields()) {
        pks.add(quotize(pk));
    }

    final String pkName = md5(format("PK_%s", entity.getName()), properties.getMaxIdentifierSize());

    List<String> statement = new ArrayList<String>();
    statement.add("ALTER TABLE");
    statement.add(quotize(entity.getName()));
    statement.add("ADD CONSTRAINT");
    statement.add(quotize(pkName));
    statement.add("PRIMARY KEY");
    statement.add("(" + join(pks, ", ") + ")");

    final String addPrimaryKey = join(statement, " ");

    logger.trace(addPrimaryKey);

    Statement s = null;
    try {
        s = conn.createStatement();
        s.executeUpdate(addPrimaryKey);
    } catch (SQLException ex) {
        if (ex.getSQLState().startsWith(TABLE_CAN_ONLY_HAVE_ONE_PRIMARY_KEY)
                || ex.getSQLState().startsWith(CONSTRAINT_NAME_ALREADY_EXISTS)) {
            logger.debug(dev, "'{}' already has a primary key", entity.getName());
            handleOperation(
                    new OperationFault(entity.getName(), OperationFault.Type.PRIMARY_KEY_ALREADY_EXISTS), ex);
        } else {
            throw new DatabaseEngineException("Something went wrong handling statement", ex);
        }
    } finally {
        try {
            if (s != null) {
                s.close();
            }
        } catch (Exception e) {
            logger.trace("Error closing statement.", e);
        }
    }
}