Java Code Examples for org.springframework.transaction.TransactionException

The following examples show how to use org.springframework.transaction.TransactionException. 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: hazelcastmq   Source File: HazelcastMQTransactionManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doRollback(DefaultTransactionStatus status) throws
    TransactionException {
  HazelcastMQTransactionObject txObject =
      (HazelcastMQTransactionObject) status.
      getTransaction();
  HazelcastMQContext con = txObject.getHazelcastMQContextHolder().
      getHazelcastMQContext();

  if (status.isDebug() && log.isFinestEnabled()) {
    log.finest(format("Rolling back HazelcastMQ transaction on "
        + "HazelcastMQContext [%s].", con));
  }

  try {
    con.rollback();
  }
  catch (com.hazelcast.transaction.TransactionException ex) {
    throw new TransactionSystemException(
        "Could not rollback HazelcastMQ transaction", ex);
  }
}
 
Example 2
Source Project: spring4-understanding   Source File: OpenJpaDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager);

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration
		FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan();
		if (fetchPlan instanceof JDBCFetchPlan) {
			IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel());
			((JDBCFetchPlan) fetchPlan).setIsolation(isolation);
		}
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly()) {
		// Like with EclipseLink, make sure to start the logic transaction early so that other
		// participants using the connection (such as JdbcTemplate) run in a transaction.
		openJpaEntityManager.beginStore();
	}

	// Custom implementation for OpenJPA savepoint handling
	return new OpenJpaTransactionData(openJpaEntityManager);
}
 
Example 3
/**
 * Resume the given transaction. Delegates to the {@code doResume}
 * template method first, then resuming transaction synchronization.
 * @param transaction the current transaction object
 * @param resourcesHolder the object that holds suspended resources,
 * as returned by {@code suspend} (or {@code null} to just
 * resume synchronizations, if any)
 * @see #doResume
 * @see #suspend
 */
protected final void resume(@Nullable Object transaction, @Nullable SuspendedResourcesHolder resourcesHolder)
		throws TransactionException {

	if (resourcesHolder != null) {
		Object suspendedResources = resourcesHolder.suspendedResources;
		if (suspendedResources != null) {
			doResume(transaction, suspendedResources);
		}
		List<TransactionSynchronization> suspendedSynchronizations = resourcesHolder.suspendedSynchronizations;
		if (suspendedSynchronizations != null) {
			TransactionSynchronizationManager.setActualTransactionActive(resourcesHolder.wasActive);
			TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(resourcesHolder.isolationLevel);
			TransactionSynchronizationManager.setCurrentTransactionReadOnly(resourcesHolder.readOnly);
			TransactionSynchronizationManager.setCurrentTransactionName(resourcesHolder.name);
			doResumeSynchronization(suspendedSynchronizations);
		}
	}
}
 
Example 4
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see ReactiveTransaction#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final Mono<Void> commit(ReactiveTransaction transaction) throws TransactionException {
	if (transaction.isCompleted()) {
		return Mono.error(new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction"));
	}

	return TransactionSynchronizationManager.currentTransaction().flatMap(synchronizationManager -> {
		GenericReactiveTransaction reactiveTx = (GenericReactiveTransaction) transaction;
		if (reactiveTx.isRollbackOnly()) {
			if (reactiveTx.isDebug()) {
				logger.debug("Transactional code has requested rollback");
			}
			return processRollback(synchronizationManager, reactiveTx);
		}
		return processCommit(synchronizationManager, reactiveTx);
	});
}
 
