JcrInterceptor extends JcrAccessor implements MethodInterceptor { public Object invoke(MethodInvocation methodInvocation) throws Throwable { boolean existingTransaction = false; Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); if (TransactionSynchronizationManager.hasResource(getSessionFactory())) { LOG.debug("Found thread-bound Session for JCR interceptor"); existingTransaction = true; } else { LOG.debug("Using new Session for JCR interceptor"); TransactionSynchronizationManager.bindResource(getSessionFactory(), getSessionFactory().getSessionHolder(session)); } try { Object retVal = methodInvocation.proceed(); return retVal; } finally { if (existingTransaction) { LOG.debug("Not closing pre-bound JCR Session after interceptor"); } else { TransactionSynchronizationManager.unbindResource(getSessionFactory()); SessionFactoryUtils.releaseSession(session, getSessionFactory()); } } }  Object invoke(MethodInvocation methodInvocation);  }
@Test public void testInterceptor() throws RepositoryException { SessionFactory sessionFactory = createMock(SessionFactory.class); Session session = createMock(Session.class); expect(sessionFactory.getSession()).andReturn(session); session.logout(); expectLastCall().once(); expect(sessionFactory.getSessionHolder(session)).andReturn(new SessionHolder(session)); replay(sessionFactory, session); JcrInterceptor interceptor = new JcrInterceptor(); interceptor.setSessionFactory(sessionFactory); interceptor.afterPropertiesSet(); try { interceptor.invoke(new TestInvocation(sessionFactory)); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t); } verify(sessionFactory, session); }
@Test public void testInterceptorWithPrebound() { SessionFactory sessionFactory = createMock(SessionFactory.class); Session session = createMock(Session.class); replay(sessionFactory, session); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); JcrInterceptor interceptor = new JcrInterceptor(); interceptor.setSessionFactory(sessionFactory); interceptor.afterPropertiesSet(); try { interceptor.invoke(new TestInvocation(sessionFactory)); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { TransactionSynchronizationManager.unbindResource(sessionFactory); } verify(sessionFactory, session); }