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

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#registerSynchronization() . 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: PersistenceImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * INTERNAL.
 * Register synchronizations with a just started transaction.
 */
public void registerSynchronizationsIfAbsent(String store) {
    log.trace("registerSynchronizations for store '{}'", store);

    List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();

    boolean absent = synchronizations.stream()
            .noneMatch(s -> s instanceof EntityManagerContextSynchronization
                    && Objects.equals(store, ((EntityManagerContextSynchronization)s).getStore()));
    if (absent) {
        TransactionSynchronizationManager.registerSynchronization(createSynchronization(store));
        support.getInstanceContainerResourceHolder(store);

        statisticsAccumulator.incStartedTransactionsCount();
        TransactionSynchronizationManager.registerSynchronization(new StatisticsTransactionSynchronization());
    }
}
 
Example 2
Source File: SavedEntitiesHolder.java    From cuba with Apache License 2.0 6 votes vote down vote up
public static SavedEntitiesHolder setEntities(Set<Entity> saved) {
    SavedEntitiesHolder holder = (SavedEntitiesHolder) TransactionSynchronizationManager.getResource(RESOURCE_KEY);

    if (holder == null) {
        holder = new SavedEntitiesHolder();
        TransactionSynchronizationManager.bindResource(RESOURCE_KEY, holder);

        holder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.registerSynchronization(new Synchronization(holder, RESOURCE_KEY));
        log.debug("Created {}", holder);
    }

    log.debug("{} updates entities: {}", holder, saved);
    for (Entity entity : saved) {
        holder.entities.remove(entity);
        holder.entities.add(entity);
    }

    return holder;
}
 
Example 3
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 4
Source File: SpringTransactionProvider.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public void setTransactionListener(TransactionListener listener) {
    if (!TransactionSynchronizationManager.isSynchronizationActive()) throw E;

    this.transactionListener = listener;
    TransactionSynchronizationManager.registerSynchronization(this);
}
 
Example 5
Source File: SessionFactoryUtils.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get a JCR Session for the given Repository. Is aware of and will return any existing corresponding
 * Session bound to the current thread, for example when using JcrTransactionManager. Same as
 * <code>getSession</code> but throws the original Repository.
 * @param sessionFactory Jcr Repository to create session with
 * @param allowCreate if a non-transactional Session should be created when no transactional Session can
 *            be found for the current thread
 * @throws RepositoryException
 * @return
 */
public static Session doGetSession(SessionFactory sessionFactory, boolean allowCreate) throws RepositoryException {
    Assert.notNull(sessionFactory, "No sessionFactory specified");

    // check if there is any transaction going on
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.getSession() != null)
        return sessionHolder.getSession();

    if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("No session bound to thread, " + "and configuration does not allow creation of non-transactional one here");
    }

    LOG.debug("Opening JCR Session");
    Session session = sessionFactory.getSession();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        LOG.debug("Registering transaction synchronization for JCR session");
        // Use same session for further JCR actions within the transaction
        // thread object will get removed by synchronization at transaction
        // completion.
        sessionHolder = sessionFactory.getSessionHolder(session);
        sessionHolder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.registerSynchronization(new JcrSessionSynchronization(sessionHolder, sessionFactory));
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
    }

    return session;
}
 
Example 6
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void sendDeleteChannel(ChatChannel channel) {
    ChatChannelDeleteTxSync txSync = new ChatChannelDeleteTxSync(channel);

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(txSync);
    }
    else {
        txSync.afterCompletion(ChatChannelDeleteTxSync.STATUS_COMMITTED);
    }
}
 
Example 7
Source File: TransactionAwareCacheDecorator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example 8
Source File: LobCreatorUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a transaction synchronization for closing the given LobCreator,
 * preferring Spring transaction synchronization and falling back to
 * plain JTA transaction synchronization.
 * @param lobCreator the LobCreator to close after transaction completion
 * @param jtaTransactionManager the JTA TransactionManager to fall back to
 * when no Spring transaction synchronization is active (may be {@code null})
 * @throws IllegalStateException if there is neither active Spring transaction
 * synchronization nor active JTA transaction synchronization
 */
