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.phoenix.util.ServerUtil.java

private static String constructSQLErrorMessage(SQLException e, String message) {
    return constructSQLErrorMessage(e.getErrorCode(), e.getSQLState(), e.getMessage() + " " + message);
}

From source file:org.jumpmind.db.platform.JdbcDatabasePlatformFactory.java

private static boolean isRedshiftDatabase(Connection connection) {
    boolean isRedshift = false;
    try {/*from   w w  w .j  av  a2  s .  c  o  m*/
        DatabaseMetaData dmd = connection.getMetaData();
        dmd.getMaxColumnsInIndex();
    } catch (SQLException ex) {
        if (ex.getSQLState().equals("99999")) {
            isRedshift = true;
        }
    }
    return isRedshift;
}

From source file:uk.ac.kcl.texthunter.utils.Utils.java

public static void shutdownDerby() {
    try {//from  ww  w  .j ava 2s.c o  m
        // the shutdown=true attribute shuts down Derby
        DriverManager.getConnection("jdbc:derby:;shutdown=true");
        // To shut down a specific database only, but keep the
        // engine running (for example for connecting to other
        // databases), specify a database in the connection URL:
        //DriverManager.getConnection("jdbc:derby:" + dbName + ";shutdown=true");
    } catch (SQLException se) {
        if (((se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState())))) {
            // we got the expected exception
            System.out.println("Derby shut down normally");
            // Note that for single database shutdown, the expected
            // SQL state is "08006", and the error code is 45000.
        } else {
            // if the error code or SQLState is different, we have
            // an unexpected exception (shutdown failed)
            System.err.println("Derby did not shut down normally");
            printSQLException(se);
        }
    }

}

From source file:org.nuxeo.ecm.core.storage.sql.SQLBinaryManager.java

protected static boolean isDuplicateKeyException(SQLException e) {
    String sqlState = e.getSQLState();
    if ("23000".equals(sqlState)) {
        // MySQL: Duplicate entry ... for key ...
        // Oracle: unique constraint ... violated
        // SQL Server: Violation of PRIMARY KEY constraint
        return true;
    }/*ww w.jav  a 2  s .  co  m*/
    if ("23001".equals(sqlState)) {
        // H2: Unique index or primary key violation
        return true;
    }
    if ("23505".equals(sqlState)) {
        // PostgreSQL: duplicate key value violates unique constraint
        return true;
    }
    if ("S0003".equals(sqlState) || "S0005".equals(sqlState)) {
        // SQL Server: Snapshot isolation transaction aborted due to update
        // conflict
        return true;
    }
    return false;
}

From source file:core.PlanC.java

/**
 * try to connect to local database. this method determine if an instance of this app is already running. in this
 * case, send {@link TPreferences#REQUEST_MAXIMIZE} message throwout internal comunication file (_.properties file)
 * to signal active instance to display main frame and this execution ends
 * /*  w  w  w. ja  va 2  s .c o m*/
 */
private static void connectToLocalDB() {
    // System.getProperties().put("connectTimeout", 10 * 1000);
    // System.getProperties().put("socketTimeout", 10 * 1000);
    try {
        ConnectionManager.connect();
    } catch (Exception e) {
        // if local db is lock, app is already running
        if (e instanceof SQLException) {
            SQLException se = (SQLException) e;
            if (se.getSQLState().equals("08001")) {
                TPreferences.sendMessage(TPreferences.REQUEST_MAXIMIZE, "true");
                System.exit(0);
            }
        }
        SystemLog.logException1(e, true);
        System.exit(-1);
    }
}

From source file:com.ndemyanovskyi.backend.DataManager.java

@SuppressWarnings("unchecked")
public static <R extends Rate> void writeRate(R rate, boolean updateIfExists) {
    Bank<R> bank = (Bank<R>) rate.getBank();
    String table = getTableName(bank, rate.getCurrency());
    try {/*from   ww  w  .  j ava2  s.com*/
        getDatabase().queryUpdate(bank.getDatabaseHelper().getInsertSql(table, rate));
    } catch (RuntimeSQLException ex) {
        SQLException sqlCause = Database.Utils.extractCause(ex);
        LOG.log(Level.SEVERE, "Rate(" + rate + ") does not writed: Message: " + ex);
        switch (sqlCause.getSQLState()) {

        case "23505": //Duplicate value
            if (updateIfExists) {
                getDatabase().queryUpdate(bank.getDatabaseHelper().getUpdateSql(table, rate));
            }
            break;

        case "42X05": //Table does not exists
            createTable(bank, rate.getCurrency());
            writeRate(rate, updateIfExists);
            break;

        }
    }
}

From source file:de.micromata.genome.jpa.EmgrFactory.java

/**
 * Convert exception./* w ww  . j  av  a 2  s  .  c  om*/
 *
 * @param ex the ex
 * @return the runtime exception
 */
