Search in sources :

Example 1 with UserTransaction

use of javax.transaction.UserTransaction in project jetty.project by eclipse.

the class JNDITest method init.

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {
        InitialContext ic = new InitialContext();
        woggle = (Integer) ic.lookup("java:comp/env/woggle");
        envEntryGlobalScopeResult = "EnvEntry defined in context xml lookup result (java:comp/env/woggle): " + (woggle == 4000 ? "<span class=\"pass\">PASS" : "<span class=\"fail\">FAIL(expected 4000, got " + woggle + ")") + "</span>";
        gargle = (Double) ic.lookup("java:comp/env/gargle");
        envEntryWebAppScopeResult = "EnvEntry defined in jetty-env.xml lookup result (java:comp/env/gargle): " + (gargle == 100.0 ? "<span class=\"pass\">PASS" : "<span class=\"fail\">FAIL(expected 100, got " + gargle + ")") + "</span>";
        UserTransaction utx = (UserTransaction) ic.lookup("java:comp/UserTransaction");
        userTransactionResult = "UserTransaction lookup result (java:comp/UserTransaction): " + (utx != null ? "<span class=\"pass\">PASS" : "<span class=\"fail\">FAIL") + "</span>";
        myMailSession = (Session) ic.lookup("java:comp/env/mail/Session");
        mailSessionResult = "Mail Session lookup result (java:comp/env/mail/Session): " + (myMailSession != null ? "<span class=\"pass\">PASS" : "<span class=\"fail\">FAIL") + "</span>";
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) ServletException(javax.servlet.ServletException) InitialContext(javax.naming.InitialContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 2 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 3 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 4 with UserTransaction

use of javax.transaction.UserTransaction in project ignite by apache.

the class AbstractCacheJtaSelfTest method testJta.

/**
     * JUnit.
     *
     * @throws Exception If failed.
     */
public void testJta() throws Exception {
    UserTransaction jtaTx = jotm.getUserTransaction();
    IgniteCache<String, Integer> cache = jcache();
    assert ignite(0).transactions().tx() == null;
    jtaTx.begin();
    try {
        assert ignite(0).transactions().tx() == null;
        assert cache.getAndPut("key", 1) == null;
        Transaction tx = ignite(0).transactions().tx();
        assert tx != null;
        assert tx.state() == ACTIVE;
        Integer one = 1;
        assertEquals(one, cache.get("key"));
        tx = ignite(0).transactions().tx();
        assert tx != null;
        assert tx.state() == ACTIVE;
        jtaTx.commit();
        assert ignite(0).transactions().tx() == null;
    } finally {
        if (jtaTx.getStatus() == Status.STATUS_ACTIVE)
            jtaTx.rollback();
    }
    assertEquals((Integer) 1, cache.get("key"));
}
Also used : UserTransaction(javax.transaction.UserTransaction) UserTransaction(javax.transaction.UserTransaction) Transaction(org.apache.ignite.transactions.Transaction)

Example 5 with UserTransaction

use of javax.transaction.UserTransaction in project geode by apache.

the class DataSourceJTAJUnitTest method testInsertUpdateOnSimpleAndXAdsRollback.

/**
   * The following test scenario is to test rollback. In this test scenario it is tested that if
   * transactions are rolled back then XA datasource transactions should be rolled back andSimple
   * datasource transactions should get committed
   */
@Test
public void testInsertUpdateOnSimpleAndXAdsRollback() throws Exception {
    Region currRegion = null;
    Cache cache;
    DistributedSystem ds = null;
    int tblIDFld;
    String tblNameFld;
    String tblName;
    String tableName = null;
    // boolean to_continue = true;
    final int XA_INSERTS = 3;
    final int SM_INSERTS = 1;
    // call to init method
    try {
        Properties props = new Properties();
        String path = TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml");
        props.setProperty(CACHE_XML_FILE, path);
        ds = connect(props);
        tableName = CacheUtils.init(ds, "JTATest");
        System.out.println("Table name: " + tableName);
        tblName = tableName;
        if (tableName == null || tableName.equals("")) {
            // to_continue = false;
            fail(" table name not created, Aborting test...");
        }
    } catch (Exception e) {
        // to_continue = false;
        fail(" Aborting test at set up...[" + e + "]", e);
    }
    System.out.println("init for testscenario 2 Successful!");
    // test task
    cache = CacheUtils.getCache();
    tblName = tableName;
    currRegion = cache.getRegion("/root");
    tblIDFld = 1;
    tblNameFld = "test2";
    JTAUtils jtaObj = new JTAUtils(cache, currRegion);
    // to delete all rows inserted in creatTable () of CacheUtils class
    // deleteRows method of JTAUtils class is used.
    jtaObj.deleteRows(tblName);
    // initialize cache and get user transaction
    Context ctx = cache.getJNDIContext();
    UserTransaction ta = null;
    Connection xa_conn = null;
    Connection sm_conn = null;
    try {
        ta = (UserTransaction) ctx.lookup("java:/UserTransaction");
    } catch (NamingException e) {
        fail(" fail in user txn lookup ", e);
    }
    try {
        // get the SimpleDataSource before the transaction begins
        DataSource sds = (DataSource) ctx.lookup("java:/SimpleDataSource");
        // Begin the user transaction
        ta.begin();
        // Obtain XAPooledDataSource
        DataSource da = (DataSource) ctx.lookup("java:/XAPooledDataSource");
        // obtain connection from SimpleDataSource and XAPooledDataSource
        xa_conn = da.getConnection();
        sm_conn = sds.getConnection();
        Statement xa_stmt = xa_conn.createStatement();
        Statement sm_stmt = sm_conn.createStatement();
        // perform inserts and updates using both viz. Simple and XA DataSources
        // String sqlSTR = "insert into " + tblName + " values (" + tblIDFld + ","
        // + "'" + tblNameFld + "'" + ")" ;
        String sqlSTR;
        // insert XA_INSERTS rows into timestamped table
        for (int i = 0; i < XA_INSERTS; i++) {
            tblIDFld = tblIDFld + i;
            sqlSTR = "insert into " + tblName + " values (" + tblIDFld + "," + "'" + tblNameFld + "'" + ")";
            xa_stmt.executeUpdate(sqlSTR);
        }
        // insert SM_INSERTS rows into timestamped table
        for (int j = 0; j < SM_INSERTS; j++) {
            tblIDFld = tblIDFld + j + 1;
            sqlSTR = "insert into " + tblName + " values (" + tblIDFld + "," + "'" + tblNameFld + "'" + ")";
            sm_stmt.executeUpdate(sqlSTR);
        }
        // close the Simple and XA statements
        xa_stmt.close();
        sm_stmt.close();
        // close the connections
        xa_conn.close();
        sm_conn.close();
        // rollback the transaction
        ta.rollback();
        System.out.println("Rows are rolled back in the database");
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        fail(" failed ", e);
    } finally {
        if (xa_conn != null) {
            try {
                // close the connections
                xa_conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        int num_rows = jtaObj.getRows(tblName);
        System.out.println("\nNumber of rows in Table under tests are: " + num_rows);
        switch(num_rows) {
            case 0:
                System.out.println("Both Simple and XA DataSource transactions got rolled back!!");
                break;
            case SM_INSERTS:
                System.out.println("Only Simple DataSource transactions got committed!");
                break;
            case XA_INSERTS:
                System.out.println("Only XA DataSource transactions got committed!");
                break;
            default:
                System.out.println("Looks like that things are messed up...look into it");
        }
    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }
    System.out.println("test task for testScenario2 Succeessful");
    // destroying table
    try {
        System.out.println("Destroying table: " + tblName);
        CacheUtils.destroyTable(tblName);
        System.out.println("Closing cache...");
        System.out.println("destroyTable for testscenario 2 Successful!");
    } catch (Exception e) {
        fail(" failed during tear down of this test...", e);
    } finally {
        CacheUtils.closeCache();
        // CacheUtils.ds.disconnect();
        ds.disconnect();
    }
}
Also used : Context(javax.naming.Context) UserTransaction(javax.transaction.UserTransaction) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) DistributedSystem(org.apache.geode.distributed.DistributedSystem) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) DataSource(javax.sql.DataSource) Region(org.apache.geode.cache.Region) NamingException(javax.naming.NamingException) Cache(org.apache.geode.cache.Cache) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Aggregations

UserTransaction (javax.transaction.UserTransaction)642 EntityManager (javax.persistence.EntityManager)244 Test (org.testng.annotations.Test)187 Test (org.junit.Test)157 JPATest (org.jpwh.env.JPATest)138 InitialContext (javax.naming.InitialContext)62 BigDecimal (java.math.BigDecimal)53 HashMap (java.util.HashMap)52 IOException (java.io.IOException)50 Context (javax.naming.Context)49 List (java.util.List)47 FacesContext (javax.faces.context.FacesContext)43 NamingException (javax.naming.NamingException)43 NodeRef (org.alfresco.service.cmr.repository.NodeRef)43 Node (javax.jcr.Node)42 KieSession (org.kie.api.runtime.KieSession)42 Query (javax.persistence.Query)38 QueryingTest (org.jpwh.test.querying.QueryingTest)36 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)35 Item (org.jpwh.model.querying.Item)35