public static void registerTransactionSynchronization(
		LobCreator lobCreator, TransactionManager jtaTransactionManager) throws IllegalStateException {

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering Spring transaction synchronization for LobCreator");
		TransactionSynchronizationManager.registerSynchronization(
			new SpringLobCreatorSynchronization(lobCreator));
	}
	else {
		if (jtaTransactionManager != null) {
			try {
				int jtaStatus = jtaTransactionManager.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					logger.debug("Registering JTA transaction synchronization for LobCreator");
					jtaTransactionManager.getTransaction().registerSynchronization(
							new JtaLobCreatorSynchronization(lobCreator));
					return;
				}
			}
			catch (Throwable ex) {
				throw new TransactionSystemException(
						"Could not register synchronization with JTA TransactionManager", ex);
			}
		}
		throw new IllegalStateException("Active Spring transaction synchronization or active " +
			"JTA transaction with specified [javax.transaction.TransactionManager] required");
	}
}
 
Example 9
Source File: ExtendedEntityManagerCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Enlist this application-managed EntityManager in the current transaction.
 */
private void enlistInCurrentTransaction() {
	// Resource local transaction, need to acquire the EntityTransaction,
	// start a transaction now and enlist a synchronization for commit or rollback later.
	EntityTransaction et = this.target.getTransaction();
	et.begin();
	if (logger.isDebugEnabled()) {
		logger.debug("Starting resource-local transaction on application-managed " +
				"EntityManager [" + this.target + "]");
	}
	ExtendedEntityManagerSynchronization extendedEntityManagerSynchronization =
			new ExtendedEntityManagerSynchronization(this.target, this.exceptionTranslator);
	TransactionSynchronizationManager.bindResource(this.target, extendedEntityManagerSynchronization);
	TransactionSynchronizationManager.registerSynchronization(extendedEntityManagerSynchronization);
}
 
Example 10
Source File: RocketMqSendUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
public static void sendMq(List<MqBaseModel> mqBaseModels){
    // 判断是否存在事务,为空则说明不存在
    String currentTransactionName  = TransactionSynchronizationManager.getCurrentTransactionName();
    boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
    if (StrUtil.isBlank(currentTransactionName) || readOnly){
        MqNoTransactionSynchronizationAdapter.commit(mqBaseModels);
    } else {
        TransactionSynchronizationManager.registerSynchronization(new MqTransactionSynchronizationAdapter(mqBaseModels));
    }
}
 
Example 11
Source File: EasyTransSynchronizer.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
/**
 * create LogContext.<br>
 * pass in busCode and trxId will help about the execute efficient and the debug and statistics<br>
 * so I demand to pass in busCode and trxId to generate a global unique bus key 
 * @param busCode the unique busCode in AppId
 * @param trxId the unique trxId in appId+busCode
 */
public void startSoftTrans(String busCode,long trxId){
	
	if(isSoftTransBegon()) {
		throw new RuntimeException("transaction already started,but try to start again." + busCode + "," + trxId);
	}
	
	//hook to TransactionSynchronizer
	TransactionSynchronizationManager.registerSynchronization(new TransactionHook());
	LogProcessContext logProcessContext = new LogProcessContext(applicationName, busCode, trxId, writer,transStatusLogger);
	TransactionSynchronizationManager.bindResource(LOG_PROCESS_CONTEXT,logProcessContext);
	
	//check whether is a parent transaction
	TransactionId pTrxId = getParentTransactionId();
	if(pTrxId == null){
		
		//if this transaction is roll back, this record is will disappear
		//transStatusLogger.writeExecuteFlag(applicationName, busCode, trxId, null, null, null, TransactionStatus.COMMITTED);
		
		// since introduced SAGA, Global-transaction status can not be determined by master transaction commit 
		transStatusLogger.writeExecuteFlag(applicationName, busCode, trxId, null, null, null, TransactionStatus.UNKNOWN);
	} else {
		//a transaction with parent transaction,it's status depends on parent
		//check whether the parent transaction status is determined
		Integer pTransStatus = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.PARENT_TRANSACTION_STATUS);
		if(pTransStatus == null){
			pTransStatus = TransactionStatus.UNKNOWN;
		} 
		transStatusLogger.writeExecuteFlag(applicationName, busCode, trxId, pTrxId.getAppId(), pTrxId.getBusCode(), pTrxId.getTrxId(), pTransStatus);
	}
}
 
