@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);
 }
    @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);
      }
    }
Exemplo n.º 3
0
  @Override
  protected void tearDown() throws Exception {
    TransactionSynchronizationManager.unbindResource(sessionFactory);
    SessionFactoryUtils.releaseSession(session, sessionFactory);

    super.tearDown();
  }
  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();
  }
 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());
     }
   }
 }
 private boolean unbindEntityManager(EntityManager em) {
   if (TransactionSynchronizationManager.hasResource(entityManagerFactory)) {
     TransactionSynchronizationManager.unbindResource(entityManagerFactory);
     return true;
   }
   return false;
 }
  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();
  }
  /* (non-Javadoc)
   * @see org.jobcenter.internalservice.SetUpHibernateSessionForNonWebRequestProcessing#closeSession()
   */
  public void closeSession() {

    if (sessionFactory != null) {

      SessionHolder sessionHolder =
          (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);

      SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
  }
  /*
   * @seeorg.springframework.jdbc.datasource.DataSourceTransactionManager#
   * doCleanupAfterCompletion(java.lang.Object)
   */
  public void doCleanupAfterCompletion(Object transaction) {
    log.debug("Cleaning stored transaction synchronization");
    TransactionSynchronizationManager.unbindResource(getTransactionSynchronizationKey());

    CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction;
    CompensatingTransactionHolderSupport transactionHolderSupport = txObject.getHolder();

    closeTargetResource(transactionHolderSupport);

    txObject.getHolder().clear();
  }
Exemplo n.º 10
0
  @Override
  public void commit() {

    if (txLogger.isInfoEnabled()) {
      txLogger.info("commit");
    }

    ThreadContext.Context ctx = ThreadContext.getContext(this.metaData.getName());

    if (ctx == null) {
      if (txLogger.isWarnEnabled()) {
        txLogger.warn("ignoring commit - no tx in progress");
        if (txLogger.isDebugEnabled()) {
          logStackTrace();
        }
      }
      return;
    }

    TransactionStatus txStatus = ctx.getTransactionStatus();

    try {
      if (txStatus == null) {
        if (txLogger.isWarnEnabled()) {
          txLogger.warn("ignoring commit - no tx status");
          if (txLogger.isDebugEnabled()) {
            logStackTrace();
          }
        }
      } else {
        this.txMgr.commit(txStatus);
      }
    } finally {
      ctx.setTransactionStatus(null);
      ThreadContext.unsetContext(this.metaData.getName());
      HashMap<String, ThreadContext.Context> contextHash = ThreadContext.getThreadLocalHash();

      if (contextHash != null && contextHash.size() > 0) {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
          TransactionSynchronizationManager.initSynchronization();
        }
      } else {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
          TransactionSynchronizationManager.clear();
          Map map = TransactionSynchronizationManager.getResourceMap();
          for (Object entry : map.keySet()) {
            TransactionSynchronizationManager.unbindResource(entry);
          }
        }
      }
    }
  }
 /**
  * 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());
     }
   }
 }
Exemplo n.º 12
0
 @Override
 public void suspend() {
   if (this.holderActive) {
     TransactionSynchronizationManager.unbindResource(this.dataSource);
     if (this.connectionHolder.hasConnection() && !this.connectionHolder.isOpen()) {
       // Release Connection on suspend if the application doesn't keep
       // a handle to it anymore. We will fetch a fresh Connection if the
       // application accesses the ConnectionHolder again after resume,
       // assuming that it will participate in the same transaction.
       releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
       this.connectionHolder.setConnection(null);
     }
   }
 }
  @Override
  protected void doCleanupAfterCompletion(Object transaction) {
    JpaTransactionObject txObject = (JpaTransactionObject) transaction;

    // Remove the entity manager holder from the thread.
    if (txObject.isNewEntityManagerHolder()) {
      TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
    }
    txObject.getEntityManagerHolder().clear();

    // Remove the JDBC connection holder from the thread, if exposed.
    if (txObject.hasConnectionHolder()) {
      TransactionSynchronizationManager.unbindResource(getDataSource());
      try {
        getJpaDialect()
            .releaseJdbcConnection(
                txObject.getConnectionHolder().getConnectionHandle(),
                txObject.getEntityManagerHolder().getEntityManager());
      } catch (Exception ex) {
        // Just log it, to keep a transaction-related exception.
        logger.error("Could not close JDBC connection after transaction", ex);
      }
    }

    getJpaDialect().cleanupTransaction(txObject.getTransactionData());

    // Remove the entity manager holder from the thread.
    if (txObject.isNewEntityManagerHolder()) {
      EntityManager em = txObject.getEntityManagerHolder().getEntityManager();
      if (logger.isDebugEnabled()) {
        logger.debug("Closing JPA EntityManager [" + em + "] after transaction");
      }
      EntityManagerFactoryUtils.closeEntityManager(em);
    } else {
      logger.debug("Not closing pre-bound JPA EntityManager after transaction");
    }
  }
 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();
   }
 }
Exemplo n.º 15
0
 @Override
 public void beforeCompletion() {
   // Release Connection early if the holder is not open anymore
   // (that is, not used by another resource like a Hibernate Session
   // that has its own cleanup via transaction synchronization),
   // to avoid issues with strict JTA implementations that expect
   // the close call before transaction completion.
   if (!this.connectionHolder.isOpen()) {
     TransactionSynchronizationManager.unbindResource(this.dataSource);
     this.holderActive = false;
     if (this.connectionHolder.hasConnection()) {
       releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
     }
   }
 }
 private void unbindSession() {
   if (sessionFactory == null) {
     throw new IllegalStateException("No sessionFactory property provided");
   }
   SessionHolder sessionHolder =
       (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
   try {
     if (!FlushMode.MANUAL.equals(sessionHolder.getSession().getFlushMode())) {
       sessionHolder.getSession().flush();
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     TransactionSynchronizationManager.unbindResource(sessionFactory);
     SessionFactoryUtils.closeSession(sessionHolder.getSession());
   }
 }
  @Override
  protected void doCleanupAfterCompletion(final Object transaction) {
    try {
      super.doCleanupAfterCompletion(transaction);
    } finally {
      JdbcTransactionObjectSupport transactionObj = (JdbcTransactionObjectSupport) transaction;
      EntityManager em = _newTransactionObjects.remove(transactionObj);

      if (em != null) {
        EntityManagerHolder holder =
            (EntityManagerHolder)
                TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
        LOGGER.debug(
            "doCleanupAfterCompletion() unbound holder [{}] and removed transactionObj [{}]",
            holder,
            transactionObj);
      }
    }
  }
 @Override
 public void afterCompletion(int status) {
   RestPostProcessorDelegate.LOG.info("Transaction completed");
   try {
     if (status == STATUS_COMMITTED) {
       RestPostProcessorDelegate.LOG.info("Transaction was committed, sending events.");
       List<String> eventLog =
           (List<String>) TransactionSynchronizationManager.getResource(EVENT_LOG_KEY);
       eventLogSender.send(eventLog);
     } else {
       RestPostProcessorDelegate.LOG.info(
           "Transaction was not committed, status was " + status + ", not sending events.");
     }
   } catch (IOException e) {
     throw new RuntimeException("Failed to send the event log.", e);
   } finally {
     TransactionSynchronizationManager.unbindResource(EVENT_LOG_KEY);
   }
 }
Exemplo n.º 19
0
  /** @param args */
  public static void main(String[] args) throws Exception {
    System.out.println("Starting up... " + new Date());
    logger.info("Starting up...");
    ApplicationContext context = new ClassPathXmlApplicationContext("rssAggregatorContext.xml");
    SessionFactory sessionFactory = context.getBean(SessionFactory.class);

    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));

    RSSAggregatorService rssAggregatorService =
        context.getBean("rssAggregatorService", RSSAggregatorService.class);
    rssAggregatorService.checkActiveFeedsForUpdates();

    // check the feeds?

    TransactionSynchronizationManager.unbindResource(sessionFactory);
    SessionFactoryUtils.releaseSession(session, sessionFactory);

    System.out.println("Finished at " + new Date());
    logger.info("Finished");
  }
  @Test
  public void testDoGetEntityManagerWithTx() throws Exception {
    try {
      EntityManagerFactory factory = mock(EntityManagerFactory.class);
      EntityManager manager = mock(EntityManager.class);

      TransactionSynchronizationManager.initSynchronization();
      given(factory.createEntityManager()).willReturn(manager);

      // no tx active
      assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
      assertSame(
          manager,
          ((EntityManagerHolder) TransactionSynchronizationManager.unbindResource(factory))
              .getEntityManager());
    } finally {
      TransactionSynchronizationManager.clearSynchronization();
    }

    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
  }
 @Override
 public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
   String participateAttributeName = getParticipateAttributeName();
   Integer count =
       (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
   if (count != null) {
     // Do not modify the PersistenceManager: just clear the marker.
     if (count > 1) {
       request.setAttribute(participateAttributeName, count - 1, WebRequest.SCOPE_REQUEST);
     } else {
       request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
     }
   } else {
     PersistenceManagerHolder pmHolder =
         (PersistenceManagerHolder)
             TransactionSynchronizationManager.unbindResource(getPersistenceManagerFactory());
     logger.debug("Closing JDO PersistenceManager in OpenPersistenceManagerInViewInterceptor");
     PersistenceManagerFactoryUtils.releasePersistenceManager(
         pmHolder.getPersistenceManager(), getPersistenceManagerFactory());
   }
 }
