Search in sources :

Example 56 with DataAccessException

use of org.springframework.dao.DataAccessException in project uPortal by Jasig.

the class HibernateStyleCounterStore method getNextIdInternal.

private int getNextIdInternal(final Optimizer optimizer, final String counterName) {
    return (Integer) optimizer.generate(new AccessCallback() {

        @Override
        public IntegralDataTypeHolder getNextValue() {
            IntegralDataTypeHolder rslt = null;
            for (int i = 0; rslt == null && i < MAX_ATTEMPTS; i++) {
                rslt = transactionOperations.execute(new TransactionCallback<IntegralDataTypeHolder>() {

                    @Override
                    public IntegralDataTypeHolder doInTransaction(TransactionStatus status) {
                        final IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder(identifierType.getReturnedClass());
                        // Try and load the current value,
                        // returns true if the expected row
                        // exists, null otherwise
                        final boolean selected = jdbcOperations.query(SELECT_QUERY, new ResultSetExtractor<Boolean>() {

                            @Override
                            public Boolean extractData(ResultSet rs) throws SQLException, DataAccessException {
                                if (rs.next()) {
                                    value.initialize(rs, 1);
                                    return true;
                                }
                                return false;
                            }
                        }, counterName);
                        // it
                        if (!selected) {
                            value.initialize(initialValue);
                            jdbcOperations.update(INSERT_QUERY, new PreparedStatementSetter() {

                                @Override
                                public void setValues(PreparedStatement ps) throws SQLException {
                                    ps.setString(1, counterName);
                                    value.bind(ps, 2);
                                }
                            });
                        }
                        // Increment the counter row value
                        final IntegralDataTypeHolder updateValue = value.copy();
                        if (optimizer.applyIncrementSizeToSourceValues()) {
                            updateValue.add(incrementSize);
                        } else {
                            updateValue.increment();
                        }
                        // Update the counter row, if rows
                        // returns 0 the update failed due to a
                        // race condition, it will be retried
                        int rowsAltered = jdbcOperations.update(UPDATE_QUERY, new PreparedStatementSetter() {

                            @Override
                            public void setValues(PreparedStatement ps) throws SQLException {
                                updateValue.bind(ps, 1);
                                ps.setString(2, counterName);
                                value.bind(ps, 3);
                            }
                        });
                        return rowsAltered > 0 ? // Success
                        value : // Failed;  try again...
                        null;
                    }
                });
            }
            if (rslt == null) {
                throw new RuntimeException("Failed to fetch a new batch of sequence values after " + MAX_ATTEMPTS + " tries");
            }
            return rslt;
        }
    });
}
Also used : SQLException(java.sql.SQLException) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) PreparedStatement(java.sql.PreparedStatement) AccessCallback(org.hibernate.id.enhanced.AccessCallback) TransactionCallback(org.springframework.transaction.support.TransactionCallback) ResultSet(java.sql.ResultSet) IntegralDataTypeHolder(org.hibernate.id.IntegralDataTypeHolder) DataAccessException(org.springframework.dao.DataAccessException)

Example 57 with DataAccessException

use of org.springframework.dao.DataAccessException in project camel by apache.

the class ElsqlSqlProcessingStrategy method commitBatchComplete.

@Override
public int commitBatchComplete(DefaultSqlEndpoint endpoint, NamedParameterJdbcTemplate namedJdbcTemplate, SqlParameterSource parameterSource, String query) throws Exception {
    final SqlParameterSource param = new EmptySqlParameterSource();
    final String sql = elSql.getSql(query, new SpringSqlParams(param));
    LOG.debug("commitBatchComplete @{} using sql: {}", query, sql);
    return namedJdbcTemplate.execute(sql, param, new PreparedStatementCallback<Integer>() {

        @Override
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();
            int updateCount = ps.getUpdateCount();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Update count {}", updateCount);
            }
            return updateCount;
        }
    });
}
Also used : EmptySqlParameterSource(org.springframework.jdbc.core.namedparam.EmptySqlParameterSource) SqlParameterSource(org.springframework.jdbc.core.namedparam.SqlParameterSource) SQLException(java.sql.SQLException) EmptySqlParameterSource(org.springframework.jdbc.core.namedparam.EmptySqlParameterSource) PreparedStatement(java.sql.PreparedStatement) DataAccessException(org.springframework.dao.DataAccessException) SpringSqlParams(com.opengamma.elsql.SpringSqlParams)