Example 5
/**
 * 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 6
Source Project: hypersistence-optimizer   Source File: SpringJpaXmlTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    try {
        transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {
            Tag hibernate = new Tag();
            hibernate.setName("hibernate");
            entityManager.persist(hibernate);

            Tag jpa = new Tag();
            jpa.setName("jpa");
            entityManager.persist(jpa);
            return null;
        });
    } catch (TransactionException e) {
        LOGGER.error("Failure", e);
    }

}
 
Example 7
Source Project: hypersistence-optimizer   Source File: SpringJpaTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    try {
        transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {
            Tag hibernate = new Tag();
            hibernate.setName("hibernate");
            entityManager.persist(hibernate);

            Tag jpa = new Tag();
            jpa.setName("jpa");
            entityManager.persist(jpa);
            return null;
        });
    } catch (TransactionException e) {
        LOGGER.error("Failure", e);
    }

}
 
Example 8
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to EclipseLink's DatabaseLogin configuration
		// (since Spring 4.1.2)
		UnitOfWork uow = entityManager.unwrap(UnitOfWork.class);
		uow.getLogin().setTransactionIsolation(definition.getIsolationLevel());
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) {
		// Begin an early transaction to force EclipseLink to get a JDBC Connection
		// so that Spring can manage transactions with JDBC as well as EclipseLink.
		entityManager.unwrap(UnitOfWork.class).beginEarlyTransaction();
	}

	return null;
}
 
Example 9
Source Project: ignite   Source File: CacheSpringStoreSessionListener.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void onSessionStart(CacheStoreSession ses) {
    if (ses.isWithinTransaction() && ses.attachment() == null) {
        try {
            TransactionDefinition def = definition(ses.transaction(), ses.cacheName());

            ses.attach(txMgr.getTransaction(def));
        }
        catch (TransactionException e) {
            throw new CacheWriterException("Failed to start store session [tx=" + ses.transaction() + ']', e);
        }
    }
}
 
Example 10
Source Project: sdn-rx   Source File: ReactiveNeo4jTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doBegin(TransactionSynchronizationManager transactionSynchronizationManager, Object transaction,
		TransactionDefinition transactionDefinition) throws TransactionException {

	return Mono.defer(() -> {
		ReactiveNeo4jTransactionObject transactionObject = extractNeo4jTransaction(transaction);

		TransactionConfig transactionConfig = createTransactionConfigFrom(transactionDefinition);
		boolean readOnly = transactionDefinition.isReadOnly();

		transactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly);

		return databaseSelectionProvider.getDatabaseSelection()
			.switchIfEmpty(Mono.just(DatabaseSelection.undecided()))
			.map(databaseName -> new Neo4jTransactionContext(databaseName.getValue(), bookmarkManager.getBookmarks()))
			.map(context -> Tuples.of(context, this.driver.rxSession(sessionConfig(readOnly, context.getBookmarks(), context.getDatabaseName()))))
			.flatMap(contextAndSession -> Mono
					.from(contextAndSession.getT2().beginTransaction(transactionConfig))
					.map(nativeTransaction -> new ReactiveNeo4jTransactionHolder(contextAndSession.getT1(), contextAndSession.getT2(), nativeTransaction))
			)
			.doOnNext(transactionHolder -> {
				transactionHolder.setSynchronizedWithTransaction(true);
				transactionObject.setResourceHolder(transactionHolder);
				transactionSynchronizationManager.bindResource(this.driver, transactionHolder);
			});

	}).then();
}
 
Example 11
Source Project: sdn-rx   Source File: ReactiveNeo4jTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doRollback(TransactionSynchronizationManager transactionSynchronizationManager,
		GenericReactiveTransaction genericReactiveTransaction) throws TransactionException {

	ReactiveNeo4jTransactionHolder holder = extractNeo4jTransaction(genericReactiveTransaction)
		.getRequiredResourceHolder();
	return holder.rollback();
}
 
Example 12
@Override
protected Object doGetTransaction(TransactionSynchronizationManager synchronizationManager) throws TransactionException {
    ReactiveRedissonTransactionObject transactionObject = new ReactiveRedissonTransactionObject();

    ReactiveRedissonResourceHolder holder = (ReactiveRedissonResourceHolder) synchronizationManager.getResource(redissonClient);
    transactionObject.setResourceHolder(holder);
    return transactionObject;
}
 
Example 13
/**
 * This implementation of rollback handles participating in existing
 * transactions. Delegates to {@code doRollback} and
 * {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	processRollback(defStatus);
}
 
Example 14
Source Project: sdn-rx   Source File: Neo4jTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object doGetTransaction() throws TransactionException {

	Neo4jTransactionHolder resourceHolder = (Neo4jTransactionHolder) TransactionSynchronizationManager
		.getResource(driver);
	return new Neo4jTransactionObject(resourceHolder);
}
 
Example 15
Source Project: sdn-rx   Source File: Neo4jTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
	Neo4jTransactionObject transactionObject = extractNeo4jTransaction(transaction);

	TransactionConfig transactionConfig = createTransactionConfigFrom(definition);
	boolean readOnly = definition.isReadOnly();


	TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly);

	try {
		// Prepare configuration data
		Neo4jTransactionContext context = new Neo4jTransactionContext(
			databaseSelectionProvider.getDatabaseSelection().getValue(),
			bookmarkManager.getBookmarks()
		);

		// Configure and open session together with a native transaction
		Session session = this.driver
			.session(sessionConfig(readOnly, context.getBookmarks(), context.getDatabaseName()));
		Transaction nativeTransaction = session.beginTransaction(transactionConfig);

		// Synchronize on that
		Neo4jTransactionHolder transactionHolder = new Neo4jTransactionHolder(context, session, nativeTransaction);
		transactionHolder.setSynchronizedWithTransaction(true);
		transactionObject.setResourceHolder(transactionHolder);

		TransactionSynchronizationManager.bindResource(this.driver, transactionHolder);
	} catch (Exception ex) {
		throw new TransactionSystemException(String.format("Could not open a new Neo4j session: %s", ex.getMessage()));
	}
}
 
Example 16
protected void doBegin(Object transaction, TransactionDefinition definition) {
    ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) transaction;

    super.doBegin(actualTransactionObject.getHibernateTransactionObject(),
            definition);
    try {
        ldapManagerDelegate.doBegin(actualTransactionObject
                .getLdapTransactionObject(), definition);
    } catch (TransactionException e) {
        // Failed to start LDAP transaction - make sure we clean up properly
        super.doCleanupAfterCompletion(actualTransactionObject.getHibernateTransactionObject());
        throw e;
    }
}
 
Example 17
/**
 * 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
@Test
public void test() {
    try {
        transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> {
            EmailSubscriber email = new EmailSubscriber();
            email.setEmailAddress("[email protected]");
            email.setFirstName("Vlad");
            email.setLastName("Mihalcea");

            entityManager.persist(email);

            SmsSubscriber sms = new SmsSubscriber();
            sms.setPhoneNumber("012-345-67890");
            sms.setFirstName("Vlad");
            sms.setLastName("Mihalcea");

            entityManager.persist(sms);

            return null;
        });
    } catch (TransactionException e) {
        LOGGER.error("Failure", e);
    }

    campaignService.send("Black Friday", "High-Performance Java Persistence is 40% OFF");

}
 
Example 19
Source Project: spring-analysis-note   Source File: JpaTransactionManager.java    License: 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 20
Source Project: spring-analysis-note   Source File: DefaultJpaDialect.java    License: MIT License 5 votes vote down vote up
/**
 * This implementation invokes the standard JPA {@code Transaction.begin}
 * method. Throws an InvalidIsolationLevelException if a non-default isolation
 * level is set.
 * <p>This implementation does not return any transaction data Object, since there
 * is no state to be kept for a standard JPA transaction. Hence, subclasses do not
 * have to care about the return value ({@code null}) of this implementation
 * and are free to return their own transaction data Object.
 * @see javax.persistence.EntityTransaction#begin
 * @see org.springframework.transaction.InvalidIsolationLevelException
 * @see #cleanupTransaction
 */
