org.springframework.transaction.CannotCreateTransactionException Java Examples

The following examples show how to use org.springframework.transaction.CannotCreateTransactionException. 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: DataSourceTransactionManagerTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example #2
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example #3
Source File: JdbcTransactionObjectSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * This implementation creates a JDBC 3.0 Savepoint and returns it.
 * @see java.sql.Connection#setSavepoint
 */
@Override
public Object createSavepoint() throws TransactionException {
	ConnectionHolder conHolder = getConnectionHolderForSavepoint();
	try {
		if (!conHolder.supportsSavepoints()) {
			throw new NestedTransactionNotSupportedException(
					"Cannot create a nested transaction because savepoints are not supported by your JDBC driver");
		}
		if (conHolder.isRollbackOnly()) {
			throw new CannotCreateTransactionException(
					"Cannot create savepoint for transaction which is already marked as rollback-only");
		}
		return conHolder.createSavepoint();
	}
	catch (SQLException ex) {
		throw new CannotCreateTransactionException("Could not create JDBC savepoint", ex);
	}
}
 
Example #4
Source File: JdbcTransactionObjectSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation creates a JDBC 3.0 Savepoint and returns it.
 * @see java.sql.Connection#setSavepoint
 */
@Override
public Object createSavepoint() throws TransactionException {
	ConnectionHolder conHolder = getConnectionHolderForSavepoint();
	try {
		if (!conHolder.supportsSavepoints()) {
			throw new NestedTransactionNotSupportedException(
					"Cannot create a nested transaction because savepoints are not supported by your JDBC driver");
		}
		if (conHolder.isRollbackOnly()) {
			throw new CannotCreateTransactionException(
					"Cannot create savepoint for transaction which is already marked as rollback-only");
		}
		return conHolder.createSavepoint();
	}
	catch (SQLException ex) {
		throw new CannotCreateTransactionException("Could not create JDBC savepoint", ex);
	}
}
 
Example #5
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example #6
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example #7
Source File: SpringTransactionManager.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
    if (definition.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_UNCOMMITTED)
        throw new InvalidIsolationLevelException("Ignite does not support READ_UNCOMMITTED isolation level.");

    IgniteTransactionObject txObj = (IgniteTransactionObject)transaction;
    Transaction tx = null;

    try {
        if (txObj.getTransactionHolder() == null || txObj.getTransactionHolder().isSynchronizedWithTransaction()) {
            long timeout = ignite.configuration().getTransactionConfiguration().getDefaultTxTimeout();

            if (definition.getTimeout() > 0)
                timeout = TimeUnit.SECONDS.toMillis(definition.getTimeout());

            Transaction newTx = ignite.transactions().txStart(transactionConcurrency,
                convertToIgniteIsolationLevel(definition.getIsolationLevel()), timeout, 0);

            if (log.isDebugEnabled())
                log.debug("Started Ignite transaction: " + newTx);

            txObj.setTransactionHolder(new IgniteTransactionHolder(newTx), true);
        }

        txObj.getTransactionHolder().setSynchronizedWithTransaction(true);
        txObj.getTransactionHolder().setTransactionActive(true);

        tx = txObj.getTransactionHolder().getTransaction();

        // Bind the session holder to the thread.
        if (txObj.isNewTransactionHolder())
            TransactionSynchronizationManager.bindResource(this.ignite, txObj.getTransactionHolder());
    }
    catch (Exception ex) {
        if (tx != null)
            tx.close();

        throw new CannotCreateTransactionException("Could not create Ignite transaction", ex);
    }
}
 
Example #8
Source File: JdbcTransactionObjectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This implementation creates a JDBC 3.0 Savepoint and returns it.
 * @see java.sql.Connection#setSavepoint
 */
