List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager bindResource
public static void bindResource(Object key, Object value) throws IllegalStateException
From source file:org.springextensions.db4o.Db4oTransactionManager.java
protected void doBegin(Object transaction, TransactionDefinition transactionDefinition) throws TransactionException { if (transactionDefinition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { throw new InvalidIsolationLevelException("Db4o does not support an isolation level concept"); }/*from w ww. j a v a2 s . co m*/ ObjectContainer container = null; try { Db4oTransactionObject txObject = (Db4oTransactionObject) transaction; if (txObject.getObjectContainerHolder() == null) { // use the given container container = getObjectContainer(); logger.debug("Using given objectContainer [{}] for the current thread transaction", container); txObject.setObjectContainerHolder(new ObjectContainerHolder(container)); } ObjectContainerHolder containerHolder = txObject.getObjectContainerHolder(); containerHolder.setSynchronizedWithTransaction(true); /* * We have no notion of flushing inside a db4o object container * if (transactionDefinition.isReadOnly() && txObject.isNewObjectContainerHolder()) { containerHolder.setReadOnly(true); } if (!transactionDefinition.isReadOnly() && !txObject.isNewObjectContainerHolder()) { if (containerHolder.isReadOnly()) { containerHolder.setReadOnly(false); } } */ // start the transaction // no-op // Register transaction timeout. if (transactionDefinition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { txObject.getObjectContainerHolder().setTimeoutInSeconds(transactionDefinition.getTimeout()); } // Bind the session holder to the thread. TransactionSynchronizationManager.bindResource(getObjectContainer(), containerHolder); } catch (Exception ex) { throw new CannotCreateTransactionException("Could not start db4o object container transaction", ex); } }
From source file:org.grails.datastore.mapping.core.DatastoreUtils.java
/** * Get a Datastore Session for the given Datastore. Is aware of and will * return any existing corresponding Session bound to the current thread, for * example when using {@link org.grails.datastore.mapping.transactions.DatastoreTransactionManager}. Will create a new * Session otherwise, if "allowCreate" is <code>true</code>. * * @param datastore Datastore to create the session with * 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 Datastore Session//from w w w . j av a 2 s. c o m * @throws IllegalStateException if no thread-bound Session found and * "allowCreate" is <code>false</code> */ public static Session doGetSession(Datastore datastore, boolean allowCreate) { Assert.notNull(datastore, "No Datastore specified"); SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(datastore); if (sessionHolder != null && !sessionHolder.isEmpty()) { // pre-bound Datastore Session Session session; if (TransactionSynchronizationManager.isSynchronizationActive() && sessionHolder.doesNotHoldNonDefaultSession()) { // Spring transaction management is active -> // register pre-bound Session with it for transactional flushing. session = sessionHolder.getValidatedSession(); if (session != null && !sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Datastore Session"); TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(sessionHolder, datastore, false)); sessionHolder.setSynchronizedWithTransaction(true); } if (session != null) { return session; } } else { session = sessionHolder.getValidatedSession(); if (session != null) { return session; } } } logger.debug("Opening Datastore Session"); Session session = datastore.connect(); // Use same Session for further Datastore 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 Datastore Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else { holderToUse.addSession(session); } TransactionSynchronizationManager .registerSynchronization(new SpringSessionSynchronization(holderToUse, datastore, true)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(datastore, holderToUse); } } // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, datastore)) { closeSession(session); throw new IllegalStateException("No Datastore Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return session; }
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 ww . j a v a2 s.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.Db4oTransactionManager.java
protected void doResume(Object transaction, Object suspendedResources) { SuspendedResourcesHolder resourcesHolder = (SuspendedResourcesHolder) suspendedResources; if (TransactionSynchronizationManager.hasResource(getObjectContainer())) { TransactionSynchronizationManager.unbindResource(getObjectContainer()); }//from w w w. ja v a 2 s. c o m TransactionSynchronizationManager.bindResource(getObjectContainer(), resourcesHolder.getObjectContainerHolder()); }
From source file:com.mobileman.filter.OpenSessionFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (webApplicationContext == null) { HttpServletRequest rq1 = (HttpServletRequest) request; String requestURI = rq1.getRequestURI(); if (!requestURI.endsWith(INIT_SERVLET_URI)) { request.getRequestDispatcher(INIT_SERVLET_URI).forward(request, response); return; }/*w w w.j a va2 s . c o m*/ } SessionFactory sessionFactory = lookupSessionFactory(); boolean participate = false; if (sessionFactory != null) { if (isSingleSession()) { // single session mode if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { Session session = getSession(sessionFactory); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); } } else { // deferred close mode if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) { // Do not modify deferred close: just set the participate // flag. participate = true; } else { SessionFactoryUtils.initDeferredClose(sessionFactory); } } } try { filterChain.doFilter(request, response); } finally { if (sessionFactory != null) { if (!participate) { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager .unbindResource(sessionFactory); closeSession(sessionHolder.getSession(), sessionFactory); } else { // deferred close mode SessionFactoryUtils.processDeferredClose(sessionFactory); } } } } }
From source file:org.openvpms.component.business.service.archetype.Notifier.java
/** * Returns the notifier for the given service and current thread. * <p/>/* w w w . j a v a2s .c o m*/ * If one does not exist, it will be created. * * @param service the archetype service * @return the context */ public static Notifier getNotifier(ArchetypeService service) { Notifier notifier; if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!TransactionSynchronizationManager.hasResource(service)) { notifier = new Notifier(service, true); TransactionSynchronizationManager.bindResource(service, notifier); TransactionSynchronizationManager.registerSynchronization(new NotifierSynchronization(notifier)); } else { notifier = (Notifier) TransactionSynchronizationManager.getResource(service); } } else { notifier = new Notifier(service, false); } return notifier; }
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 {/* www . j a v a 2s . 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; }
From source file:org.alfresco.util.transaction.TransactionSupportUtil.java
/** * Binds the Alfresco-specific to the transaction resources * /*from w w w. j av a 2s . c om*/ * @return Returns the current or new synchronization implementation */ private static TransactionSynchronizationImpl registerSynchronizations() { /* * No thread synchronization or locking required as the resources are all threadlocal */ if (!TransactionSynchronizationManager.isSynchronizationActive()) { Thread currentThread = Thread.currentThread(); throw new AlfrescoRuntimeException( "Transaction must be active and synchronization is required: " + currentThread); } TransactionSynchronizationImpl txnSynch = (TransactionSynchronizationImpl) TransactionSynchronizationManager .getResource(RESOURCE_KEY_TXN_SYNCH); if (txnSynch != null) { // synchronization already registered return txnSynch; } // we need a unique ID for the transaction String txnId = GUID.generate(); // register the synchronization txnSynch = new TransactionSynchronizationImpl(txnId); TransactionSynchronizationManager.registerSynchronization(txnSynch); // register the resource that will ensure we don't duplication the synchronization TransactionSynchronizationManager.bindResource(RESOURCE_KEY_TXN_SYNCH, txnSynch); // done if (logger.isDebugEnabled()) { logger.debug("Bound txn synch: " + txnSynch); } return txnSynch; }
From source file:de.codecentric.batch.metrics.BatchMetricsImpl.java
private void initializeMetricContainerAndRegisterTransactionSynchronizationIfNecessary() { if (!TransactionSynchronizationManager.hasResource(serviceKey)) { TransactionSynchronizationManager.bindResource(serviceKey, new StringBuffer()); TransactionSynchronizationManager.registerSynchronization(this); }/*from w ww . j a va 2 s. c o m*/ if (metricContainer.get() == null) { metricContainer.set(new MetricContainer()); } }
From source file:org.hengdao.utils.SqlSessionUtils.java
/** * If a Spring transaction is active it uses {@code DataSourceUtils} to get * a Spring managed {@code Connection}, then creates a new * {@code SqlSession} with this connection and synchronizes it with the * transaction. If there is not an active transaction it gets a connection * directly from the {@code DataSource} and creates a {@code SqlSession} * with it.//from ww w. j a v a 2 s. c o m * * @param sessionFactory * a MyBatis {@code SqlSessionFactory} to create new sessions * @param executorType * The executor type of the SqlSession to create * @param exceptionTranslator * Optional. Translates SqlSession.commit() exceptions to Spring * exceptions. * @throws TransientDataAccessResourceException * if a transaction is active and the {@code SqlSessionFactory} * is not using a {@code SpringManagedTransactionFactory} * @see SpringManagedTransactionFactory */ public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { Assert.notNull(sessionFactory, "No SqlSessionFactory specified"); Assert.notNull(executorType, "No ExecutorType specified"); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (holder != null && holder.isSynchronizedWithTransaction()) { if (holder.getExecutorType() != executorType) { throw new TransientDataAccessResourceException( "Cannot change the ExecutorType when there is an existing transaction"); } holder.requested(); if (logger.isDebugEnabled()) { logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction"); } return holder.getSqlSession(); } DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource(); // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but // we keep this check for the case that SqlSessionUtils is called from // custom code boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy); Connection conn; try { conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e); } if (logger.isDebugEnabled()) { logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]"); } // Assume either DataSourceTransactionManager or the underlying // connection pool already dealt with enabling auto commit. // This may not be a good assumption, but the overhead of checking // connection.getAutoCommit() again may be expensive (?) in some drivers // (see DataSourceTransactionManager.doBegin()). One option would be to // only check for auto commit if this function is being called outside // of DSTxMgr, but to do that we would need to be able to call // ConnectionHolder.isTransactionActive(), which is protected and not // visible to this class. SqlSession session = sessionFactory.openSession(executorType, conn); // Register session holder and bind it to enable synchronization. // // Note: The DataSource 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. if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!(sessionFactory.getConfiguration().getEnvironment() .getTransactionFactory() instanceof SpringManagedTransactionFactory) && DataSourceUtils.isConnectionTransactional(conn, dataSource)) { throw new TransientDataAccessResourceException( "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization"); } 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 (logger.isDebugEnabled()) { logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active"); } } return session; }