Exemplo n.º 22
0
  public void upgradeLevels() throws Exception {
    TransactionSynchronizationManager.initSynchronization();
    Connection c = DataSourceUtils.getConnection(dataSource);
    c.setAutoCommit(false);

    try {
      List<User> users = userDao.getAll();
      for (User user : users) {
        if (canUpgradeLevel(user)) {
          upgradeLevel(user);
        }
      }
      c.commit();
    } catch (Exception e) {
      c.rollback();
      throw e;
    } finally {
      DataSourceUtils.releaseConnection(c, dataSource);
      TransactionSynchronizationManager.unbindResource(this.dataSource);
      TransactionSynchronizationManager.clearSynchronization();
    }
  }
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    AsyncExecutionChain chain = AsyncExecutionChain.getForCurrentRequest(request);

    SessionFactory sessionFactory = lookupSessionFactory(request);
    boolean participate = false;

    if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
      // Do not modify the Session: just set the participate flag.
      participate = true;
    } else {
      logger.debug("Opening Hibernate Session in OpenSessionInViewFilter");
      Session session = openSession(sessionFactory);
      SessionHolder sessionHolder = new SessionHolder(session);
      TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);

      chain.push(getAsyncCallable(request, sessionFactory, sessionHolder));
    }

    try {
      filterChain.doFilter(request, response);
    } finally {
      if (!participate) {
        SessionHolder sessionHolder =
            (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
        if (!chain.pop()) {
          return;
        }
        logger.debug("Closing Hibernate Session in OpenSessionInViewFilter");
        SessionFactoryUtils.closeSession(sessionHolder.getSession());
      }
    }
  }