@Override
@Nullable
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		throw new InvalidIsolationLevelException(getClass().getSimpleName() +
				" does not support custom isolation levels due to limitations in standard JPA. " +
				"Specific arrangements may be implemented in custom JpaDialect variants.");
	}
	entityManager.getTransaction().begin();
	return null;
}
 
Example 21
@Override
protected Object doGetTransaction(TransactionSynchronizationManager synchronizationManager)
		throws TransactionException {
	ReactiveFirestoreResourceHolder resourceHolder = (ReactiveFirestoreResourceHolder) synchronizationManager
			.getResource(this.firestore);
	return new ReactiveFirestoreTransactionObject(resourceHolder);
}
 
Example 22
/**
 * This implementation of rollback handles participating in existing
 * transactions. Delegates to {@code doRollback} and
 * {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	processRollback(defStatus, false);
}
 
Example 23
Source Project: java-technology-stack   Source File: DefaultJpaDialectTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testDefaultTransactionDefinition() throws Exception {
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);

	try {
		dialect.beginTransaction(null, definition);
		fail("expected exception");
	}
	catch (TransactionException e) {
		// ok
	}
}
 
Example 24
Source Project: java-technology-stack   Source File: AbstractTransactionStatus.java    License: MIT License 5 votes vote down vote up
/**
 * Release the savepoint that is held for the transaction.
 */
