Example #1
0
  /**
   * Get a TopLink Session for the given SessionFactory. Is aware of and will return any existing
   * corresponding Session bound to the current thread, for example when using
   * TopLinkTransactionManager. Will create a new Session otherwise, if allowCreate is true.
   *
   * <p>Same as <code>getSession</code>, but throwing the original TopLinkException.
   *
   * @param sessionFactory TopLink SessionFactory to create the session with
   * @param allowCreate if a non-transactional Session should be created when no transactional
   *     Session can be found for the current thread
   * @return the TopLink Session
   * @throws TopLinkException if the Session couldn't be created
   * @throws IllegalStateException if no thread-bound Session found and allowCreate false
   * @see #releaseSession
   * @see TopLinkTemplate
   */
  public static Session doGetSession(SessionFactory sessionFactory, boolean allowCreate)
      throws TopLinkException, IllegalStateException {

    Assert.notNull(sessionFactory, "No SessionFactory specified");

    SessionHolder sessionHolder =
        (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null) {
      return sessionHolder.getSession();
    }

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

    logger.debug("Creating TopLink Session");
    Session session = sessionFactory.createSession();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
      logger.debug("Registering new Spring transaction synchronization for new TopLink Session");
      // Use same Session for further TopLink 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));
      TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
    }

    return session;
  }
  public void testInterceptorWithThreadBoundAndFlushAlways() {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    session.isOpen();
    sessionControl.setReturnValue(true, 1);
    session.getFlushMode();
    sessionControl.setReturnValue(FlushMode.AUTO, 1);
    session.setFlushMode(FlushMode.ALWAYS);
    sessionControl.setVoidCallable(1);
    session.setFlushMode(FlushMode.AUTO);
    sessionControl.setVoidCallable(1);
    sfControl.replay();
    sessionControl.replay();

    TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    interceptor.setFlushMode(HibernateInterceptor.FLUSH_ALWAYS);
    try {
      interceptor.invoke(new TestInvocation(sf));
    } catch (Throwable t) {
      fail("Should not have thrown Throwable: " + t.getMessage());
    } finally {
      TransactionSynchronizationManager.unbindResource(sf);
    }

    sfControl.verify();
    sessionControl.verify();
  }
  @Test
  public void testTransactionRollback() {
    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 {
      tmpl.execute(
          new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
              Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb));
              NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb);
              neoDatisTemplate.store(null);
            }
          });
    } 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();
  }
 public Object invoke(MethodInvocation methodInvocation) throws Throwable {
   boolean existingTransaction = false;
   PersistenceManager pm =
       PersistenceManagerFactoryUtils.getPersistenceManager(getPersistenceManagerFactory(), true);
   if (TransactionSynchronizationManager.hasResource(getPersistenceManagerFactory())) {
     logger.debug("Found thread-bound PersistenceManager for JDO interceptor");
     existingTransaction = true;
   } else {
     logger.debug("Using new PersistenceManager for JDO interceptor");
     TransactionSynchronizationManager.bindResource(
         getPersistenceManagerFactory(), new PersistenceManagerHolder(pm));
   }
   try {
     Object retVal = methodInvocation.proceed();
     flushIfNecessary(pm, existingTransaction);
     return retVal;
   } finally {
     if (existingTransaction) {
       logger.debug("Not closing pre-bound JDO PersistenceManager after interceptor");
     } else {
       TransactionSynchronizationManager.unbindResource(getPersistenceManagerFactory());
       PersistenceManagerFactoryUtils.releasePersistenceManager(
           pm, getPersistenceManagerFactory());
     }
   }
 }
  public void testInterceptorWithThreadBoundAndFilters() {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    session.isOpen();
    sessionControl.setReturnValue(true, 1);
    session.enableFilter("myFilter");
    sessionControl.setReturnValue(null, 1);
    session.enableFilter("yourFilter");
    sessionControl.setReturnValue(null, 1);
    session.disableFilter("myFilter");
    sessionControl.setVoidCallable(1);
    session.disableFilter("yourFilter");
    sessionControl.setVoidCallable(1);
    sfControl.replay();
    sessionControl.replay();

    TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    interceptor.setFilterNames(new String[] {"myFilter", "yourFilter"});
    try {
      interceptor.invoke(new TestInvocation(sf));
    } catch (Throwable t) {
      fail("Should not have thrown Throwable: " + t.getMessage());
    } finally {
      TransactionSynchronizationManager.unbindResource(sf);
    }

    sfControl.verify();
    sessionControl.verify();
  }
  @Override
  protected Object doGetTransaction() {
    EntityManagerHolder holder =
        (EntityManagerHolder)
            TransactionSynchronizationManager.getResource(getEntityManagerFactory());

    boolean isNew = false;

    if (holder == null) {
      EntityManager em = _jpaContext.getEm(getEntityManagerFactory());
      holder = new EntityManagerHolder(em);
      TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), holder);
      isNew = true;
    }

    JdbcTransactionObjectSupport transactionObj =
        (JdbcTransactionObjectSupport) super.doGetTransaction();

    if (isNew) {
      _newTransactionObjects.put(transactionObj, holder.getEntityManager());
      LOGGER.debug(
          "doGetTransaction() bound EntityManagerHolder [{}] and saved transactionObj [{}]",
          holder,
          transactionObj);
    } else {
      LOGGER.debug(
          "doGetTransaction() existing EntityManagerHolder, ignoring transactionObj: {}",
          holder,
          transactionObj);
    }

    return transactionObj;
  }
 private boolean unbindEntityManager(EntityManager em) {
   if (TransactionSynchronizationManager.hasResource(entityManagerFactory)) {
     TransactionSynchronizationManager.unbindResource(entityManagerFactory);
     return true;
   }
   return false;
 }
  @Override
  protected Object doGetTransaction() {
    JpaTransactionObject txObject = new JpaTransactionObject();
    txObject.setSavepointAllowed(isNestedTransactionAllowed());

    EntityManagerHolder emHolder =
        (EntityManagerHolder)
            TransactionSynchronizationManager.getResource(getEntityManagerFactory());
    if (emHolder != null) {
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Found thread-bound EntityManager ["
                + emHolder.getEntityManager()
                + "] for JPA transaction");
      }
      txObject.setEntityManagerHolder(emHolder, false);
    }

    if (getDataSource() != null) {
      ConnectionHolder conHolder =
          (ConnectionHolder) TransactionSynchronizationManager.getResource(getDataSource());
      txObject.setConnectionHolder(conHolder);
    }

    return txObject;
  }
 public static List<String> bindAndGetEventLog(EventLogSender eventLogSender) {
   if (!TransactionSynchronizationManager.hasResource(EVENT_LOG_KEY)) {
     TransactionSynchronizationManager.bindResource(EVENT_LOG_KEY, new ArrayList<String>());
     TransactionSynchronizationManager.registerSynchronization(
         new EventLogSynchronization(eventLogSender));
   }
   return (List<String>) TransactionSynchronizationManager.getResource(EVENT_LOG_KEY);
 }
  public void testOpenPersistenceManagerInViewInterceptor() throws Exception {
    MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class);
    PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock();
    MockControl pmControl = MockControl.createControl(PersistenceManager.class);
    PersistenceManager pm = (PersistenceManager) pmControl.getMock();

    OpenPersistenceManagerInViewInterceptor interceptor =
        new OpenPersistenceManagerInViewInterceptor();
    interceptor.setPersistenceManagerFactory(pmf);

    MockServletContext sc = new MockServletContext();
    MockHttpServletRequest request = new MockHttpServletRequest(sc);

    pmf.getPersistenceManager();
    pmfControl.setReturnValue(pm, 1);
    pmfControl.replay();
    pmControl.replay();
    interceptor.preHandle(new ServletWebRequest(request));
    assertTrue(TransactionSynchronizationManager.hasResource(pmf));

    // check that further invocations simply participate
    interceptor.preHandle(new ServletWebRequest(request));

    interceptor.preHandle(new ServletWebRequest(request));
    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    interceptor.preHandle(new ServletWebRequest(request));
    interceptor.postHandle(new ServletWebRequest(request), null);
    interceptor.afterCompletion(new ServletWebRequest(request), null);

    pmfControl.verify();
    pmControl.verify();

    pmfControl.reset();
    pmControl.reset();
    pmfControl.replay();
    pmControl.replay();
    interceptor.postHandle(new ServletWebRequest(request), null);
    assertTrue(TransactionSynchronizationManager.hasResource(pmf));
    pmfControl.verify();
    pmControl.verify();

    pmfControl.reset();
    pmControl.reset();
    pm.close();
    pmControl.setVoidCallable(1);
    pmfControl.replay();
    pmControl.replay();
    interceptor.afterCompletion(new ServletWebRequest(request), null);
    assertFalse(TransactionSynchronizationManager.hasResource(pmf));
    pmfControl.verify();
    pmControl.verify();
  }
  public void testLoggingAutoActivate() throws Throwable {
    assertFalse(
        "Auto-logging of misuse of the wrapper should be off",
        BorrowedConnectionProxy.isCallStackTraced());

    UserTransaction txn = transactionService.getUserTransaction();
    Connection connection;
    try {
      txn.begin();
      // Dig the proxy out of ... somewhere
      ConnectionHolder conHolder =
          (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
      connection = conHolder.getConnection();
      txn.commit();
    } catch (Throwable e) {
      try {
        txn.rollback();
      } catch (Throwable ee) {
      }
      throw e;
    }
    // Now mess with the connection, which is protected by the Hibernate wrapper
    try {
      connection.commit();
      fail("Use case should have generated a HibernateException");
    } catch (HibernateException e) {
      // Expected
    }
    assertTrue(
        "Auto-logging of misuse of the wrapper should now be on",
        BorrowedConnectionProxy.isCallStackTraced());

    // Now start a new transaction and we should see logging
    txn = transactionService.getUserTransaction();
    try {
      txn.begin();
      // Dig the proxy out of ... somewhere
      ConnectionHolder conHolder =
          (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
      connection = conHolder.getConnection();
      txn.commit();
    } catch (Throwable e) {
      try {
        txn.rollback();
      } catch (Throwable ee) {
      }
      throw e;
    }
    // Now mess with the connection, which is protected by the Hibernate wrapper
    try {
      connection.commit();
      fail("Use case should have generated a HibernateException");
    } catch (HibernateException e) {
      // Expected
    }
    // Check for error logs
  }
 @Override
 protected void doResume(Object transaction, Object suspendedResources) {
   SuspendedResourcesHolder resourcesHolder = (SuspendedResourcesHolder) suspendedResources;
   TransactionSynchronizationManager.bindResource(
       getEntityManagerFactory(), resourcesHolder.getEntityManagerHolder());
   if (getDataSource() != null && resourcesHolder.getConnectionHolder() != null) {
     TransactionSynchronizationManager.bindResource(
         getDataSource(), resourcesHolder.getConnectionHolder());
   }
 }
 public Object invoke(MethodInvocation methodInvocation) throws Throwable {
   if (methodInvocation.getMethod().getName().equals("setSomething")) {
     assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
     assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
   } else {
     assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
     assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
   }
   return methodInvocation.proceed();
 }
  @After
  public void tearDown() throws Exception {
    if (this.transactionStatus != null && !this.transactionStatus.isCompleted()) {
      endTransaction();
    }

    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
    assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
  }
 @Override
 protected Session getSession() {
   SessionHolder sessionHolder =
       (SessionHolder) TransactionSynchronizationManager.getResource(jpaDatastore);
   if (sessionHolder == null) {
     Session session = jpaDatastore.connect();
     sessionHolder = new SessionHolder(session);
     TransactionSynchronizationManager.bindResource(jpaDatastore, sessionHolder);
     return session;
   }
   return sessionHolder.getSession();
 }
 /**
  * Prepare a transaction on the given EntityManager, if possible.
  *
  * @param em the EntityManager to prepare
  * @param emf the EntityManagerFactory that the EntityManager has been created with
  * @return an arbitrary object that holds transaction data, if any (to be passed into
  *     cleanupTransaction)
  * @see JpaDialect#prepareTransaction
  */
 private static Object prepareTransaction(EntityManager em, EntityManagerFactory emf) {
   if (emf instanceof EntityManagerFactoryInfo) {
     EntityManagerFactoryInfo emfInfo = (EntityManagerFactoryInfo) emf;
     JpaDialect jpaDialect = emfInfo.getJpaDialect();
     if (jpaDialect != null) {
       return jpaDialect.prepareTransaction(
           em,
           TransactionSynchronizationManager.isCurrentTransactionReadOnly(),
           TransactionSynchronizationManager.getCurrentTransactionName());
     }
   }
   return null;
 }
 public static void doBeforeCommit(final InvokationCallback invokationCallback) {
   if (TransactionSynchronizationManager.isActualTransactionActive()) {
     TransactionSynchronizationManager.registerSynchronization(
         new TransactionSynchronizationAdapter() {
           public void beforeCommit(boolean readOnly) {
             invokationCallback.invoke();
           }
         });
   } else {
     // invoke now
     invokationCallback.invoke();
   }
 }
 public static void afterCommit(final Runnable action) {
   if (TransactionSynchronizationManager.isActualTransactionActive()) {
     TransactionSynchronizationManager.registerSynchronization(
         new TransactionSynchronizationAdapter() {
           @Override
           public void afterCommit() {
             action.run();
           }
         });
   } else {
     action.run();
   }
 }
 /**
  * Process a message received from the provider.
  *
  * <p>Executes the listener, exposing the current JMS Session as thread-bound resource (if
  * "exposeListenerSession" is "true").
  *
  * @param message the received JMS Message
  * @param session the JMS Session to operate on
  * @see #executeListener
  * @see #setExposeListenerSession
  */
 protected void processMessage(Message message, Session session) {
   boolean exposeResource = isExposeListenerSession();
   if (exposeResource) {
     TransactionSynchronizationManager.bindResource(
         getConnectionFactory(), new LocallyExposedJmsResourceHolder(session));
   }
   try {
     executeListener(session, message);
   } finally {
     if (exposeResource) {
       TransactionSynchronizationManager.unbindResource(getConnectionFactory());
     }
   }
 }
 private boolean bindSession() {
   if (sessionFactory == null) {
     throw new IllegalStateException("No sessionFactory property provided");
   }
   final Object inStorage = TransactionSynchronizationManager.getResource(sessionFactory);
   if (inStorage != null) {
     ((SessionHolder) inStorage).getSession().flush();
     return false;
   } else {
     Session session = SessionFactoryUtils.getSession(sessionFactory, true);
     session.setFlushMode(FlushMode.AUTO);
     TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
     return true;
   }
 }
 /**
  * this method checks if there is a transaction active and registers an afterCommit invokation of
  * the InvokationCallback. if there is no transaction active it invokes the InvokationCallback
  * immediately.
  *
  * @param invokationCallback
  */
 public static void doAfterCommit(final InvokationCallback invokationCallback) {
   // currentlly supports spring synchronization
   if (TransactionSynchronizationManager.isActualTransactionActive()) {
     TransactionSynchronizationManager.registerSynchronization(
         new TransactionSynchronizationAdapter() {
           @Override
           public void afterCommit() {
             invokationCallback.invoke();
           }
         });
   } else {
     // invoke now
     invokationCallback.invoke();
   }
 }
 public Object intercept(Invocation invocation) throws Exception {
   try {
     Session session = sessionFactory.openSession();
     session.setFlushMode(FlushMode.MANUAL);
     SessionHolder sessionHolder = new SessionHolder(session);
     TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
     return invocation.invoke();
   } catch (Exception e) {
     throw e;
   } finally {
     SessionHolder sessionHolder =
         (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
     sessionHolder.getSession().close();
   }
 }
 @Override
 protected Object doSuspend(Object transaction) {
   JpaTransactionObject txObject = (JpaTransactionObject) transaction;
   txObject.setEntityManagerHolder(null, false);
   EntityManagerHolder entityManagerHolder =
       (EntityManagerHolder)
           TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
   txObject.setConnectionHolder(null);
   ConnectionHolder connectionHolder = null;
   if (getDataSource() != null && TransactionSynchronizationManager.hasResource(getDataSource())) {
     connectionHolder =
         (ConnectionHolder) TransactionSynchronizationManager.unbindResource(getDataSource());
   }
   return new SuspendedResourcesHolder(entityManagerHolder, connectionHolder);
 }
  @Test
  public void testCreate() {
    OrgPerson person = new OrgPerson();

    person.setId(new Integer(2));
    person.setDescription("some description");
    person.setFullname("Some testperson");
    person.setLastname("testperson");
    person.setCountry("Sweden");
    person.setCompany("company1");

    try {
      this.dummyDao.create(person);
    } catch (CannotCreateTransactionException expected) {
      assertTrue(expected.getCause() instanceof CommunicationException);
    }

    // Make sure there is no transaction synchronization
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

    try {
      this.dummyDao.create(person);
    } catch (CannotCreateTransactionException expected) {
      assertTrue(expected.getCause() instanceof CommunicationException);
    }
  }
  public void testInterceptorWithThreadBoundEmptyHolder() {
    MockControl sfControl = MockControl.createControl(SessionFactory.class);
    SessionFactory sf = (SessionFactory) sfControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    Session session = (Session) sessionControl.getMock();
    sf.openSession();
    sfControl.setReturnValue(session, 1);
    session.getSessionFactory();
    sessionControl.setReturnValue(sf, 1);
    session.flush();
    sessionControl.setVoidCallable(1);
    session.close();
    sessionControl.setReturnValue(null, 1);
    sfControl.replay();
    sessionControl.replay();

    SessionHolder holder = new SessionHolder("key", session);
    holder.removeSession("key");
    TransactionSynchronizationManager.bindResource(sf, holder);
    HibernateInterceptor interceptor = new HibernateInterceptor();
    interceptor.setSessionFactory(sf);
    try {
      interceptor.invoke(new TestInvocation(sf));
    } catch (Throwable t) {
      fail("Should not have thrown Throwable: " + t.getMessage());
    }

    sfControl.verify();
    sessionControl.verify();
  }
 private void bindEntityManager(EntityManager em) {
   if (log.isDebugEnabled()) {
     log.debug("Binding conversation's entityManager: " + em.hashCode());
   }
   TransactionSynchronizationManager.bindResource(
       entityManagerFactory, new EntityManagerHolder(em));
 }
    @Override
    public void afterCompletion(int status) {

      try {
        switch (status) {
          case TransactionSynchronization.STATUS_COMMITTED:
            connection.exec();
            break;

          case TransactionSynchronization.STATUS_ROLLED_BACK:
          case TransactionSynchronization.STATUS_UNKNOWN:
          default:
            connection.discard();
        }
      } finally {

        if (log.isDebugEnabled()) {
          log.debug("Closing bound connection after transaction completed with " + status);
        }

        connHolder.setTransactionSyncronisationActive(false);
        connection.close();
        TransactionSynchronizationManager.unbindResource(factory);
      }
    }
Example #28
0
  @Override
  protected void tearDown() throws Exception {
    TransactionSynchronizationManager.unbindResource(sessionFactory);
    SessionFactoryUtils.releaseSession(session, sessionFactory);

    super.tearDown();
  }
  /**
   * 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>.
   *
   * @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;
  }
 /**
  * Determine whether the given JMS Session is transactional, that is, bound to the current thread
  * by Spring's transaction facilities.
  *
  * @param session the JMS Session to check
  * @param cf the JMS ConnectionFactory that the Session originated from
  * @return whether the Session is transactional
  */
 public static boolean isSessionTransactional(Session session, ConnectionFactory cf) {
   if (session == null || cf == null) {
     return false;
   }
   JmsResourceHolder resourceHolder =
       (JmsResourceHolder) TransactionSynchronizationManager.getResource(cf);
   return (resourceHolder != null && resourceHolder.containsSession(session));
 }