Exemplo n.º 24
0
 public void beforeCompletion() {
   TransactionSynchronizationManager.unbindResource(this.sessionFactory);
   this.holderActive = false;
 }
Exemplo n.º 25
0
 @After
 public void tearDown() {
   SessionHolder sessionHolder =
       (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
   SessionFactoryUtils.closeSession(sessionHolder.getSession());
 }
 @Override
 public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
   TransactionSynchronizationManager.unbindResource(this.sessionFactory);
 }
  @Override
  protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    try {
      logger.debug("running offer update rules job:" + Calendar.getInstance().getTimeInMillis());

      // bind session to thread
      Session session = null;
      try {
        session = SessionFactoryUtils.getSession(sessionFactory, false);
      }
      // If not already bound the Create and Bind it!
      catch (java.lang.IllegalStateException ex) {
        session = SessionFactoryUtils.getSession(sessionFactory, true);
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
      }
      session.setFlushMode(FlushMode.AUTO);

      // find awards whose offers are expired only on bl failure
      // really should fire working memory rules against rater that has expired
      // awards

      List<Offer> expired = awardManagerService.findExpiredAwardOffers();

      logger.debug("number of expired offers:" + expired.size());

      /*for (AwardOffer awardOffer : expired) {
      	//logger.debug(awardOffer.getOffer().getExpireDateMillis());

      	//delete any expired offer
      	//remove the offer from the award
      	Award a = awardOffer.getAward();
      	a.getOffers().remove(awardOffer);
      	awardManagerService.saveAward(a);

      	awardManagerService.deleteAwardOffer(awardOffer);

      	if(awardOffer.getAward() != null)
      	{
      		//dont throw if one has a problem
      		try {
      			updateAwardOfferMessageProducer
      			.generateMessage(
      					awardOffer.getAward(),
      					awardOffer.getAwardType(),
      					awardOffer.getAward().getOwner());
      		} catch (JsonGenerationException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (JsonMappingException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (JMSException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (IOException e) {
      			logger.error("problem udating expired offer", e);
      		}
      	}


      }*/

    } catch (com.noi.utility.spring.service.BLServiceException e) {
      logger.error("problem updating expired offers", e);
      throw new JobExecutionException(e);
    } catch (Exception e) {
      logger.error("problem updating expired offers", e);
      throw new JobExecutionException(e);
    } finally {
      // unbind
      SessionHolder sessionHolder =
          (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
      if (!FlushMode.MANUAL.equals(sessionHolder.getSession().getFlushMode())) {
        sessionHolder.getSession().flush();
      }
      SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
  }
Exemplo n.º 28
0
  public static void unbindSessionFromThread(SessionFactory sessionFactory) {
    SessionHolder sessionHolder =
        (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);

    SessionFactoryUtils.closeSession(sessionHolder.getSession());
  }
Exemplo n.º 29
0
 public void suspend() {
   if (this.holderActive) {
     TransactionSynchronizationManager.unbindResource(this.sessionFactory);
   }
 }