Search in sources :

Example 6 with UserTransaction

use of javax.transaction.UserTransaction in project jBPM5-Developer-Guide by Salaboy.

the class MultiSessionsPatternsTest method multiSessionsWithSessionLocator.

/**
     * This test uses the concept of a SessionLocator to register slaves sessions.
     * Based on rules, the master session decides which (process definition), 
     * when (declaratively expressed with rules) and where (in which slave session)
     * to start a process instance.
     */
@Test
public void multiSessionsWithSessionLocator() throws Exception {
    EntityManager em = getEmf().createEntityManager();
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    StatefulKnowledgeSession interactionSession = null;
    BusinessEntity interactionSessionEntity = null;
    try {
        // This needs to happen in the same transaction if I want to keep it consistent
        ut.begin();
        interactionSession = createProcessInteractionKnowledgeSession("InteractionSession", em);
        interactionSessionEntity = new BusinessEntity(interactionSession.getId(), 0, 0, "InteractionSession");
        // I need to join the Drools/jBPM transaction 
        em.joinTransaction();
        em.persist(interactionSessionEntity);
        ut.commit();
    } catch (Exception e) {
        System.out.println("Rolling Back because of: " + e.getMessage());
        ut.rollback();
    }
    assertNotNull(interactionSessionEntity);
    assertNotNull(interactionSessionEntity.getId());
    interactionSession.dispose();
    // Let's create a session which contains a process and register it in the interaction session:
    StatefulKnowledgeSession processSession = createProcessOneKnowledgeSessionAndRegister("My Business Unit Session", interactionSessionEntity, em);
    processSession.dispose();
    Person person = new Person("Salaboy", 29);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", person);
    interactionSession = loadKnowldgeSession(interactionSessionEntity.getSessionId(), "InteractionSession", em);
    KnowledgeRuntimeLoggerFactory.newConsoleLogger(interactionSession);
    interactionSession.setGlobal("em", em);
    interactionSession.setGlobal("ksessionSupport", this);
    // Let's insert a fact in the master session and let the rules choose the appropriate session for us to start a process
    interactionSession.insert(person);
    // The process will be selected and started. Because it contains an async activity a new BusinessEntity will be created
    interactionSession.fireAllRules();
    // Look for all the pending Business Keys which represent an interaction and insert them into the interaction session
    List<BusinessEntity> pendingBusinessEntities = em.createQuery("select be from BusinessEntity be where  " + " be.active = true").getResultList();
    for (BusinessEntity be : pendingBusinessEntities) {
        if (!be.getBusinessKey().equals("InteractionSession")) {
            interactionSession.insert(be);
        }
    }
    // As soon as we add Data the completion will be triggered and the process will continue
    interactionSession.insert(new Data());
    interactionSession.fireAllRules();
    interactionSession.dispose();
}
Also used : UserTransaction(javax.transaction.UserTransaction) HashMap(java.util.HashMap) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) Data(com.salaboy.model.Data) BusinessEntity(com.salaboy.sessions.patterns.BusinessEntity) InitialContext(javax.naming.InitialContext) EntityManager(javax.persistence.EntityManager) Person(com.salaboy.model.Person) Test(org.junit.Test)

Example 7 with UserTransaction

use of javax.transaction.UserTransaction in project jersey by jersey.

the class TransactionManager method manage.