public void releaseHeldSavepoint() throws TransactionException {
	Object savepoint = getSavepoint();
	if (savepoint == null) {
		throw new TransactionUsageException(
				"Cannot release savepoint - no savepoint associated with current transaction");
	}
	getSavepointManager().releaseSavepoint(savepoint);
	setSavepoint(null);
}
 
Example 25
@Override
public void rollback(TransactionStatus status) throws TransactionException {
	if(logger.isWarnEnabled()){
		logger.warn("Rollback all connected transactions.");
	}
	try{
		TransactionSynchronizationUtils.triggerBeforeCompletion();
		Map<DataSource, ConnectionHolder> connSet = RoutingSynchronizationManager.getSynchronizations();
		Exception rollbackException = null;
		ConnectionHolder rollbackExceptionConnection = null;

        for (ConnectionHolder connection:connSet.values()) {
            try {
            	connection.rollback();
            	if (logger.isDebugEnabled()) {
        			logger.debug("Connection["+ connection +"] has been rolled back.");
        		}
            } catch (Exception ex) {
                if (rollbackException == null) {
                    rollbackException = ex;
                    rollbackExceptionConnection = connection;
                } else {
                    logger.warn("Rollback exception (" + rollbackExceptionConnection + ") " + ex.getMessage(), ex);
                }
            }
        }
        
        if (rollbackException != null) {
            throw new UnexpectedRollbackException("Rollback exception, originated at ("+rollbackExceptionConnection+") "+
              rollbackException.getMessage(), rollbackException);
        }
	}finally{
		RoutingSynchronizationManager
				.invokeAfterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
		RoutingSynchronizationManager.clearSynchronization();
	}
}
 
Example 26
/**
 * This implementation of rollback handles participating in existing
 * transactions. Delegates to {@code doRollback} and
 * {@code doSetRollbackOnly}.
 * @see #doRollback
 * @see #doSetRollbackOnly
 */
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	processRollback(defStatus, false);
}
 
Example 27
protected ConnectionHolder getConnectionHolderForSavepoint() throws TransactionException {
	if (!isSavepointAllowed()) {
		throw new NestedTransactionNotSupportedException(
				"Transaction manager does not allow nested transactions");
	}
	if (!hasConnectionHolder()) {
		throw new TransactionUsageException(
				"Cannot create nested transaction if not exposing a JDBC transaction");
	}
	return getConnectionHolder();
}
 
Example 28
Source Project: oneops   Source File: InstanceManager.java    License: Apache License 2.0 5 votes vote down vote up
private boolean acquireLock() {
	try {
		for (int i = 1; i <= this.poolSize; i++) {
			if (utilManager.acquireLock(LOCK_NAME_PREFIX + i, this.processId, lockTimeOutInSeconds)) {
				this.instanceId = i;
				logger.info(">>>>>>>Sensor process " + this.processId + " will be running as #" + i);
				startTheLockRefresh();
				try {
					this.state = State.Initializing;
					sensor.init(instanceId, poolSize);
					initJmsListeners(instanceId, poolSize);
					orphanEventHandler.start();
				} catch (Exception e) {
					cleanup();
					throw new RuntimeException(e);
				}finally {
					this.state=State.WaitingForLock;
				}
				this.state = State.Initalized;
				return true;
			}
		}
	} catch (TransactionException te) {
		//seems like DB is not accessible will retry
		logger.error(te);
	}

	return false;
}
 
Example 29
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final void commit(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	if (defStatus.isLocalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Transactional code has requested rollback");
		}
		processRollback(defStatus);
		return;
	}
	if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
		}
		processRollback(defStatus);
		// Throw UnexpectedRollbackException only at outermost transaction boundary
		// or if explicitly asked to.
		if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
			throw new UnexpectedRollbackException(
					"Transaction rolled back because it has been marked as rollback-only");
		}
		return;
	}

	processCommit(defStatus);
}
 
Example 30
protected ConnectionHolder getConnectionHolderForSavepoint() throws TransactionException {
	if (!isSavepointAllowed()) {
		throw new NestedTransactionNotSupportedException(
				"Transaction manager does not allow nested transactions");
	}
	if (!hasConnectionHolder()) {
		throw new TransactionUsageException(
				"Cannot create nested transaction if not exposing a JDBC transaction");
	}
	return getConnectionHolder();
}