@Override
public Object createSavepoint() throws TransactionException {
	ConnectionHolder conHolder = getConnectionHolderForSavepoint();
	try {
		if (!conHolder.supportsSavepoints()) {
			throw new NestedTransactionNotSupportedException(
					"Cannot create a nested transaction because savepoints are not supported by your JDBC driver");
		}
		return conHolder.createSavepoint();
	}
	catch (SQLException ex) {
		throw new CannotCreateTransactionException("Could not create JDBC savepoint", ex);
	}
}
 
Example #9
Source File: JtaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation returns a JtaTransactionObject instance for the
 * JTA UserTransaction.
 * <p>The UserTransaction object will either be looked up freshly for the
 * current transaction, or the cached one looked up at startup will be used.
 * The latter is the default: Most application servers use a shared singleton
 * UserTransaction that can be cached. Turn off the "cacheUserTransaction"
 * flag to enforce a fresh lookup for every transaction.
 * @see #setCacheUserTransaction
 */
@Override
protected Object doGetTransaction() {
	UserTransaction ut = getUserTransaction();
	if (ut == null) {
		throw new CannotCreateTransactionException("No JTA UserTransaction available - " +
				"programmatic PlatformTransactionManager.getTransaction usage not supported");
	}
	if (!this.cacheUserTransaction) {
		ut = lookupUserTransaction(
				this.userTransactionName != null ? this.userTransactionName : DEFAULT_USER_TRANSACTION_NAME);
	}
	return doGetJtaTransaction(ut);
}
 
Example #10
Source File: AbstractTransactionAspectTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Simulate a transaction infrastructure failure.
 * Shouldn't invoke target method.
 */
@Test
public void cannotCreateTransaction() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	Method m = getNameMethod;
	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(m, txatt);

	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// Expect a transaction
	CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
	given(ptm.getTransaction(txatt)).willThrow(ex);

	TestBean tb = new TestBean() {
		@Override
		public String getName() {
			throw new UnsupportedOperationException(
					"Shouldn't have invoked target method when couldn't create transaction for transactional method");
		}
	};
	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	try {
		itb.getName();
		fail("Shouldn't have invoked method");
	}
	catch (CannotCreateTransactionException thrown) {
		assertTrue(thrown == ex);
	}
}
 
Example #11
Source File: JdbcTransactionObjectSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation creates a JDBC 3.0 Savepoint and returns it.
 * @see java.sql.Connection#setSavepoint
 */
@Override
public Object createSavepoint() throws TransactionException {
	ConnectionHolder conHolder = getConnectionHolderForSavepoint();
	try {
		if (!conHolder.supportsSavepoints()) {
			throw new NestedTransactionNotSupportedException(
					"Cannot create a nested transaction because savepoints are not supported by your JDBC driver");
		}
		return conHolder.createSavepoint();
	}
	catch (SQLException ex) {
		throw new CannotCreateTransactionException("Could not create JDBC savepoint", ex);
	}
}
 
Example #12
Source File: HerdCommandInvokerTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test(expected = CannotCreateTransactionException.class)
public void testExecuteWithExceptionAndGetCreateTransactionException()
{
    // Mock dependencies.
    CommandConfig config = mock(CommandConfig.class);
    ExecuteAsyncJobCmd command = mock(ExecuteAsyncJobCmd.class);
    doThrow(CannotCreateTransactionException.class).when(command).execute(any());
    herdCommandInvoker.execute(config, command);
}
 
Example #13
Source File: JtaTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * This implementation returns a JtaTransactionObject instance for the
 * JTA UserTransaction.
 * <p>The UserTransaction object will either be looked up freshly for the
 * current transaction, or the cached one looked up at startup will be used.
 * The latter is the default: Most application servers use a shared singleton
 * UserTransaction that can be cached. Turn off the "cacheUserTransaction"
 * flag to enforce a fresh lookup for every transaction.
 * @see #setCacheUserTransaction
 */
