Java Code Examples for org.springframework.dao.DataAccessResourceFailureException

The following examples show how to use org.springframework.dao.DataAccessResourceFailureException. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: TemporaryLobCreator.java    License: 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 2
Source Project: spring-analysis-note   Source File: TemporaryLobCreator.java    License: 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 3
/**
 * 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 4
Source Project: java-technology-stack   Source File: TemporaryLobCreator.java    License: 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 5
Source Project: java-technology-stack   Source File: TemporaryLobCreator.java    License: 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 6
Source Project: java-technology-stack   Source File: TemporaryLobCreator.java    License: 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 7
/**
 * 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 8
Source Project: lams   Source File: HibernateTemplate.java    License: 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 9
Source Project: lams   Source File: TemporaryLobCreator.java    License: 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 10
Source Project: lams   Source File: TemporaryLobCreator.java    License: 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 11
Source Project: lams   Source File: TemporaryLobCreator.java    License: 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 12
/**
 * 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
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) {
		return;
	}

	EntityManagerFactory emf = obtainEntityManagerFactory();
	if (TransactionSynchronizationManager.hasResource(emf)) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, 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(emf, emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
			asyncManager.registerCallableInterceptor(key, interceptor);
			asyncManager.registerDeferredResultInterceptor(key, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
Example 14
Source Project: spring-analysis-note   Source File: OpenSessionInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * Open a Session for the given SessionFactory.
 * <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 to use
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @since 5.0
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = openSession();
	if (session == null) {
		try {
			session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.MANUAL);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
		}
	}
	return session;
}
 
Example 15
/**
 * 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 = obtainSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 16
Source Project: spring-analysis-note   Source File: OpenSessionInViewFilter.java    License: 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 17
Source Project: dubbox   Source File: SolrExceptionTranslator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex.getCause() instanceof SolrServerException) {
		SolrServerException solrServerException = (SolrServerException) ex.getCause();
		if (solrServerException.getCause() instanceof SolrException) {
			SolrException solrException = (SolrException) solrServerException.getCause();
			// solr 4.x moved ParseExecption from
			// org.apache.lucene.queryParser to
			// org.apache.lucene.queryparser.classic
			// therefore compare ShortClassName instead of using instanceof
			// expression
			if (solrException.getCause() != null && ClassUtils.getShortName(solrException.getCause().getClass())
					.equalsIgnoreCase("ParseException")) {
				return new InvalidDataAccessApiUsageException((solrException.getCause()).getMessage(),
						solrException.getCause());
			} else {
				ErrorCode errorCode = ErrorCode.getErrorCode(solrException.code());
				switch (errorCode) {
				case NOT_FOUND:
				case SERVICE_UNAVAILABLE:
				case SERVER_ERROR:
					return new DataAccessResourceFailureException(solrException.getMessage(), solrException);
				case FORBIDDEN:
				case UNAUTHORIZED:
					return new PermissionDeniedDataAccessException(solrException.getMessage(), solrException);
				case BAD_REQUEST:
					return new InvalidDataAccessApiUsageException(solrException.getMessage(), solrException);
				case UNKNOWN:
					return new UncategorizedSolrException(solrException.getMessage(), solrException);
				default:
					break;
				}
			}
		} else if (solrServerException.getCause() instanceof ConnectException) {
			return new DataAccessResourceFailureException(solrServerException.getCause().getMessage(),
					solrServerException.getCause());
		}
	}
	return null;
}
 
Example 18
@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 19
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof PersistenceException) {
		return new DataAccessResourceFailureException(ex.getMessage());
	}
	return null;
}
 
Example 20
@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 21
Source Project: spring-analysis-note   Source File: Jdbc4SqlXmlHandler.java    License: MIT License 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 22
Source Project: spring-analysis-note   Source File: Jdbc4SqlXmlHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void cleanup() {
	if (this.xmlObject != null) {
		try {
			this.xmlObject.free();
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not free SQLXML object", ex);
		}
	}
}
 
Example 23
@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 24
@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
@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 26
@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 [" +
					SessionFactoryUtils.toString(sessionHolder.getSession()) + "] for Hibernate transaction");
		}
		txObject.setSessionHolder(sessionHolder);
	}
	else if (this.hibernateManagedSession) {
		try {
			Session session = getSessionFactory().getCurrentSession();
			if (logger.isDebugEnabled()) {
				logger.debug("Found Hibernate-managed Session [" +
						SessionFactoryUtils.toString(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 27
Source Project: java-technology-stack   Source File: OpenSessionInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * Open a Session for the given SessionFactory.
 * <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 to use
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @since 5.0
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = openSession();
	if (session == null) {
		try {
			session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.MANUAL);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
		}
	}
	return session;
}
 
Example 28
/**
 * 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 = obtainSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 29
Source Project: java-technology-stack   Source File: OpenSessionInViewFilter.java    License: 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 30
@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;
}