org.springframework.dao.DataAccessResourceFailureException Java Examples

The following examples show how to use org.springframework.dao.DataAccessResourceFailureException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TemporaryLobCreator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setBlobAsBinaryStream(
		PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength)
		throws SQLException {

	if (binaryStream != null) {
		Blob blob = ps.getConnection().createBlob();
		try {
			FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryBlobs.add(blob);
		ps.setBlob(paramIndex, blob);
	}
	else {
		ps.setBlob(paramIndex, (Blob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(binaryStream != null ?
				"Copied binary stream into temporary BLOB with length " + contentLength :
				"Set BLOB to null");
	}
}
 
Example #2
Source File: TemporaryLobCreator.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void setBlobAsBinaryStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength)
		throws SQLException {

	if (binaryStream != null) {
		Blob blob = ps.getConnection().createBlob();
		try {
			FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryBlobs.add(blob);
		ps.setBlob(paramIndex, blob);
	}
	else {
		ps.setBlob(paramIndex, (Blob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(binaryStream != null ?
				"Copied binary stream into temporary BLOB with length " + contentLength :
				"Set BLOB to null");
	}
}
 
Example #3
Source File: TemporaryLobCreator.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void setClobAsAsciiStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream asciiStream, int contentLength)
		throws SQLException {

	if (asciiStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(asciiStream != null ?
				"Copied ASCII stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
Example #4
Source File: TemporaryLobCreator.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void setClobAsCharacterStream(
		PreparedStatement ps, int paramIndex, @Nullable Reader characterStream, int contentLength)
		throws SQLException {

	if (characterStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(characterStream, clob.setCharacterStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(characterStream != null ?
				"Copied character stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
Example #5
Source File: TemporaryLobCreator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setClobAsAsciiStream(
		PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength)
		throws SQLException {

	if (asciiStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(asciiStream != null ?
				"Copied ASCII stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
Example #6
Source File: AbstractSequenceMaxValueIncrementer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #7
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return a Session for use by this template.
 * <p>Returns a new Session in case of "alwaysUseNewSession" (using the same
 * JDBC Connection as a transactional Session, if applicable), a pre-bound
 * Session in case of "allowCreate" turned off, and a pre-bound or new Session
 * otherwise (new only if no transactional or otherwise pre-bound Session exists).
 * @return the Session to use (never {@code null})
 * @see SessionFactoryUtils#getSession
 * @see SessionFactoryUtils#getNewSession
 * @see #setAlwaysUseNewSession
 * @see #setAllowCreate
 */
protected Session getSession() {
	if (isAlwaysUseNewSession()) {
		return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
	}
	else if (isAllowCreate()) {
		return SessionFactoryUtils.getSession(
				getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
	}
	else if (SessionFactoryUtils.hasTransactionalSession(getSessionFactory())) {
		return SessionFactoryUtils.getSession(getSessionFactory(), false);
	}
	else {
		try {
			return getSessionFactory().getCurrentSession();
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex);
		}
	}
}
 
Example #8
Source File: TemporaryLobCreator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setClobAsCharacterStream(
		PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength)
		throws SQLException {

	if (characterStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(characterStream, clob.setCharacterStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(characterStream != null ?
				"Copied character stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
Example #9
Source File: TemporaryLobCreator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void setBlobAsBinaryStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength)
		throws SQLException {

	if (binaryStream != null) {
		Blob blob = ps.getConnection().createBlob();
		try {
			FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryBlobs.add(blob);
		ps.setBlob(paramIndex, blob);
	}
	else {
		ps.setBlob(paramIndex, (Blob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(binaryStream != null ?
				"Copied binary stream into temporary BLOB with length " + contentLength :
				"Set BLOB to null");
	}
}
 
Example #10
Source File: TemporaryLobCreator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void setClobAsAsciiStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream asciiStream, int contentLength)
		throws SQLException {

	if (asciiStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(asciiStream != null ?
				"Copied ASCII stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
Example #11
Source File: AbstractSequenceMaxValueIncrementer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #12
Source File: AbstractSequenceMaxValueIncrementer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #13
Source File: HibernateTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Object doGetTransaction() {
	HibernateTransactionObject txObject = new HibernateTransactionObject();
	txObject.setSavepointAllowed(isNestedTransactionAllowed());

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction");
		}
		txObject.setSessionHolder(sessionHolder);
	}
	else if (this.hibernateManagedSession) {
		try {
			Session session = this.sessionFactory.getCurrentSession();
			if (logger.isDebugEnabled()) {
				logger.debug("Found Hibernate-managed Session [" + session + "] for Spring-managed transaction");
			}
			txObject.setExistingSession(session);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException(
					"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
		}
	}

	if (getDataSource() != null) {
		ConnectionHolder conHolder = (ConnectionHolder)
				TransactionSynchronizationManager.getResource(getDataSource());
		txObject.setConnectionHolder(conHolder);
	}

	return txObject;
}
 
Example #14
Source File: OpenSessionInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example #15
Source File: OpenSessionInViewFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a Session for the SessionFactory that this filter uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	try {
		Session session = sessionFactory.openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example #16
Source File: OpenEntityManagerInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
		try {
			EntityManager em = createEntityManager();
			EntityManagerHolder emHolder = new EntityManagerHolder(em);
			TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example #17
Source File: SQLErrorCodeSQLExceptionTranslatorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void dataTruncationTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException dataAccessEx = new SQLException("", "", 5);
	DataTruncation dataTruncation = new DataTruncation(1, true, true, 1, 1, dataAccessEx);
	DataAccessResourceFailureException daex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataTruncation);
	assertEquals(dataTruncation, daex.getCause());
}
 
Example #18
Source File: Jdbc4SqlXmlHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setValue(PreparedStatement ps, int paramIndex) throws SQLException {
	this.xmlObject = ps.getConnection().createSQLXML();
	try {
		provideXml(this.xmlObject);
	}
	catch (IOException ex) {
		throw new DataAccessResourceFailureException("Failure encountered while providing XML", ex);
	}
	ps.setSQLXML(paramIndex, this.xmlObject);
}
 
Example #19
Source File: AbstractIdentityColumnMaxValueIncrementer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that @@identity
		* returns the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate(getIncrementStatement());
				ResultSet rs = stmt.executeQuery(getIdentityStatement());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("Identity statement failed after inserting");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			stmt.executeUpdate(getDeleteStatement(this.valueCache));
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example #20
Source File: SQLExceptionSubclassTranslator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
	if (ex instanceof SQLTransientException) {
		if (ex instanceof SQLTransientConnectionException) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTransactionRollbackException) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTimeoutException) {
			return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLNonTransientException) {
		if (ex instanceof SQLNonTransientConnectionException) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLDataException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLIntegrityConstraintViolationException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLInvalidAuthorizationSpecException) {
			return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLSyntaxErrorException) {
			return new BadSqlGrammarException(task, sql, ex);
		}
		else if (ex instanceof SQLFeatureNotSupportedException) {
			return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLRecoverableException) {
		return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex);
	}

	// Fallback to Spring's own SQL state translation...
	return null;
}
 
Example #21
Source File: OpenSessionInViewFilter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Open a Session for the SessionFactory that this filter uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	try {
		Session session = sessionFactory.openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example #22
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example #23
Source File: OpenSessionInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example #24
Source File: SQLErrorCodeSQLExceptionTranslatorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void errorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
Example #25
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example #26
Source File: SQLStateSQLExceptionTranslator.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
	// First, the getSQLState check...
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}

	// For MySQL: exception class name indicating a timeout?
	// (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
	if (ex.getClass().getName().contains("Timeout")) {
		return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
	}

	// Couldn't resolve anything proper - resort to UncategorizedSQLException.
	return null;
}
 
Example #27
Source File: AbstractIdentityColumnMaxValueIncrementer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that @@identity
		* returns the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate(getIncrementStatement());
				ResultSet rs = stmt.executeQuery(getIdentityStatement());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("Identity statement failed after inserting");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			stmt.executeUpdate(getDeleteStatement(this.valueCache));
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example #28
Source File: PersistenceExceptionTranslationPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof PersistenceException) {
		return new DataAccessResourceFailureException(ex.getMessage());
	}
	return null;
}
 
Example #29
Source File: PersistenceExceptionTranslationPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void proxiesCorrectly() {
	GenericApplicationContext gac = new GenericApplicationContext();
	gac.registerBeanDefinition("translator",
			new RootBeanDefinition(PersistenceExceptionTranslationPostProcessor.class));
	gac.registerBeanDefinition("notProxied", new RootBeanDefinition(RepositoryInterfaceImpl.class));
	gac.registerBeanDefinition("proxied", new RootBeanDefinition(StereotypedRepositoryInterfaceImpl.class));
	gac.registerBeanDefinition("classProxied", new RootBeanDefinition(RepositoryWithoutInterface.class));
	gac.registerBeanDefinition("classProxiedAndAdvised",
			new RootBeanDefinition(RepositoryWithoutInterfaceAndOtherwiseAdvised.class));
	gac.registerBeanDefinition("myTranslator",
			new RootBeanDefinition(MyPersistenceExceptionTranslator.class));
	gac.registerBeanDefinition("proxyCreator",
			BeanDefinitionBuilder.rootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class).
					addPropertyValue("order", 50).getBeanDefinition());
	gac.registerBeanDefinition("logger", new RootBeanDefinition(LogAllAspect.class));
	gac.refresh();

	RepositoryInterface shouldNotBeProxied = (RepositoryInterface) gac.getBean("notProxied");
	assertFalse(AopUtils.isAopProxy(shouldNotBeProxied));
	RepositoryInterface shouldBeProxied = (RepositoryInterface) gac.getBean("proxied");
	assertTrue(AopUtils.isAopProxy(shouldBeProxied));
	RepositoryWithoutInterface rwi = (RepositoryWithoutInterface) gac.getBean("classProxied");
	assertTrue(AopUtils.isAopProxy(rwi));
	checkWillTranslateExceptions(rwi);

	Additional rwi2 = (Additional) gac.getBean("classProxiedAndAdvised");
	assertTrue(AopUtils.isAopProxy(rwi2));
	rwi2.additionalMethod(false);
	checkWillTranslateExceptions(rwi2);
	try {
		rwi2.additionalMethod(true);
		fail("Should have thrown DataAccessResourceFailureException");
	}
	catch (DataAccessResourceFailureException ex) {
		assertEquals("my failure", ex.getMessage());
	}
}
 
Example #30
Source File: HibernateTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected Object doGetTransaction() {
	HibernateTransactionObject txObject = new HibernateTransactionObject();
	txObject.setSavepointAllowed(isNestedTransactionAllowed());

	SessionFactory sessionFactory = obtainSessionFactory();
	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
	if (sessionHolder != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction");
		}
		txObject.setSessionHolder(sessionHolder);
	}
	else if (this.hibernateManagedSession) {
		try {
			Session session = sessionFactory.getCurrentSession();
			if (logger.isDebugEnabled()) {
				logger.debug("Found Hibernate-managed Session [" + session + "] for Spring-managed transaction");
			}
			txObject.setExistingSession(session);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException(
					"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
		}
	}

	if (getDataSource() != null) {
		ConnectionHolder conHolder = (ConnectionHolder)
				TransactionSynchronizationManager.getResource(getDataSource());
		txObject.setConnectionHolder(conHolder);
	}

	return txObject;
}