List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager bindResource
public static void bindResource(Object key, Object value) throws IllegalStateException
From source file:com.autentia.wuija.persistence.impl.hibernate.HibernateTestUtils.java
/** * Mtodo pensado para usar en los test, de forma que para la ejecucin tengamos una nica sesin. Sera similar a * clases como <code>penSessionInViewFilter</code>. La idea es invocar este mtodo en un <code>@Before</code>. * <p>/*from w w w . j a v a2 s . co m*/ * Este mtodo se debera invocar una nica vez. * <p> * La sesin se "attacha" al contexto, de forma que est disponible para usar desde las transacciones o desde el * <code>HibernteTemplate</code>. Luego se cerrar con el mtodo {@link #closeSessionFromContext()}. */ public void openSessionAndAttachToContext() { Assert.state(sessionAlreadyOpened == null, "A session is already opened: " + ObjectUtils.identityToString(sessionAlreadyOpened)); sessionAlreadyOpened = SessionFactoryUtils.getSession(sessionFactory, true); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(sessionAlreadyOpened)); if (log.isDebugEnabled()) { log.debug("Opened Session: " + ObjectUtils.identityToString(sessionAlreadyOpened) + ", with SessionFactory: " + ObjectUtils.identityToString(sessionFactory)); } }
From source file:com.rainy.redis.connection.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 www .j av 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 IRedisConnection doGetConnection(IRedisConnectionFactory 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"); IRedisConnection conn = factory.getConnection(); if (bind) { connHolder = new RedisConnectionHolder(conn); TransactionSynchronizationManager.bindResource(factory, connHolder); return connHolder.getConnection(); } return conn; }
From source file:corner.orm.gae.impl.EntityManagerSourceImpl.java
public EntityManagerSourceImpl(@Inject @Symbol(SymbolConstants.PRODUCTION_MODE) boolean product, EntityManagerFactory entityManagerFactory, Logger logger, Delegate delegate) { this.entityManagerFactory = entityManagerFactory; this.logger = logger; if (!product) { ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment()); ApiProxy.setDelegate(delegate);//w ww . ja v a2 s. c o m } if (TransactionSynchronizationManager.hasResource(entityManagerFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { logger.debug("Opening single entity manager in EntityManagerSourceImpl"); EntityManager em = entityManagerFactory.createEntityManager(); TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(em)); } }
From source file:com.healthcit.cacure.dao.QuestionDaoTest.java
@Before public void setUp() { // EntityManagerFactory emf = (EntityManagerFactory)context.getBean("entityManagerFactory"); EntityManager em = emf.createEntityManager(); TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em)); }
From source file:ar.com.zauber.commons.repository.closures.OpenSessionClosure.java
/** @see Closure#execute(Object) */ public final void execute(final T t) { if (dryrun) { //permite evitar que se hagan commit() en el ambiente de test target.execute(t);//from w w w .jav a2s . co m } else { final Session session = SessionFactoryUtils.getSession(sessionFactory, true); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); Transaction transaction = null; try { transaction = session.beginTransaction(); target.execute(t); session.flush(); transaction.commit(); } catch (final Throwable e) { if (transaction != null && transaction.isActive()) { transaction.rollback(); } throw new UnhandledException(e); } finally { TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSession(session); } } }
From source file:gov.nih.nci.protexpress.test.ProtExpressBaseHibernateTest.java
/** * {@inheritDoc}//from ww w . j a va 2 s .c o m */ @Override protected void onSetUp() throws Exception { super.onSetUp(); this.csmInitializer.dropAndCreateCsmDb(); User u = new User(); u.setLoginName("~unittestuser~"); UserHolder.setUser(u); LocalSessionFactoryBean theSessionFactoryBean = (LocalSessionFactoryBean) getApplicationContext() .getBean("&sessionFactory"); theSessionFactoryBean.dropDatabaseSchema(); theSessionFactoryBean.createDatabaseSchema(); this.theSessionFactory = (SessionFactory) theSessionFactoryBean.getObject(); this.theSessionFactory.evictQueries(); for (Object o : this.theSessionFactory.getAllClassMetadata().values()) { ClassMetadata cm = (ClassMetadata) o; this.theSessionFactory.evict(cm.getMappedClass(EntityMode.POJO)); } this.theSession = this.theSessionFactory.openSession(); TransactionSynchronizationManager.bindResource(this.theSessionFactory, new SessionHolder(this.theSession)); }
From source file:org.guzz.web.context.spring.SpringSessionSynchronization.java
public void resume() { if (this.holderActive) { TransactionSynchronizationManager.bindResource(this.transactionManager, this.sessionHolder); }/*w w w. j a v a 2s. c o m*/ }
From source file:com.mobileman.projecth.TestCaseBase.java
/** * @throws Exception/* ww w . j a va 2 s. c o m*/ */ @Before public void setUp() throws Exception { sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory"); try { session = SessionFactoryUtils.getSession(sessionFactory, false); if (session == null) { sessionOwner = true; session = SessionFactoryUtils.getSession(sessionFactory, true); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); } else { sessionOwner = false; } } catch (IllegalStateException e) { } if (wiser == null) { wiser = new Wiser(); wiser.setPort(2525); wiser.start(); @SuppressWarnings("unchecked") Map<String, JavaMailSenderImpl> ofType = applicationContext .getBeansOfType(org.springframework.mail.javamail.JavaMailSenderImpl.class); for (Entry<String, JavaMailSenderImpl> bean : ofType.entrySet()) { JavaMailSenderImpl mailSender = bean.getValue(); mailSender.setPort(2525); mailSender.setHost("localhost"); mailSender.setUsername(null); mailSender.setPassword(null); Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "localhost"); props.put("mail.smtp.auth", "false"); mailSender.setJavaMailProperties(props); } } if (wiser.getMessages() != null) { wiser.getMessages().clear(); } }
From source file:podd.dataaccess.AbstractDAOUnitTest.java
@Before public void setUp() throws Exception { // To avoid LazyInitializationException SessionFactory sessionFactory = PODD_CONTEXT.getSessionFactory(); if (!TransactionSynchronizationManager.hasResource(sessionFactory)) { Session session = SessionFactoryUtils.getSession(sessionFactory, true); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); }/*from w ww. j av a 2s. co m*/ pidDao = PODD_CONTEXT.getPIDHolderDAO(); fedoraUtil = PODD_CONTEXT.getFedoraUtil(); entityFactory = PODD_CONTEXT.getEntityFactory(); ontologyHelper = PODD_CONTEXT.getOntologyHelper(); entityValidator = PODD_CONTEXT.getEntityValidator(); pidGenerator = PODD_CONTEXT.getHibernatePIDGenerator(); clearDB(PoddEntity.class); clearDB(UserSearchCriteria.class); clearDB(User.class); clearDB("RepositoryRole"); setupDefaultRepoRoles(); user = entityFactory.createUser(null); populateUser(user); userDAO = getUserDAO(); userDAO.save(user); entity = getEntity(); }
From source file:org.openplans.delayfeeder.RouteStatus.java
/** * Main entry point for the route status server *///from w w w .j av a2s . co m @GET @Produces("application/x-javascript") public JSONWithPadding getStatus(@QueryParam("route") List<String> routes, @QueryParam("callback") String callback) { RouteStatusResponse response = new RouteStatusResponse(); try { Session session = sessionFactory.getCurrentSession(); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); session.beginTransaction(); response.items = new ArrayList<RouteStatusItem>(routes.size()); for (String routeId : routes) { String[] parts = routeId.split(","); if (parts.length != 2) continue; String agency = parts[0]; String route = parts[1]; if (agency == null || route == null) continue; /* get data from cache */ RouteFeedItem item = getLatestItem(agency, route, session); RouteStatusItem status = new RouteStatusItem(); response.items.add(status); /* serve data */ status.agency = agency; status.route = route; if (item != null) { status.status = item.title; status.date = item.date; status.link = item.link; status.category = item.category; } } session.flush(); session.getTransaction().commit(); } finally { TransactionSynchronizationManager.unbindResource(sessionFactory); } return new JSONWithPadding(response, callback); }