Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive() . 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: MessagingServiceImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private void queueJob(MessageProcessingJob.Mode mode, long messageId, String user, String cause) {
    // queue up the processing job after the transaction has committed
    LOG.debug("registering synchronization");

    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
    	throw new RiceRuntimeException("transaction syncronization is not active " +
    			"(!TransactionSynchronizationManager.isSynchronizationActive())");
    } else if (!TransactionSynchronizationManager.isActualTransactionActive()) {
    	throw new RiceRuntimeException("actual transaction is not active " +
    			"(!TransactionSynchronizationManager.isActualTransactionActive())");
    }

    TransactionSynchronizationManager.registerSynchronization(new QueueProcessingJobSynchronization(
        jobName,
        jobGroup,
        mode,
        messageId,
        user,
        cause,
        synchronous
    ));
}
 
Example 2
Source File: SpringTransactionInterceptor.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T execute(final CommandConfig config, final Command<T> command) {
    LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());


    // If the transaction is required (the other two options always need to go through the transactionTemplate),
    // the transactionTemplate is not used when the transaction is already active.
    // The reason for this is that the transactionTemplate try-catches exceptions and marks it as rollback.
    // Which will break nested service calls that go through the same stack of interceptors.

    int transactionPropagation = getPropagation(config);
    if (transactionPropagation == TransactionTemplate.PROPAGATION_REQUIRED && TransactionSynchronizationManager.isActualTransactionActive()) {
        return next.execute(config, command);

    } else {
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(transactionPropagation);
        return transactionTemplate.execute(status -> next.execute(config, command));

    }

}
 
Example 3
Source File: IbisTransaction.java    From iaf with Apache License 2.0 6 votes vote down vote up
public IbisTransaction(PlatformTransactionManager txManager, TransactionDefinition txDef, String object) {
	this.txManager = txManager;
	this.txDef = txDef;
	this.object = object;

	txClientIsActive = TransactionSynchronizationManager.isActualTransactionActive();
	txClientName = TransactionSynchronizationManager.getCurrentTransactionName();

	txStatus = txManager.getTransaction(txDef);

	txIsActive = TransactionSynchronizationManager.isActualTransactionActive();
	txIsNew = txStatus.isNewTransaction();

	if (txIsNew) {
		txName = Misc.createSimpleUUID();
		TransactionSynchronizationManager.setCurrentTransactionName(txName);
		int txTimeout = txDef.getTimeout();
		log.debug("Transaction manager ["+getRealTransactionManager()+"] created a new transaction ["+txName+"] for " + object + " with timeout [" + (txTimeout<0?"system default(=120s)":""+txTimeout) + "]");
	} else {
		txName = TransactionSynchronizationManager.getCurrentTransactionName();
		if (txClientIsActive && !txIsActive) {
			log.debug("Transaction manager ["+getRealTransactionManager()+"] suspended the transaction [" + txClientName + "] for " + object);
		}
	}
}
 
Example 4
Source File: PersistenceImplSupport.java    From cuba with Apache License 2.0 5 votes vote down vote up
public void registerInstance(Entity entity, EntityManager entityManager) {
    if (!TransactionSynchronizationManager.isActualTransactionActive())
        throw new RuntimeException("No transaction");

    UnitOfWork unitOfWork = entityManager.getDelegate().unwrap(UnitOfWork.class);
    getInstanceContainerResourceHolder(getStorageName(unitOfWork)).registerInstanceForUnitOfWork(entity, unitOfWork);

    if (entity instanceof BaseGenericIdEntity) {
        BaseEntityInternalAccess.setDetached((BaseGenericIdEntity) entity, false);
    }
}
 