Example 12
Source File: ChatManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void sendDeleteChannelMessages(ChatChannel channel) {
    ChatChannelMessagesDeleteTxSync txSync = new ChatChannelMessagesDeleteTxSync(channel);

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.registerSynchronization(txSync);
    }
    else {
        txSync.afterCompletion(ChatChannelMessagesDeleteTxSync.STATUS_COMMITTED);
    }
    
    sendToCluster(new TransferableChatMessage(TransferableChatMessage.MessageType.REMOVE, "*", channel.getId()));
}
 
Example 13
Source File: ExtendedEntityManagerCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Enlist this application-managed EntityManager in the current transaction.
 */
private void enlistInCurrentTransaction() {
	// Resource local transaction, need to acquire the EntityTransaction,
	// start a transaction now and enlist a synchronization for commit or rollback later.
	EntityTransaction et = this.target.getTransaction();
	et.begin();
	if (logger.isDebugEnabled()) {
		logger.debug("Starting resource-local transaction on application-managed " +
				"EntityManager [" + this.target + "]");
	}
	ExtendedEntityManagerSynchronization extendedEntityManagerSynchronization =
			new ExtendedEntityManagerSynchronization(this.target, this.exceptionTranslator);
	TransactionSynchronizationManager.bindResource(this.target, extendedEntityManagerSynchronization);
	TransactionSynchronizationManager.registerSynchronization(extendedEntityManagerSynchronization);
}
 
Example 14
Source File: P0_JdbcTemplateOp.java    From nimble-orm with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean executeAfterCommit(final Runnable runnable) {
	if(runnable == null) {
           return false;
       }
	if(!TransactionSynchronizationManager.isActualTransactionActive()) {
           return false;
       }
	TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
		@Override
		public void suspend() {
		}
		@Override
		public void resume() {
		}
		@Override
		public void flush() {
		}
		@Override
		public void beforeCompletion() {
		}
		@Override
		public void beforeCommit(boolean readOnly) {
		}
		@Override
		public void afterCompletion(int status) {
		}
		@Override
		public void afterCommit() {
			runnable.run();
		}
	});
	return true;
}
 
Example 15
Source File: TransactionAwareCacheDecorator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void evict(final Object key) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.evict(key);
			}
		});
	}
	else {
		this.targetCache.evict(key);
	}
}
 
Example 16
Source File: DataSourceUtils.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * Actually obtain a JDBC Connection from the given DataSource.
 * Same as {@link #getConnection}, but throwing the original SQLException.
 * <p>Is aware of a corresponding Connection bound to the current thread, for example
 * when using {@link DataSourceTransactionManager}. Will bind a Connection to the thread
 * if transaction synchronization is active (e.g. if in a JTA transaction).
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param dataSource the DataSource to obtain Connections from
 * @return a JDBC Connection from the given DataSource
 * @throws SQLException if thrown by JDBC methods
 * @see #doReleaseConnection
 */
public static Connection doGetConnection(DataSource dataSource) throws SQLException {
	Assert.notNull(dataSource, "No DataSource specified");

	ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
	if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
		conHolder.requested();
		if (!conHolder.hasConnection()) {
			logger.debug("Fetching resumed JDBC Connection from DataSource");
			conHolder.setConnection(dataSource.getConnection());
		}
		return conHolder.getConnection();
	}
	// Else we either got no holder or an empty thread-bound holder here.

	logger.debug("Fetching JDBC Connection from DataSource");
	Connection con = dataSource.getConnection();

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		logger.debug("Registering transaction synchronization for JDBC Connection");
		// Use same Connection for further JDBC actions within the transaction.
		// Thread-bound object will get removed by synchronization at transaction completion.
		ConnectionHolder holderToUse = conHolder;
		if (holderToUse == null) {
			holderToUse = new ConnectionHolder(con);
		}
		else {
			holderToUse.setConnection(con);
		}
		holderToUse.requested();
		TransactionSynchronizationManager.registerSynchronization(
				new ConnectionSynchronization(holderToUse, dataSource));
		holderToUse.setSynchronizedWithTransaction(true);
		if (holderToUse != conHolder) {
			TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
		}
	}

	return con;
}
 