Example 58 with DataAccessException

use of org.springframework.dao.DataAccessException in project opennms by OpenNMS.

the class Correlation method format.

/**
 * Format the correlation block to have the xml
 *
 * @param ec
 *            the correlation
 * @param sz
 *            the size to which the formatted string is to be limited
 *            to(usually the size of the column in the database)
 * @return the formatted event correlation
 */
public static String format(final org.opennms.netmgt.xml.event.Correlation ec, final int sz) {
    StringWriter out = new StringWriter();
    try {
        JaxbUtils.marshal(ec, out);
    } catch (DataAccessException e) {
        LOG.error("Failed to convert new event to XML", e);
        return null;
    }
    String outstr = out.toString();
    if (outstr.length() >= sz) {
        final StringBuilder buf = new StringBuilder(outstr);
        buf.setLength(sz - 4);
        buf.append(EventDatabaseConstants.VALUE_TRUNCATE_INDICATOR);
        return buf.toString();
    } else {
        return outstr;
    }
}
Also used : StringWriter(java.io.StringWriter) DataAccessException(org.springframework.dao.DataAccessException)

Example 59 with DataAccessException

use of org.springframework.dao.DataAccessException in project camel by apache.

the class CallableStatementWrapperTest method shouldExecuteStoredProcedure.

@Test
public void shouldExecuteStoredProcedure() throws Exception {
    CallableStatementWrapper wrapper = new CallableStatementWrapper("SUBNUMBERS" + "(INTEGER ${header.v1},INTEGER ${header.v2},OUT INTEGER resultofsub)", factory);
    final Exchange exchange = createExchangeWithBody(null);
    exchange.getIn().setHeader("v1", 1);
    exchange.getIn().setHeader("v2", 2);
    wrapper.call(new WrapperExecuteCallback() {

        @Override
        public void execute(StatementWrapper statementWrapper) throws SQLException, DataAccessException {
            statementWrapper.populateStatement(null, exchange);
            Map resultOfQuery = (Map) statementWrapper.executeStatement();
            Assert.assertEquals(-1, resultOfQuery.get("resultofsub"));
        }
    });
}
Also used : Exchange(org.apache.camel.Exchange) SQLException(java.sql.SQLException) Map(java.util.Map) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Example 60 with DataAccessException

use of org.springframework.dao.DataAccessException in project jOOQ by jOOQ.

the class TransactionTest method testExplicitTransactions.

@Test
public void testExplicitTransactions() {
    boolean rollback = false;
    TransactionStatus tx = txMgr.getTransaction(new DefaultTransactionDefinition());
    try {
        // constraint violation exception
        for (int i = 0; i < 2; i++) dsl.insertInto(BOOK).set(BOOK.ID, 5).set(BOOK.AUTHOR_ID, 1).set(BOOK.TITLE, "Book 5").execute();
        Assert.fail();
    }// Upon the constraint violation, we explicitly roll back the transaction.
     catch (DataAccessException e) {
        txMgr.rollback(tx);
        rollback = true;
    }
    assertEquals(4, dsl.fetchCount(BOOK));
    assertTrue(rollback);
}
Also used : DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) TransactionStatus(org.springframework.transaction.TransactionStatus) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)89 SQLException (java.sql.SQLException)40 Test (org.junit.Test)26 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 MongoException (com.mongodb.MongoException)13 Document (org.bson.Document)8 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)5 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IOException (java.io.IOException)4 ConnectionCallback (org.springframework.jdbc.core.ConnectionCallback)4 SpringSqlParams (com.opengamma.elsql.SpringSqlParams)3 DatabaseMetaData (java.sql.DatabaseMetaData)3 Statement (java.sql.Statement)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)3