@Override
protected Object doGetTransaction() {
	UserTransaction ut = getUserTransaction();
	if (ut == null) {
		throw new CannotCreateTransactionException("No JTA UserTransaction available - " +
				"programmatic PlatformTransactionManager.getTransaction usage not supported");
	}
	if (!this.cacheUserTransaction) {
		ut = lookupUserTransaction(
				this.userTransactionName != null ? this.userTransactionName : DEFAULT_USER_TRANSACTION_NAME);
	}
	return doGetJtaTransaction(ut);
}
 
Example #14
Source File: BusinessResourceTransactionManager.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
@Override
public TransactionStatus getTransaction(TransactionDefinition definition)
		throws TransactionException {
	TransactionStatus status = super.getTransaction(definition);
	try {
		TransactionResourceManager.initSynchronization();
		triggerBegin(status);
	} catch (Throwable e) {
		throw new CannotCreateTransactionException(
				"Unable to open the transaction", e);
	}
	return status;
}
 
Example #15
Source File: ResourceAndSimpleDSTransactionManager.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation sets the isolation level but ignores the timeout.
 */
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
	super.doBegin(transaction, definition);
	try {
		TransactionResourceManager.initSynchronization();
		triggerBegin();
	} catch (Throwable e) {
		throw new CannotCreateTransactionException(
				"Unable to begin the transaction", e);
	}
}
 
Example #16
Source File: DataSourceUtils.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
public static void doBegin(Connection con, DataSource dataSource) {
	try {
		if (con.getAutoCommit()) {
			if (logger.isDebugEnabled()) {
				logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
			}
			con.setAutoCommit(false);
		}
	}
	catch (Throwable ex) {
		DataSourceUtils.releaseConnection(con);
		throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
	}
}
 
Example #17
Source File: JdbcTransactionObjectSupport.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation creates a JDBC 3.0 Savepoint and returns it.
 * @see java.sql.Connection#setSavepoint
 */
@Override
public Object createSavepoint() throws TransactionException {
	ConnectionHolder conHolder = getConnectionHolderForSavepoint();
	try {
		if (!conHolder.supportsSavepoints()) {
			throw new NestedTransactionNotSupportedException(
					"Cannot create a nested transaction because savepoints are not supported by your JDBC driver");
		}
		return conHolder.createSavepoint();
	}
	catch (SQLException ex) {
		throw new CannotCreateTransactionException("Could not create JDBC savepoint", ex);
	}
}
 
Example #18
Source File: AbstractCompensatingTransactionManagerDelegate.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
public void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
	try {
		CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction;
		if (txObject.getHolder() == null) {
			CompensatingTransactionHolderSupport contextHolder = getNewHolder();
			txObject.setHolder(contextHolder);

			TransactionSynchronizationManager.bindResource(getTransactionSynchronizationKey(), contextHolder);
		}
	}
	catch (Exception e) {
		throw new CannotCreateTransactionException("Could not create DirContext instance for transaction", e);
	}
}
 
Example #19
Source File: JtaTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * This implementation returns a JtaTransactionObject instance for the
 * JTA UserTransaction.
 * <p>The UserTransaction object will either be looked up freshly for the
 * current transaction, or the cached one looked up at startup will be used.
 * The latter is the default: Most application servers use a shared singleton
 * UserTransaction that can be cached. Turn off the "cacheUserTransaction"
 * flag to enforce a fresh lookup for every transaction.
 * @see #setCacheUserTransaction
 */
@Override
protected Object doGetTransaction() {
	UserTransaction ut = getUserTransaction();
	if (ut == null) {
		throw new CannotCreateTransactionException("No JTA UserTransaction available - " +
				"programmatic PlatformTransactionManager.getTransaction usage not supported");
	}
	if (!this.cacheUserTransaction) {
		ut = lookupUserTransaction(
				this.userTransactionName != null ? this.userTransactionName : DEFAULT_USER_TRANSACTION_NAME);
	}
	return doGetJtaTransaction(ut);
}
 