Example 5
Source File: PersistenceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public EntityManager getEntityManager(String store) {
    if (!TransactionSynchronizationManager.isActualTransactionActive())
        throw new IllegalStateException("No active transaction");

    EntityManagerFactory emf;
    if (Stores.isMain(store))
        emf = this.jpaEmf;
    else
        emf = beanLocator.get("entityManagerFactory_" + store);

    javax.persistence.EntityManager jpaEm = EntityManagerFactoryUtils.doGetTransactionalEntityManager(emf, null, true);
    if (jpaEm == null) {
        throw new RuntimeException("Unable to get JPA EntityManager from EntityManagerFactoryUtils");
    }

    if (!jpaEm.isJoinedToTransaction()) {
        throw new IllegalStateException(String.format("No active transaction for %s database", store));
    }

    EntityManager entityManager = createEntityManager(jpaEm);

    EntityManagerContext ctx = contextHolder.get(store);
    if (ctx != null) {
        entityManager.setSoftDeletion(ctx.isSoftDeletion());
    } else {
        ctx = new EntityManagerContext();
        ctx.setSoftDeletion(isSoftDeletion());
        contextHolder.set(ctx, store);
        entityManager.setSoftDeletion(isSoftDeletion());
    }

    EntityManager emProxy = (EntityManager) Proxy.newProxyInstance(
            getClass().getClassLoader(),
            new Class[]{EntityManager.class},
            new EntityManagerInvocationHandler(entityManager, store)
    );
    return emProxy;
}
 
Example 6
Source File: SwitchDataSourceResetInterceptor.java    From Aooms with Apache License 2.0 5 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
    try{
        Object value = invocation.proceed();
        return value;
    }finally {
        if(!TransactionSynchronizationManager.isActualTransactionActive()){
            DynamicDataSourceHolder.removeDataSource();
        }
    }
}
 
Example 7
Source File: PersistenceImplSupport.java    From cuba with Apache License 2.0 5 votes vote down vote up
public Collection<Entity> getInstances(EntityManager entityManager) {
    if (!TransactionSynchronizationManager.isActualTransactionActive())
        throw new RuntimeException("No transaction");

    UnitOfWork unitOfWork = entityManager.getDelegate().unwrap(UnitOfWork.class);
    return getInstanceContainerResourceHolder(getStorageName(unitOfWork)).getInstances(unitOfWork);
}
 
Example 8
Source File: Db.java    From Aooms with Apache License 2.0 5 votes vote down vote up
/**
 * 注意:开启	@Transactional 时无法使用该方法
 */
public void useOff(String name) {
    logger.info("off datasource [{}]",name);
    // 如果包含在当前spring事务中,拒绝操作
    if(TransactionSynchronizationManager.isActualTransactionActive()){
        throw new UnsupportedOperationException("Cannot be used in spring transactions !");
    }
    DynamicDataSourceHolder.removeDataSource();
}
 
Example 9
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
protected boolean shouldPassReadOnlyToHibernate() {
    if((passReadOnlyToHibernate || osivReadOnly) && TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        if(TransactionSynchronizationManager.isActualTransactionActive()) {
            return passReadOnlyToHibernate && TransactionSynchronizationManager.isCurrentTransactionReadOnly();
        } else {
            return osivReadOnly;
        }
    } else {
        return false;
    }
}
 
Example 10
Source File: SpringTransactionFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isTransactionInProgress(
		JDBCContext jdbcContext, Context transactionContext, Transaction transaction) {

	return (transaction != null && transaction.isActive()) ||
			TransactionSynchronizationManager.isActualTransactionActive();
}
 
Example 11
Source File: PersistenceImplSupport.java    From cuba with Apache License 2.0 5 votes vote down vote up
public void registerInstance(Entity entity, AbstractSession session) {
    // Can be called outside of a transaction when fetching lazy attributes
    if (!TransactionSynchronizationManager.isActualTransactionActive())
        return;

    if (!(session instanceof UnitOfWork))
        throw new RuntimeException("Session is not a UnitOfWork: " + session);

    getInstanceContainerResourceHolder(getStorageName(session)).registerInstanceForUnitOfWork(entity, (UnitOfWork) session);
}
 
Example 12
Source File: SpringTransactionContext.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
public boolean isTransactionActive() {
  return TransactionSynchronizationManager.isActualTransactionActive() &&
         !TransactionState.ROLLED_BACK.equals(lastTransactionState) &&
         !TransactionState.ROLLINGBACK.equals(lastTransactionState);
}
 
