List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager isSynchronizationActive
public static boolean isSynchronizationActive()
From source file:com._4dconcept.springframework.data.marklogic.datasource.ContentSourceUtils.java
/** * Actually obtain a XDBC Session from the given ContentSource. * Same as {@link #getSession}, but throwing the original XccException. * <p>Is aware of a corresponding Session bound to the current thread, for example * when using {@link ContentSourceTransactionManager}. Will bind a Session to the thread * if transaction synchronization is active (e.g. if in a JTA transaction). * <p>Directly accessed by {@link TransactionAwareContentSourceProxy}. * @param contentSource the ContentSource to obtain Sessions from * @return a XDBC Session from the given ContentSource * @throws XccException if thrown by XDBC methods * @see #doReleaseSession/* w ww. j a v a2s .co m*/ */ public static Session doGetSession(ContentSource contentSource) throws XccException { Assert.notNull(contentSource, "No ContentSource specified"); SessionHolder sesHolder = (SessionHolder) TransactionSynchronizationManager.getResource(contentSource); if (sesHolder != null && (sesHolder.hasSession() || sesHolder.isSynchronizedWithTransaction())) { sesHolder.requested(); if (!sesHolder.hasSession()) { logger.debug("Fetching resumed XDBC Session from ContentSource"); sesHolder.setSession(contentSource.newSession()); } return sesHolder.getSession(); } // Else we either got no holder or an empty thread-bound holder here. logger.debug("Fetching XDBC Session from ContentSource"); Session ses = contentSource.newSession(); if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering transaction synchronization for XDBC Session"); // Use same Session for further XDBC actions within the transaction. // Thread-bound object will get removed by synchronization at transaction completion. SessionHolder holderToUse = sesHolder; if (holderToUse == null) { holderToUse = new SessionHolder(ses); } else { holderToUse.setSession(ses); } holderToUse.requested(); TransactionSynchronizationManager .registerSynchronization(new SessionSynchronization(holderToUse, contentSource)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sesHolder) { TransactionSynchronizationManager.bindResource(contentSource, holderToUse); } } return ses; }
From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java
@Test public void testTransactionRollbackOnly() { final ODB odb = Mockito.mock(ODB.class); Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException()); PlatformTransactionManager tm = new NeoDatisTransactionManager(odb); TransactionTemplate tmpl = new TransactionTemplate(tm); Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb)); Assert.assertFalse("There should no active synchronizations", TransactionSynchronizationManager.isSynchronizationActive()); try {/*from w w w . ja va 2 s. com*/ tmpl.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb)); NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb); neoDatisTemplate.store(null); transactionStatus.setRollbackOnly(); } }); } catch (RuntimeException e) { // is ok } Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb)); Assert.assertFalse("There should no active synchronizations", TransactionSynchronizationManager.isSynchronizationActive()); Mockito.verify(odb, Mockito.times(1)).rollback(); }
From source file:com.github.rholder.spring.transaction.TransactionBindingSupport.java
/** * Checks the state of the current transaction and throws an exception if a transaction * is not present or if the transaction is not read-write, if required. * // w ww. j av a2 s . c om * @param requireReadWrite <tt>true</tt> if the transaction must be read-write * * @since 3.2 */ public static void checkTransactionReadState(boolean requireReadWrite) { if (!TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException("The current operation requires an active " + (requireReadWrite ? "read-write" : "") + "transaction."); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly() && requireReadWrite) { throw new IllegalStateException("The current operation requires an active read-write transaction."); } }
From source file:org.cfr.capsicum.datasource.DataSourceUtils.java
/** * 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//from w w w . j ava 2s . c om */ public static Connection doGetConnection(DataSource dataSource) throws SQLException { Assert.notNull(dataSource, "No DataSource specified"); CayenneConnectionHolder conHolder = (CayenneConnectionHolder) 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. CayenneConnectionHolder holderToUse = conHolder; if (holderToUse == null) { ObjectContext context = BaseContext.getThreadObjectContext(); holderToUse = new CayenneConnectionHolder(con, context); } else { holderToUse.setConnection(con); } holderToUse.requested(); TransactionSynchronizationManager .registerSynchronization(new ConnectionSynchronization(holderToUse, dataSource)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != conHolder) { TransactionSynchronizationManager.bindResource(dataSource, holderToUse); } } return con; }
From source file:org.springextensions.db4o.Db4oTransactionManagerTest.java
@Test public void testTransactionRollbackOnly() throws Exception { final ExtObjectContainer container = mock(ExtObjectContainer.class); when(container.identity()).thenReturn(null); when(container.ext()).thenReturn(container); PlatformTransactionManager tm = new Db4oTransactionManager(container); TransactionTemplate tt = new TransactionTemplate(tm); Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container"); Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); try {//from w w w .j a v a 2 s. c om tt.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { Assert.assertTrue(TransactionSynchronizationManager.hasResource(container), "Has thread session"); Db4oTemplate template = new Db4oTemplate(container); template.execute(new Db4oCallback() { public Object doInDb4o(ObjectContainer cont) { cont.ext().identity(); return null; } }); status.setRollbackOnly(); } }); } catch (RuntimeException e) { // it's okay } Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container"); Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(), "JTA synchronizations not active"); verify(container).rollback(); }
From source file:org.mybatis.spring.SqlSessionUtils.java
/** * Register session holder if synchronization is active (i.e. a Spring TX is active). * * Note: The DataSource used by the Environment should be synchronized with the * transaction either through DataSourceTxMgr or another tx synchronization. * Further assume that if an exception is thrown, whatever started the transaction will * handle closing / rolling back the Connection associated with the SqlSession. * /*www. ja v a2 s . c om*/ * @param sessionFactory sqlSessionFactory used for registration. * @param executorType executorType used for registration. * @param exceptionTranslator persistenceExceptionTranslater used for registration. * @param session sqlSession used for registration. */ private static void registerSessionHolder(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator, SqlSession session) { SqlSessionHolder holder; if (TransactionSynchronizationManager.isSynchronizationActive()) { Environment environment = sessionFactory.getConfiguration().getEnvironment(); if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registering transaction synchronization for SqlSession [" + session + "]"); } holder = new SqlSessionHolder(session, executorType, exceptionTranslator); TransactionSynchronizationManager.bindResource(sessionFactory, holder); TransactionSynchronizationManager .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory)); holder.setSynchronizedWithTransaction(true); holder.requested(); } else { if (TransactionSynchronizationManager.getResource(environment.getDataSource()) == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("SqlSession [" + session + "] was not registered for synchronization because DataSource is not transactional"); } } else { throw new TransientDataAccessResourceException( "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization"); } } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active"); } } }
From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java
private void doTestJtaTransaction(final boolean rollback) throws Exception { if (rollback) { given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); } else {//from ww w. j a v a 2 s . c o m given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); } JtaTransactionManager ptm = new JtaTransactionManager(userTransaction); TransactionTemplate tt = new TransactionTemplate(ptm); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource)); assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("Is new transaction", status.isNewTransaction()); Session c = ContentSourceUtils.getSession(contentSource); assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource)); ContentSourceUtils.releaseSession(c, contentSource); c = ContentSourceUtils.getSession(contentSource); assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource)); ContentSourceUtils.releaseSession(c, contentSource); if (rollback) { status.setRollbackOnly(); } } }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); verify(userTransaction).begin(); if (rollback) { verify(userTransaction).rollback(); } verify(session).close(); }
From source file:com.avaje.ebean.springsupport.txn.SpringAwareJdbcTransactionManager.java
/** * Search for our specific transaction listener. * <p>//from w w w . j a v a2s . c om * If it exists then we have already seen and "wrapped" this transaction. * </p> */ private SpringTxnListener getSpringTxnListener() { if (TransactionSynchronizationManager.isSynchronizationActive()) { List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager .getSynchronizations(); if (synchronizations != null) { // search for our specific listener for (int i = 0; i < synchronizations.size(); i++) { if (synchronizations.get(i) instanceof SpringTxnListener) { return (SpringTxnListener) synchronizations.get(i); } } } } return null; }
From source file:org.apache.servicemix.transaction.GeronimoPlatformTransactionManager.java
protected void registerTransactionAssociationListener() { addTransactionAssociationListener(new TransactionManagerMonitor() { public void threadAssociated(Transaction transaction) { try { if (transaction.getStatus() == Status.STATUS_ACTIVE) { SuspendedResourcesHolder holder = suspendedResources.remove(transaction); if (holder != null && holder.getSuspendedSynchronizations() != null) { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(holder.isReadOnly()); TransactionSynchronizationManager.setCurrentTransactionName(holder.getName()); TransactionSynchronizationManager.initSynchronization(); for (Iterator<?> it = holder.getSuspendedSynchronizations().iterator(); it.hasNext();) { TransactionSynchronization synchronization = (TransactionSynchronization) it.next(); synchronization.resume(); TransactionSynchronizationManager.registerSynchronization(synchronization); }//www . j a va 2s . c o m } } } catch (SystemException e) { return; } } public void threadUnassociated(Transaction transaction) { try { if (transaction.getStatus() == Status.STATUS_ACTIVE) { if (TransactionSynchronizationManager.isSynchronizationActive()) { List<?> suspendedSynchronizations = TransactionSynchronizationManager .getSynchronizations(); for (Iterator<?> it = suspendedSynchronizations.iterator(); it.hasNext();) { ((TransactionSynchronization) it.next()).suspend(); } TransactionSynchronizationManager.clearSynchronization(); String name = TransactionSynchronizationManager.getCurrentTransactionName(); TransactionSynchronizationManager.setCurrentTransactionName(null); boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); TransactionSynchronizationManager.setActualTransactionActive(false); SuspendedResourcesHolder holder = new SuspendedResourcesHolder(null, suspendedSynchronizations, name, readOnly); suspendedResources.put(transaction, holder); } } } catch (SystemException e) { return; } } }); }
From source file:org.grails.orm.hibernate.GrailsSessionContext.java
private Session createSession(Object resource) { LOG.debug("Opening Hibernate Session"); SessionHolder sessionHolder = (SessionHolder) resource; Session session = sessionFactory.openSession(); // Use same Session for further Hibernate actions within the transaction. // Thread object will get removed by synchronization at transaction completion. if (TransactionSynchronizationManager.isSynchronizationActive()) { // We're within a Spring-managed transaction, possibly from JtaTransactionManager. LOG.debug("Registering Spring transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else {/*ww w. j a va 2 s. c o m*/ // it's up to the caller to manage concurrent sessions // holderToUse.addSession(session); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.MANUAL); } TransactionSynchronizationManager .registerSynchronization(createSpringSessionSynchronization(holderToUse)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } else { // No Spring transaction management active -> try JTA transaction synchronization. registerJtaSynchronization(session, sessionHolder); } /* // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, sessionFactory)) { closeSession(session); throw new IllegalStateException("No Hibernate Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } */ return session; }