Example #20
Source File: JpaTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object createSavepoint() throws TransactionException {
	if (getEntityManagerHolder().isRollbackOnly()) {
		throw new CannotCreateTransactionException(
				"Cannot create savepoint for transaction which is already marked as rollback-only");
	}
	return getSavepointManager().createSavepoint();
}
 
Example #21
Source File: AbstractReactiveTransactionAspectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Simulate a transaction infrastructure failure.
 * Shouldn't invoke target method.
 */
@Test
public void cannotCreateTransaction() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	Method m = getNameMethod;
	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(m, txatt);

	ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
	// Expect a transaction
	CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
	given(rtm.getReactiveTransaction(txatt)).willThrow(ex);

	DefaultTestBean tb = new DefaultTestBean() {
		@Override
		public Mono<String> getName() {
			throw new UnsupportedOperationException(
					"Shouldn't have invoked target method when couldn't create transaction for transactional method");
		}
	};
	TestBean itb = (TestBean) advised(tb, rtm, tas);

	itb.getName()
			.as(StepVerifier::create)
			.expectError(CannotCreateTransactionException.class)
			.verify();
}
 
Example #22
Source File: AbstractTransactionAspectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Simulate a transaction infrastructure failure.
 * Shouldn't invoke target method.
 */
@Test
public void cannotCreateTransaction() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	Method m = getNameMethod;
	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(m, txatt);

	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// Expect a transaction
	CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
	given(ptm.getTransaction(txatt)).willThrow(ex);

	TestBean tb = new TestBean() {
		@Override
		public String getName() {
			throw new UnsupportedOperationException(
					"Shouldn't have invoked target method when couldn't create transaction for transactional method");
		}
	};
	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	try {
		itb.getName();
		fail("Shouldn't have invoked method");
	}
	catch (CannotCreateTransactionException thrown) {
		assertTrue(thrown == ex);
	}
}
 
Example #23
Source File: ReactiveTestTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Mono<Void> doBegin(TransactionSynchronizationManager synchronizationManager, Object transaction, TransactionDefinition definition) {
	if (!TRANSACTION.equals(transaction)) {
		return Mono.error(new IllegalArgumentException("Not the same transaction object"));
	}
	if (!this.canCreateTransaction) {
		return Mono.error(new CannotCreateTransactionException("Cannot create transaction"));
	}
	return Mono.fromRunnable(() -> this.begin = true);
}
 
Example #24
Source File: JmsTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void initializeConnection() {
	if (!this.connectionInitialized) {
		try {
			addConnection(createConnection());
		}
		catch (JMSException ex) {
			throw new CannotCreateTransactionException(
					"Failed to lazily initialize JMS Connection for transaction", ex);
		}
		this.connectionInitialized = true;
	}
}
 
Example #25
Source File: JmsTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void initializeSession() {
	if (!this.sessionInitialized) {
		Connection con = getConnection();
		Assert.state(con != null, "No transactional JMS Connection");
		try {
			addSession(createSession(con), con);
		}
		catch (JMSException ex) {
			throw new CannotCreateTransactionException(
					"Failed to lazily initialize JMS Session for transaction", ex);
		}
		this.sessionInitialized = true;
	}
}
 
Example #26
Source File: JpaTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object createSavepoint() throws TransactionException {
	if (getEntityManagerHolder().isRollbackOnly()) {
		throw new CannotCreateTransactionException(
				"Cannot create savepoint for transaction which is already marked as rollback-only");
	}
	return getSavepointManager().createSavepoint();
}
 
Example #27
Source File: JtaTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This implementation returns a JtaTransactionObject instance for the
 * JTA UserTransaction.
 * <p>The UserTransaction object will either be looked up freshly for the
 * current transaction, or the cached one looked up at startup will be used.
 * The latter is the default: Most application servers use a shared singleton
 * UserTransaction that can be cached. Turn off the "cacheUserTransaction"
 * flag to enforce a fresh lookup for every transaction.
 * @see #setCacheUserTransaction
 */