Example 13
Source File: ProducerOnlyTransactionTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Transactional
public void DoInTransaction(MessageChannel output) {
	this.isInTx = TransactionSynchronizationManager.isActualTransactionActive();
	output.send(new GenericMessage<>("foo"));
}
 
Example 14
Source File: TransactionSupportUtil.java    From alfresco-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static boolean isActualTransactionActive()
{
    return TransactionSynchronizationManager.isActualTransactionActive();
}
 
Example 15
Source File: SpringTransactionProvider.java    From qmq with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isInTransaction() {
    return TransactionSynchronizationManager.isActualTransactionActive();
}
 
Example 16
Source File: JtaUtil.java    From iaf with Apache License 2.0 4 votes vote down vote up
public static String displayTransactionStatus(TransactionStatus txStatus) {
	String result;
	result="txName ["+TransactionSynchronizationManager.getCurrentTransactionName()+"]";
	if (txStatus!=null) {
		result+=" status new ["+txStatus.isNewTransaction()+"]";
		result+=" status completeted ["+txStatus.isCompleted()+"]";
		result+=" status rollbackOnly ["+txStatus.isRollbackOnly()+"]";
		result+=" status hasSavepoint ["+txStatus.hasSavepoint()+"]";
	} else {
		result+=" currently not in a transaction";
	}
	result+=" isolation ["+TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()+"]";
	result+=" active ["+TransactionSynchronizationManager.isActualTransactionActive()+"]";
	boolean syncActive=TransactionSynchronizationManager.isSynchronizationActive();
	result+=" synchronization active ["+syncActive+"]";
	result+="\n";
	Map<Object, Object> resources = TransactionSynchronizationManager.getResourceMap();
	result += "resources:\n";
	if (resources==null) {
		result+="  map is null\n";
	} else {
		for (Iterator<Object> it=resources.keySet().iterator(); it.hasNext();) {
			Object key = it.next();
			Object resource = resources.get(key);
			result += ClassUtils.nameOf(key)+"("+key+"): "+ClassUtils.nameOf(resource)+"("+resource+")\n";
			if (resource instanceof JmsResourceHolder) {
				JmsResourceHolder jrh = (JmsResourceHolder)resource; 
				result+="  connection: "+jrh.getConnection()+", session: "+jrh.getSession()+"\n";
			}
		}
	}
	if (syncActive) {
		List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
		result += "synchronizations:\n";
		for (int i=0; i<synchronizations.size(); i++) {
			TransactionSynchronization synchronization = synchronizations.get(i);
			result += ClassUtils.nameOf(synchronization)+"("+synchronization+")\n"; 
		}
	}
	return result;
}
 
Example 17
Source File: PersistenceImplSupport.java    From cuba with Apache License 2.0 4 votes vote down vote up
public Collection<Entity> getSavedInstances(String storeName) {
    if (!TransactionSynchronizationManager.isActualTransactionActive())
        throw new RuntimeException("No transaction");

    return getInstanceContainerResourceHolder(storeName).getSavedInstances();
}
 
Example 18
Source File: TransactionTestUtils.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Convenience method for determining if a transaction is active for the
 * current {@link Thread}.
 * @return {@code true} if a transaction is currently active
 */
public static boolean inTransaction() {
	return TransactionSynchronizationManager.isActualTransactionActive();
}
 
Example 19
Source File: TransactionTestUtils.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Convenience method for determining if a transaction is active for the
 * current {@link Thread}.
 * @return {@code true} if a transaction is currently active
 */
public static boolean inTransaction() {
	return TransactionSynchronizationManager.isActualTransactionActive();
}
 
Example 20
Source File: DistributedCacheManagerDecorator.java    From rice with Educational Community License v2.0 2 votes vote down vote up
/**
 * Should a transaction bound flush be performed?
 * @return true for transaction based flushing
 */
private boolean doTransactionalFlush() {
    return TransactionSynchronizationManager.isSynchronizationActive() && TransactionSynchronizationManager.isActualTransactionActive();
}