public static RuntimeException convertException(RuntimeException ex) {
    if (ex instanceof QueryTimeoutException) {
        // this is a oracle/hibernate bug workouround.
        // hibernate think this is is a query timeout, but should a DataException
        if (ex.getCause() instanceof org.hibernate.QueryTimeoutException) {
            org.hibernate.QueryTimeoutException qto = (org.hibernate.QueryTimeoutException) ex.getCause();
            if (qto.getCause() instanceof SQLException) {
                SQLException sqlex = (SQLException) qto.getCause();
                // ORA-12899
                if (sqlex.getErrorCode() == 12899) {
                    return new DataPersistenceException(ex.getMessage(), qto.getSQL(), sqlex.getSQLState(), ex);
                }
            }
        }
    }
    if (ex instanceof PersistenceException) {
        Throwable cause = ex.getCause();
        if (cause instanceof ConstraintViolationException) {
            ConstraintViolationException cve = (ConstraintViolationException) cause;
            cve.getMessage();
            String sql = cve.getSQL();
            return new ConstraintPersistenceException(cve.getMessage(), sql, cve.getSQLState(),
                    cve.getConstraintName(), ex);
        } else if (cause instanceof DataException) {
            DataException dex = (DataException) cause;
            return new DataPersistenceException(ex.getMessage(), dex.getSQL(), dex.getSQLState(), ex);
        } else if (cause instanceof PropertyValueException) {
            if (StringUtils.startsWith(cause.getMessage(), "not-null ") == true) {
                return new NullableConstraintPersistenceException(ex.getMessage(), ex);
            }
        }
    }
    return ex;
}

From source file:com.mycompany.rproject.runnableClass.java

public static void use() throws IOException {
    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));

    AmazonSQS sqs = new AmazonSQSClient(awsCreds);

    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    sqs.setRegion(usWest2);/*from   w w w  .j av  a2s .  c  om*/
    String myQueueUrl = "https://sqs.us-west-2.amazonaws.com/711690152696/MyQueue";

    System.out.println("Receiving messages from MyQueue.\n");

    ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
    List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    while (messages.isEmpty()) {

        messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
    }

    String messageRecieptHandle = messages.get(0).getReceiptHandle();

    String a = messages.get(0).getBody();

    sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));

    //aqui opero y cuando acabe llamo para operar el siguiente.

    String n = "";
    String dbName = "mydb";
    String userName = "pmontojo";
    String password = "pmontojo";
    String hostname = "mydb.cued7orr1q2t.us-west-2.rds.amazonaws.com";
    String port = "3306";
    String jdbcUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password="
            + password;
    Connection conn = null;
    Statement setupStatement = null;
    Statement readStatement = null;
    ResultSet resultSet = null;
    String results = "";
    int numresults = 0;
    String statement = null;

    try {

        conn = DriverManager.getConnection(jdbcUrl);

        setupStatement = conn.createStatement();

        String insertUrl = "select video_name from metadata where id = " + a + ";";
        String checkUrl = "select url from metadata where id = " + a + ";";

        ResultSet rs = setupStatement.executeQuery(insertUrl);

        rs.next();

        System.out.println("este es el resultdo " + rs.getString(1));

        String names = rs.getString(1);
        ResultSet ch = setupStatement.executeQuery(checkUrl);
        ch.next();
        System.out.println("este es la url" + ch.getString(1));
        String urli = ch.getString(1);

        while (urli == null) {
            ResultSet sh = setupStatement.executeQuery(checkUrl);
            sh.next();
            System.out.println("este es la url" + sh.getString(1));
            urli = sh.getString(1);

        }
        setupStatement.close();
        AmazonS3 s3Client = new AmazonS3Client(awsCreds);

        S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, names));

        IOUtils.copy(object.getObjectContent(),
                new FileOutputStream(new File("/Users/paulamontojo/Desktop/download.avi")));

        putOutput();
        write();
        putInDb(sbu.toString(), a);

    } 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 {
        System.out.println("Closing the connection.");
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
    }

    use();

}

From source file:fi.ilmoeuro.membertrack.db.DataIntegrityException.java

public static @Nullable DataIntegrityException fromThrowable(Throwable throwable) {
    Throwable rootCause = ExceptionUtils.getRootCause(throwable);

    if (rootCause instanceof SQLException) {
        SQLException sqle = (SQLException) rootCause;
        String constraint = "";
        String message = sqle.getMessage();
        if (message != null) {
            Matcher matcher = CONSTRAINT_REGEX.matcher(message);

            if (matcher.find()) {
                String group = matcher.group(1);
                if (group != null) {
                    constraint = group;/*from ww  w . java 2 s.com*/
                }
            }
        }

        for (IntegrityViolation errorType : IntegrityViolation.values()) {
            if (errorType.errorCodes.contains(sqle.getSQLState())) {
                return new DataIntegrityException(errorType, constraint, throwable);
            }
        }
    }

    return null;
}

From source file:uk.ac.kcl.texthunter.utils.Utils.java

public static void printSQLException(SQLException e) {
    // Unwraps the entire exception chain to unveil the real cause of the
    // Exception.
    while (e != null) {
        System.err.println("\n----- SQLException -----");
        System.err.println("  SQL State:  " + e.getSQLState());
        System.err.println("  Error Code: " + e.getErrorCode());
        System.err.println("  Message:    " + e.getMessage());
        // for stack traces, refer to derby.log or uncomment this:
        //e.printStackTrace(System.err);
        e = e.getNextException();/*from w  w  w .j  av  a2s.  co m*/
    }
}