@Override
protected Object doGetTransaction() {
	UserTransaction ut = getUserTransaction();
	if (ut == null) {
		throw new CannotCreateTransactionException("No JTA UserTransaction available - " +
				"programmatic PlatformTransactionManager.getTransaction usage not supported");
	}
	if (!this.cacheUserTransaction) {
		ut = lookupUserTransaction(
				this.userTransactionName != null ? this.userTransactionName : DEFAULT_USER_TRANSACTION_NAME);
	}
	return doGetJtaTransaction(ut);
}
 
Example #28
Source File: AbstractTransactionAspectTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Simulate a transaction infrastructure failure.
 * Shouldn't invoke target method.
 */
@Test
public void cannotCreateTransaction() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	Method m = getNameMethod;
	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(m, txatt);

	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// Expect a transaction
	CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
	given(ptm.getTransaction(txatt)).willThrow(ex);

	TestBean tb = new TestBean() {
		@Override
		public String getName() {
			throw new UnsupportedOperationException(
					"Shouldn't have invoked target method when couldn't create transaction for transactional method");
		}
	};
	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	try {
		itb.getName();
		fail("Shouldn't have invoked method");
	}
	catch (CannotCreateTransactionException thrown) {
		assertTrue(thrown == ex);
	}
}
 
Example #29
Source File: LocalListner.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to process messages from queue.
 * 
 * @param in
 * @param channel
 * @param tag
 * @throws IOException
 * @throws InterruptedException
 */
@RabbitListener(queues = "espm.salesOrders")
public void recieve(SalesOrder in, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag)
		throws IOException, InterruptedException {

	SalesOrderRepository repo = appContext.getBean(SalesOrderRepository.class);
	try {
		if (!repo.existsById(in.getSalesOrderId())) {
			repo.save(in);
			logger.info(in.getSalesOrderId() + " created");
			channel.basicAck(tag, false);
			value = initialValue;

		} else {
			logger.error(in.getSalesOrderId() + " already Exists, Deleting from Queue");
			channel.basicAck(tag, false);

		}
	} catch (DataIntegrityViolationException e) {
		logger.error(in.getSalesOrderId() + " is an invalid Sales-Order, Deleting from Queue");
		channel.basicNack(tag, false, false);

	} catch (CannotCreateTransactionException ccte) {
		logger.error("Unable to connect to DB");
		logger.error("Backing  for " + value);
		TimeUnit.MILLISECONDS.sleep(value);
		if (value <= maxVal)
			value = value * multiplier;
		channel.basicNack(tag, false, true);

	}

}
 
Example #30
Source File: DataSourceTransactionManager.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * This implementation sets the isolation level but ignores the timeout.
 */
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
	DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
	Connection con = null;

	try {
		if (txObject.getConnectionHolder() == null ||
				txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
			Connection newCon = this.dataSource.getConnection();
			if (logger.isDebugEnabled()) {
				logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
			}
			txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
		}

		txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
		con = txObject.getConnectionHolder().getConnection();

		Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
		txObject.setPreviousIsolationLevel(previousIsolationLevel);

		// Switch to manual commit if necessary. This is very expensive in some JDBC drivers,
		// so we don't want to do it unnecessarily (for example if we've explicitly
		// configured the connection pool to set it already).
		if (con.getAutoCommit()) {
			txObject.setMustRestoreAutoCommit(true);
			if (logger.isDebugEnabled()) {
				logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
			}
			con.setAutoCommit(false);
		}
		txObject.getConnectionHolder().setTransactionActive(true);

		int timeout = determineTimeout(definition);
		if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
			txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
		}

		// Bind the session holder to the thread.
		if (txObject.isNewConnectionHolder()) {
			TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
		}
	}

	catch (Throwable ex) {
		if (txObject.isNewConnectionHolder()) {
			DataSourceUtils.releaseConnection(con, this.dataSource);
			txObject.setConnectionHolder(null, false);
		}
		throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
	}
}