Example 17
Source File: SpringTransactionContext.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void addTransactionListener(final TransactionState transactionState, final TransactionListener transactionListener) {
  if (transactionState.equals(TransactionState.COMMITTING)) {

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void beforeCommit(boolean readOnly) {
        transactionListener.execute(commandContext);
      }
    });

  } else if (transactionState.equals(TransactionState.COMMITTED)) {

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void afterCommit() {
        transactionListener.execute(commandContext);
      }
    });

  } else if (transactionState.equals(TransactionState.ROLLINGBACK)) {

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void beforeCompletion() {
        transactionListener.execute(commandContext);
      }
    });

  } else if (transactionState.equals(TransactionState.ROLLED_BACK)) {

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void afterCompletion(int status) {
        if (TransactionSynchronization.STATUS_ROLLED_BACK == status) {
          transactionListener.execute(commandContext);
        }
      }
    });
  }
}
 
Example 18
Source File: TransactionAwareCacheDecorator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void put(final Object key, final Object value) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				TransactionAwareCacheDecorator.this.targetCache.put(key, value);
			}
		});
	}
	else {
		this.targetCache.put(key, value);
	}
}
 
Example 19
Source File: DataSourceUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Actually obtain a JDBC Connection from the given DataSource.
 * Same as {@link #getConnection}, but throwing the original SQLException.
 * <p>Is aware of a corresponding Connection bound to the current thread, for example
 * when using {@link DataSourceTransactionManager}. Will bind a Connection to the thread
 * if transaction synchronization is active (e.g. if in a JTA transaction).
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param dataSource the DataSource to obtain Connections from
 * @return a JDBC Connection from the given DataSource
 * @throws SQLException if thrown by JDBC methods
 * @see #doReleaseConnection
 */
public static Connection doGetConnection(DataSource dataSource) throws SQLException {
	Assert.notNull(dataSource, "No DataSource specified");

	ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
	if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
		conHolder.requested();
		if (!conHolder.hasConnection()) {
			logger.debug("Fetching resumed JDBC Connection from DataSource");
			conHolder.setConnection(fetchConnection(dataSource));
		}
		return conHolder.getConnection();
	}
	// Else we either got no holder or an empty thread-bound holder here.

	logger.debug("Fetching JDBC Connection from DataSource");
	Connection con = fetchConnection(dataSource);

	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		try {
			// Use same Connection for further JDBC actions within the transaction.
			// Thread-bound object will get removed by synchronization at transaction completion.
			ConnectionHolder holderToUse = conHolder;
			if (holderToUse == null) {
				holderToUse = new ConnectionHolder(con);
			}
			else {
				holderToUse.setConnection(con);
			}
			holderToUse.requested();
			TransactionSynchronizationManager.registerSynchronization(
					new ConnectionSynchronization(holderToUse, dataSource));
			holderToUse.setSynchronizedWithTransaction(true);
			if (holderToUse != conHolder) {
				TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
			}
		}
		catch (RuntimeException ex) {
			// Unexpected exception from external delegation call -> close Connection and rethrow.
			releaseConnection(con, dataSource);
			throw ex;
		}
	}

	return con;
}
 
Example 20
Source File: SpringTransactionContext.java    From camunda-bpm-platform with Apache License 2.0 4 votes vote down vote up
public void addTransactionListener(final TransactionState transactionState, final TransactionListener transactionListener) {
  if (transactionState.equals(TransactionState.COMMITTING)) {
    
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void beforeCommit(boolean readOnly) {
        transactionListener.execute(commandContext);
      }
    });
    
  } else if (transactionState.equals(TransactionState.COMMITTED)) {
  
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void afterCommit() {
        transactionListener.execute(commandContext);
      }
    });
    
  } else if (transactionState.equals(TransactionState.ROLLINGBACK)) {
    
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void beforeCompletion() {
        transactionListener.execute(commandContext);
      }
    });
    
  } else if (transactionState.equals(TransactionState.ROLLED_BACK)) {
    
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
      @Override
      public void afterCompletion(int status) {
        if(TransactionSynchronization.STATUS_ROLLED_BACK == status) {
          transactionListener.execute(commandContext);
        }
      }
    });
    
  }
  
}