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.springframework.data.document.mongodb.MongoDbUtils.java
public static DB doGetDB(Mongo mongo, String databaseName, String username, char[] password, boolean allowCreate) { Assert.notNull(mongo, "No Mongo instance specified"); DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo); if (dbHolder != null && !dbHolder.isEmpty()) { // pre-bound Mongo DB DB db = null;// ww w .jav a2s . c o m if (TransactionSynchronizationManager.isSynchronizationActive() && dbHolder.doesNotHoldNonDefaultDB()) { // Spring transaction management is active -> db = dbHolder.getDB(); if (db != null && !dbHolder.isSynchronizedWithTransaction()) { LOGGER.debug("Registering Spring transaction synchronization for existing Mongo DB"); TransactionSynchronizationManager .registerSynchronization(new MongoSynchronization(dbHolder, mongo)); dbHolder.setSynchronizedWithTransaction(true); } } if (db != null) { return db; } } LOGGER.trace("Getting Mongo Database name=[" + databaseName + "]"); DB db = mongo.getDB(databaseName); boolean credentialsGiven = username != null && password != null; if (credentialsGiven && !db.isAuthenticated()) { //Note, can only authenticate once against the same com.mongodb.DB object. if (!db.authenticate(username, password)) { throw new CannotGetMongoDbConnectionException("Failed to authenticate to database [" + databaseName + "], username = [" + username + "], password = [" + new String(password) + "]", databaseName, username, password); } } // Use same Session for further Mongo 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"); DbHolder holderToUse = dbHolder; if (holderToUse == null) { holderToUse = new DbHolder(db); } else { holderToUse.addDB(db); } TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != dbHolder) { TransactionSynchronizationManager.bindResource(mongo, holderToUse); } } // Check whether we are allowed to return the DB. if (!allowCreate && !isDBTransactional(db, mongo)) { throw new IllegalStateException("No Mongo DB bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return db; }
From source file:org.springframework.data.keyvalue.redis.core.RedisConnectionUtils.java
/** * Gets a Redis connection. Is aware of and will return any existing corresponding connections bound to the current thread, * for example when using a transaction manager. Will create a new Connection otherwise, if {@code allowCreate} is <tt>true</tt>. * /* ww w .ja v a 2 s . c o m*/ * @param factory connection factory for creating the connection * @param allowCreate whether a new (unbound) connection should be created when no connection can be found for the current thread * @param bind binds the connection to the thread, in case one was created * @return an active Redis connection */ public static RedisConnection doGetConnection(RedisConnectionFactory factory, boolean allowCreate, boolean bind) { Assert.notNull(factory, "No RedisConnectionFactory specified"); RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager .getResource(factory); //TODO: investigate tx synchronization if (connHolder != null) return connHolder.getConnection(); if (!allowCreate) { throw new IllegalArgumentException("No connection found and allowCreate = false"); } if (log.isDebugEnabled()) log.debug("Opening RedisConnection"); RedisConnection conn = factory.getConnection(); boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive(); if (bind || synchronizationActive) { connHolder = new RedisConnectionHolder(conn); if (synchronizationActive) { TransactionSynchronizationManager .registerSynchronization(new RedisConnectionSynchronization(connHolder, factory, true)); } TransactionSynchronizationManager.bindResource(factory, connHolder); return connHolder.getConnection(); } return conn; }
From source file:org.springframework.data.mongodb.core.MongoDbUtils.java
public static DB doGetDB(Mongo mongo, String databaseName, String username, char[] password, boolean allowCreate) { Assert.notNull(mongo, "No Mongo instance specified"); DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo); if (dbHolder != null && !dbHolder.isEmpty()) { // pre-bound Mongo DB DB db = null;/*from w w w . j a va 2 s . c o m*/ if (TransactionSynchronizationManager.isSynchronizationActive() && dbHolder.doesNotHoldNonDefaultDB()) { // Spring transaction management is active -> db = dbHolder.getDB(databaseName); if (db != null && !dbHolder.isSynchronizedWithTransaction()) { LOGGER.debug("Registering Spring transaction synchronization for existing Mongo DB"); TransactionSynchronizationManager .registerSynchronization(new MongoSynchronization(dbHolder, mongo)); dbHolder.setSynchronizedWithTransaction(true); } } if (db != null) { return db; } } LOGGER.trace("Getting Mongo Database name=[" + databaseName + "]"); DB db = mongo.getDB(databaseName); boolean credentialsGiven = username != null && password != null; if (credentialsGiven && !db.isAuthenticated()) { // Note, can only authenticate once against the same com.mongodb.DB object. synchronized (db) { if (!db.authenticate(username, password)) { throw new CannotGetMongoDbConnectionException( "Failed to authenticate to database [" + databaseName + "], username = [" + username + "], password = [" + new String(password) + "]", databaseName, username, password); } } } // Use same Session for further Mongo 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"); DbHolder holderToUse = dbHolder; if (holderToUse == null) { holderToUse = new DbHolder(databaseName, db); } else { holderToUse.addDB(databaseName, db); } TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != dbHolder) { TransactionSynchronizationManager.bindResource(mongo, holderToUse); } } // Check whether we are allowed to return the DB. if (!allowCreate && !isDBTransactional(db, mongo)) { throw new IllegalStateException("No Mongo DB bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return db; }
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 w w .ja v a2 s. com*/ 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.neo4j.web.support.AsyncRequestInterceptor.java
public void bindSession() { this.timeoutInProgress = false; TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); }
From source file:org.springframework.data.neo4j.web.support.OpenSessionInViewInterceptor.java
@Override public void preHandle(WebRequest request) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult()) { if (applyCallableInterceptor(asyncManager, participateAttributeName)) { return; }/*w ww . j a v a 2s. c om*/ } if (TransactionSynchronizationManager.hasResource(getSessionFactory())) { // Do not modify the Session: just mark the request accordingly. Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { logger.debug("Opening Neo4j OGM Session in OpenSessionInViewInterceptor"); Session session = sessionFactory.openSession(); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getSessionFactory(), sessionHolder); asyncManager.registerCallableInterceptor(participateAttributeName, interceptor); asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor); } }
From source file:org.springframework.data.redis.core.RedisConnectionUtils.java
/** * Gets a Redis connection. Is aware of and will return any existing corresponding connections bound to the current * thread, for example when using a transaction manager. Will create a new Connection otherwise, if * {@code allowCreate} is <tt>true</tt>. * //from w w w .java 2 s . c om * @param factory connection factory for creating the connection * @param allowCreate whether a new (unbound) connection should be created when no connection can be found for the * current thread * @param bind binds the connection to the thread, in case one was created * @param enableTransactionSupport * @return an active Redis connection */ public static RedisConnection doGetConnection(RedisConnectionFactory factory, boolean allowCreate, boolean bind, boolean enableTransactionSupport) { Assert.notNull(factory, "No RedisConnectionFactory specified"); RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager .getResource(factory); if (connHolder != null) { if (enableTransactionSupport) { potentiallyRegisterTransactionSynchronisation(connHolder, factory); } return connHolder.getConnection(); } if (!allowCreate) { throw new IllegalArgumentException("No connection found and allowCreate = false"); } if (log.isDebugEnabled()) { log.debug("Opening RedisConnection"); } RedisConnection conn = factory.getConnection(); if (bind) { RedisConnection connectionToBind = conn; if (enableTransactionSupport && isActualNonReadonlyTransactionActive()) { connectionToBind = createConnectionProxy(conn, factory); } connHolder = new RedisConnectionHolder(connectionToBind); TransactionSynchronizationManager.bindResource(factory, connHolder); if (enableTransactionSupport) { potentiallyRegisterTransactionSynchronisation(connHolder, factory); } return connHolder.getConnection(); } return conn; }
From source file:org.springframework.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.springframework.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 ww.jav a 2s. c o m*/ * @throws IllegalStateException if no thread-bound Session found and * "allowCreate" is <code>false</code> */ private 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.getSession(); 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; } } } 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.springframework.datastore.mapping.web.support.OpenSessionInViewInterceptor.java
public void preHandle(WebRequest webRequest) throws Exception { if (!hasSessionBound()) { // single session mode LOG.debug("Opening single Datastore Session in OpenSessionInViewInterceptor"); Session session = DatastoreUtils.getSession(datastore, true); session.setFlushMode(flushMode); if (!hasSessionBound()) { TransactionSynchronizationManager.bindResource(getDatastore(), new SessionHolder(session)); }//from ww w.j a v a 2 s . c om } }
From source file:org.springframework.jca.cci.connection.ConnectionFactoryUtils.java
/** * Actually obtain a CCI Connection from the given ConnectionFactory. * Same as {@link #getConnection}, but throwing the original ResourceException. * <p>Is aware of a corresponding Connection bound to the current thread, for example * when using {@link CciLocalTransactionManager}. Will bind a Connection to the thread * if transaction synchronization is active (e.g. if in a JTA transaction). * <p>Directly accessed by {@link TransactionAwareConnectionFactoryProxy}. * @param cf the ConnectionFactory to obtain Connection from * @return a CCI Connection from the given ConnectionFactory * @throws ResourceException if thrown by CCI API methods * @see #doReleaseConnection/*from w ww. j a va 2 s . c o m*/ */ public static Connection doGetConnection(ConnectionFactory cf) throws ResourceException { Assert.notNull(cf, "No ConnectionFactory specified"); ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(cf); if (conHolder != null) { return conHolder.getConnection(); } logger.debug("Opening CCI Connection"); Connection con = cf.getConnection(); if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering transaction synchronization for CCI Connection"); conHolder = new ConnectionHolder(con); conHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.registerSynchronization(new ConnectionSynchronization(conHolder, cf)); TransactionSynchronizationManager.bindResource(cf, conHolder); } return con; }