public static void manage(Transactional t) {
    UserTransaction utx = getUtx();
    try {
        utx.begin();
        if (t.joinTransaction) {
            t.em.joinTransaction();
        }
        t.transact();
        utx.commit();
    } catch (Exception e) {
        try {
            utx.rollback();
        } catch (SystemException se) {
            throw new WebApplicationException(se);
        }
        throw new WebApplicationException(e);
    } finally {
        t.em.close();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) SystemException(javax.transaction.SystemException) WebApplicationException(javax.ws.rs.WebApplicationException) SystemException(javax.transaction.SystemException) WebApplicationException(javax.ws.rs.WebApplicationException) NamingException(javax.naming.NamingException)

Example 8 with UserTransaction

use of javax.transaction.UserTransaction in project hibernate-orm by hibernate.

the class JBossStandaloneJtaExampleTest method testPersistAndLoadUnderJta.

@Test
public void testPersistAndLoadUnderJta() throws Exception {
    Item item;
    SessionFactory sessionFactory = buildSessionFactory();
    try {
        UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertTrue(session.getTransaction().isActive());
            item = new Item("anItem", "An item owned by someone");
            session.persist(item);
            // IMO the flush should not be necessary, but session.close() does not flush
            // and the item is not persisted.
            session.flush();
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }
        ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertTrue(session.getTransaction().isActive());
            Item found = (Item) session.load(Item.class, item.getId());
            Statistics stats = session.getSessionFactory().getStatistics();
            log.info(stats.toString());
            assertEquals(item.getDescription(), found.getDescription());
            assertEquals(0, stats.getSecondLevelCacheMissCount());
            assertEquals(1, stats.getSecondLevelCacheHitCount());
            session.delete(found);
            // IMO the flush should not be necessary, but session.close() does not flush
            // and the item is not deleted.
            session.flush();
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }
        ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertTrue(session.getTransaction().isActive());
            assertNull(session.get(Item.class, item.getId()));
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }
    } finally {
        if (sessionFactory != null)
            sessionFactory.close();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) UserTransaction(javax.transaction.UserTransaction) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) Statistics(org.hibernate.stat.Statistics) NameNotFoundException(javax.naming.NameNotFoundException) Session(org.hibernate.Session) Test(org.junit.Test)

Example 9 with UserTransaction

use of javax.transaction.UserTransaction in project spring-framework by spring-projects.

the class WebLogicJtaTransactionManager method retrieveUserTransaction.

@Override
protected UserTransaction retrieveUserTransaction() throws TransactionSystemException {
    loadWebLogicTransactionHelper();
    try {
        logger.debug("Retrieving JTA UserTransaction from WebLogic TransactionHelper");
        Method getUserTransactionMethod = this.transactionHelper.getClass().getMethod("getUserTransaction");
        return (UserTransaction) getUserTransactionMethod.invoke(this.transactionHelper);
    } catch (InvocationTargetException ex) {
        throw new TransactionSystemException("WebLogic's TransactionHelper.getUserTransaction() method failed", ex.getTargetException());
    } catch (Exception ex) {
        throw new TransactionSystemException("Could not invoke WebLogic's TransactionHelper.getUserTransaction() method", ex);
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Method(java.lang.reflect.Method) TransactionSystemException(org.springframework.transaction.TransactionSystemException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NotSupportedException(javax.transaction.NotSupportedException) TransactionSystemException(org.springframework.transaction.TransactionSystemException) SystemException(javax.transaction.SystemException) InvalidTransactionException(javax.transaction.InvalidTransactionException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 10 with UserTransaction

use of javax.transaction.UserTransaction in project spring-framework by spring-projects.

the class JtaTransactionManagerTests method jtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly.

@Test
public void jtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception {
    UserTransaction ut = mock(UserTransaction.class);
    given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
    willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly();
    try {
        JtaTransactionManager ptm = newJtaTransactionManager(ut);
        TransactionTemplate tt = new TransactionTemplate(ptm);
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                status.setRollbackOnly();
            }
        });
        fail("Should have thrown TransactionSystemException");
    } catch (TransactionSystemException ex) {
    // expected
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) JtaTransactionManager(org.springframework.transaction.jta.JtaTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.Test)

Aggregations

UserTransaction (javax.transaction.UserTransaction)224 Test (org.junit.Test)105 Context (javax.naming.Context)47 JtaTransactionManager (org.springframework.transaction.jta.JtaTransactionManager)46 Node (javax.jcr.Node)42 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)42 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)42 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)35 DataSource (javax.sql.DataSource)30 Connection (java.sql.Connection)27 NamingException (javax.naming.NamingException)25 IOException (java.io.IOException)24 Statement (java.sql.Statement)23 Session (javax.jcr.Session)23 InitialContext (javax.naming.InitialContext)22 SQLException (java.sql.SQLException)20 SystemException (javax.transaction.SystemException)17 RollbackException (javax.transaction.RollbackException)16 Region (org.apache.geode.cache.Region)13 Lock (javax.jcr.lock.Lock)12