List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager isCurrentTransactionReadOnly
public static boolean isCurrentTransactionReadOnly()
From source file:org.alfresco.util.transaction.SpringAwareUserTransaction.java
/** * @throws NotSupportedException if an attempt is made to reuse this instance */// www . j ava 2s .com public synchronized void begin() throws NotSupportedException, SystemException { // make sure that the status and info align - the result may or may not be null @SuppressWarnings("unused") TransactionInfo txnInfo = getTransactionInfo(); if (internalStatus != Status.STATUS_NO_TRANSACTION) { throw new NotSupportedException("The UserTransaction may not be reused"); } // check if ((propagationBehaviour != TransactionDefinition.PROPAGATION_REQUIRES_NEW)) { if (!readOnly && TransactionSynchronizationManager.isSynchronizationActive() && TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalStateException("Nested writable transaction in a read only transaction"); } } // begin a transaction try { internalTxnInfo = createTransactionIfNecessary((Method) null, (Class<?>) null); // super class will just pass nulls back to us } catch (CannotCreateTransactionException e) { throw new ConnectionPoolException("The DB connection pool is depleted.", e); } internalStatus = Status.STATUS_ACTIVE; threadId = Thread.currentThread().getId(); // Record that transaction details now that begin was successful isBeginMatched = false; if (isCallStackTraced) { // get the stack trace Exception e = new Exception(); e.fillInStackTrace(); beginCallStack = e.getStackTrace(); } // done if (logger.isDebugEnabled()) { logger.debug("Began user transaction: " + this); } }
From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java
private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(final boolean requiresNew, boolean notSupported) throws Exception { if (notSupported) { given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); given(transactionManager.suspend()).willReturn(transaction); } else {/*from w w w.j a v a 2 s . co m*/ given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); } final ContentSource contentSource = mock(ContentSource.class); final Session session1 = mock(Session.class); final Session session2 = mock(Session.class); given(contentSource.newSession()).willReturn(session1, session2); final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager); TransactionTemplate tt = new TransactionTemplate(ptm); tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED : TransactionDefinition.PROPAGATION_SUPPORTS); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); assertSame(session1, ContentSourceUtils.getSession(contentSource)); assertSame(session1, ContentSourceUtils.getSession(contentSource)); TransactionTemplate tt2 = new TransactionTemplate(ptm); tt2.setPropagationBehavior(requiresNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW : TransactionDefinition.PROPAGATION_REQUIRED); tt2.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); assertSame(session2, ContentSourceUtils.getSession(contentSource)); assertSame(session2, ContentSourceUtils.getSession(contentSource)); } }); assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); assertSame(session1, ContentSourceUtils.getSession(contentSource)); } }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); verify(userTransaction).begin(); verify(userTransaction).commit(); if (notSupported) { verify(transactionManager).resume(transaction); } verify(session2).close(); verify(session1).close(); }
From source file:org.alfresco.repo.transaction.AlfrescoTransactionSupport.java
/** * @return Returns the read-write state of the current transaction * @since 2.1.4/* www . ja v a 2s . c om*/ */ public static TxnReadState getTransactionReadState() { if (!TransactionSynchronizationManager.isSynchronizationActive()) { return TxnReadState.TXN_NONE; } // Find the read-write state of the txn if (getResource(RESOURCE_KEY_TXN_COMPLETING) != null) { // Transaction is completing. For all intents and purposes, we are not in a transaction. return TxnReadState.TXN_NONE; } else if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { return TxnReadState.TXN_READ_ONLY; } else { return TxnReadState.TXN_READ_WRITE; } }
From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateTemplate.java
protected boolean isCurrentTransactionReadOnly() { if (TransactionSynchronizationManager.hasResource(sessionFactory)) { if (TransactionSynchronizationManager.isActualTransactionActive()) { return TransactionSynchronizationManager.isCurrentTransactionReadOnly(); } else {//w ww . jav a 2 s .co m return osivReadOnly; } } else { return false; } }
From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsSessionContext.java
/** * Retrieve the Spring-managed Session for the current thread, if any. */// ww w. j a v a 2s.co m public Session currentSession() throws HibernateException { Object value = TransactionSynchronizationManager.getResource(sessionFactory); if (value instanceof Session) { return (Session) value; } if (value instanceof SessionHolder) { SessionHolder sessionHolder = (SessionHolder) value; Session session = sessionHolder.getSession(); if (TransactionSynchronizationManager.isSynchronizationActive() && !sessionHolder.isSynchronizedWithTransaction()) { TransactionSynchronizationManager .registerSynchronization(createSpringSessionSynchronization(sessionHolder)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session // with FlushMode.MANUAL, which needs to allow flushing within the transaction. FlushMode flushMode = session.getFlushMode(); if (FlushMode.isManualFlushMode(flushMode) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } return session; } if (jtaSessionContext != null) { Session session = jtaSessionContext.currentSession(); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager .registerSynchronization(createSpringFlushSynchronization(session)); } return session; } if (allowCreate) { // be consistent with older HibernateTemplate behavior return createSession(value); } throw new HibernateException("No Session found for current thread"); }
From source file:org.springframework.data.neo4j.transaction.SessionFactoryUtils.java
public static Session getSession(SessionFactory sessionFactory) throws IllegalStateException { Assert.notNull(sessionFactory, "No SessionFactory specified"); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null) { if (!sessionHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) { sessionHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager .registerSynchronization(new SessionSynchronization(sessionHolder, sessionFactory, false)); }/* w ww . j a v a 2 s . co m*/ return sessionHolder.getSession(); } if (!TransactionSynchronizationManager.isSynchronizationActive()) { return null; } Session session = sessionFactory.openSession(); if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { System.out.println("hitting read only txn."); } logger.debug("Registering transaction synchronization for Neo4j Session"); // Use same Session for further Neo4j actions within the transaction. // Thread object will get removed by synchronization at transaction completion. sessionHolder = new SessionHolder(session); sessionHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager .registerSynchronization(new SessionSynchronization(sessionHolder, sessionFactory, true)); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); return session; }
From source file:org.springframework.data.redis.core.RedisConnectionUtils.java
private static boolean isActualNonReadonlyTransactionActive() { return TransactionSynchronizationManager.isActualTransactionActive() && !TransactionSynchronizationManager.isCurrentTransactionReadOnly(); }
From source file:org.springframework.data.redis.core.RedisConnectionUtils.java
/** * Closes the given connection, created via the given factory if not managed externally (i.e. not bound to the * thread)./* www. j ava 2s . c o m*/ * * @param conn the Redis connection to close * @param factory the Redis factory that the connection was created with */ public static void releaseConnection(RedisConnection conn, RedisConnectionFactory factory) { if (conn == null) { return; } RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager .getResource(factory); if (connHolder != null && connHolder.isTransactionSyncronisationActive()) { if (log.isDebugEnabled()) { log.debug("Redis Connection will be closed when transaction finished."); } return; } // release transactional/read-only and non-transactional/non-bound connections. // transactional connections for read-only transactions get no synchronizer registered if (isConnectionTransactional(conn, factory) && TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { unbindConnection(factory); } else if (!isConnectionTransactional(conn, factory)) { if (log.isDebugEnabled()) { log.debug("Closing Redis Connection"); } conn.close(); } }
From source file:org.springframework.integration.sqs.SQSInboundGateway.java
/** * {@inheritDoc}//from www . ja v a 2 s. c o m */ public Message<Object> receive() { if (transaction && (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly())) { throw new IllegalStateException("An active non read only transaction is required!"); } String queueName = getQueueName(); final com.amazonaws.queue.doc._2009_02_01.Message message = template.receive(queueName); log.debug("Pulled message: " + message); if (message == null) { return null; } Message<Object> result = handleReceivedMessage(message); postReceive(queueName, message); return result; }
From source file:org.springframework.orm.hibernate.SessionFactoryUtils.java
/** * Get a Hibernate Session for the given SessionFactory. Is aware of and will * return any existing corresponding Session bound to the current thread, for * example when using {@link HibernateTransactionManager}. Will create a new * Session otherwise, if "allowCreate" is <code>true</code>. * @param sessionFactory Hibernate SessionFactory to create the session with * @param entityInterceptor Hibernate entity interceptor, or <code>null</code> if none * @param jdbcExceptionTranslator SQLExceptionTranslator to use for flushing the * Session on transaction synchronization (may be <code>null</code>) * @param allowCreate whether a non-transactional Session should be created * when no transactional Session can be found for the current thread * @return the Hibernate Session// w w w . j a v a2 s . c om * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and * "allowCreate" is <code>false</code> */ private static Session getSession(SessionFactory sessionFactory, Interceptor entityInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { Assert.notNull(sessionFactory, "No SessionFactory specified"); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (sessionHolder != null && !sessionHolder.isEmpty()) { // pre-bound Hibernate Session Session session = null; if (TransactionSynchronizationManager.isSynchronizationActive() && sessionHolder.doesNotHoldNonDefaultSession()) { // Spring transaction management is active -> // register pre-bound Session with it for transactional flushing. session = sessionHolder.getValidatedSession(); if (!sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Hibernate Session"); TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization( sessionHolder, sessionFactory, jdbcExceptionTranslator, false)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO if we're not within a read-only transaction. FlushMode flushMode = session.getFlushMode(); if (FlushMode.NEVER.equals(flushMode) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } else { // No Spring transaction management active -> try JTA transaction synchronization. session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator); } if (session != null) { return session; } } try { logger.debug("Opening Hibernate Session"); Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession()); // Set Session to FlushMode.NEVER if we're within a read-only transaction. // 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. logger.debug("Registering Spring transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else { holderToUse.addSession(session); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.NEVER); } TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization( holderToUse, sessionFactory, jdbcExceptionTranslator, true)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } else { // No Spring transaction management active -> try JTA transaction synchronization. registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder); } // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, sessionFactory)) { doClose(session); throw new IllegalStateException("No Hibernate Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return session; } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }