Java Code Examples for javax.sql.XAConnection#getXAResource()

The following examples show how to use javax.sql.XAConnection#getXAResource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SuspendableXAConnection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private synchronized void switchToXid(Xid xid) throws XAException {
    if (xid == null) {
        throw new XAException();
    }

    try {
        if (!xid.equals(this.currentXid)) {
            XAConnection toSwitchTo = findConnectionForXid(this.underlyingConnection, xid);
            this.currentXAConnection = toSwitchTo;
            this.currentXid = xid;
            this.currentXAResource = toSwitchTo.getXAResource();
        }
    } catch (SQLException sqlEx) {
        throw new XAException();
    }
}
 
Example 2
Source File: SuspendableXAConnection.java    From r-course with MIT License 6 votes vote down vote up
private synchronized void switchToXid(Xid xid) throws XAException {
    if (xid == null) {
        throw new XAException();
    }

    try {
        if (!xid.equals(this.currentXid)) {
            XAConnection toSwitchTo = findConnectionForXid(this.underlyingConnection, xid);
            this.currentXAConnection = toSwitchTo;
            this.currentXid = xid;
            this.currentXAResource = toSwitchTo.getXAResource();
        }
    } catch (SQLException sqlEx) {
        throw new XAException();
    }
}
 
Example 3
Source File: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * DERBY-4232: Test that an XA transaction can be suspended and resumed
 * when a timeout is in effect.
 */
public void testTransactionTimeoutAndSuspendResume() throws Exception {
    XADataSource xads = J2EEDataSource.getXADataSource();
    XAConnection xac = xads.getXAConnection();
    XAResource xar = xac.getXAResource();
    Xid xid = XATestUtil.getXid(1, 2, 3);

    // Start work in a new transaction with a timeout
    xar.setTransactionTimeout(500);
    xar.start(xid, XAResource.TMNOFLAGS);

    // Suspend the transaction
    xar.end(xid, XAResource.TMSUSPEND);

    // Resume the transaction (used to fail with a XAER_PROTO on the
    // network client)
    xar.start(xid, XAResource.TMRESUME);

    // End the transaction and free up the resources
    xar.end(xid, XAResource.TMSUCCESS);
    xar.rollback(xid);
    xac.close();
}
 
Example 4
Source File: TestFBXADataSource.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Tests if setting autoCommit(true) when autoCommit is false throws an exception when participating in a distributed transaction (JDBC 4.0 section 12.4).
 */
@Test
public void testInDistributed_setAutoCommit_true_notInAutoCommit() throws Exception {
    XAConnection pc = getXAConnection();
    XAResource xa = pc.getXAResource();
    Xid xid = new XidImpl();
    try (Connection con = pc.getConnection()) {
        con.setAutoCommit(false);
        xa.start(xid, XAResource.TMNOFLAGS);

        expectedException.expect(SQLException.class);
        expectedException.expect(sqlStateEquals(SQLStateConstants.SQL_STATE_INVALID_TX_STATE));

        con.setAutoCommit(true);
    } finally {
        xa.end(xid, XAResource.TMSUCCESS);
        xa.rollback(xid);
    }
}
 
Example 5
Source File: TestFBXADataSource.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test if calling rollback for savepoint throws an exception when participating in a distributed transaction (JDBC 4.0 section 12.4).
 */
@Test
public void testInDistributed_rollback_savepoint() throws Exception {
    XAConnection pc = getXAConnection();
    XAResource xa = pc.getXAResource();
    try (Connection con = pc.getConnection()) {
        assumeTrue("Test requires SAVEPOINT support", supportInfoFor(con).supportsSavepoint());
        Xid xid = new XidImpl();
        try {
            con.setAutoCommit(false);
            Savepoint savepoint = con.setSavepoint(); // Just to create one
            con.rollback(); // Required to make sure start() works.
            xa.start(xid, XAResource.TMNOFLAGS);

            expectedException.expect(SQLException.class);
            expectedException.expect(sqlStateEquals(SQLStateConstants.SQL_STATE_INVALID_TX_STATE));

            con.rollback(savepoint);
        } finally {
            xa.end(xid, XAResource.TMSUCCESS);
            xa.rollback(xid);
        }
    }
}
 
Example 6
Source File: TestFBXADataSource.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test if calling commit throws an exception when participating in a distributed transaction (JDBC 4.0 section 12.4).
 */
@Test
public void testInDistributed_commit() throws Exception {
    XAConnection pc = getXAConnection();
    XAResource xa = pc.getXAResource();
    Xid xid = new XidImpl();
    try (Connection con = pc.getConnection()) {
        con.setAutoCommit(false);
        xa.start(xid, XAResource.TMNOFLAGS);

        expectedException.expect(SQLException.class);
        expectedException.expect(sqlStateEquals(SQLStateConstants.SQL_STATE_INVALID_TX_STATE));

        con.commit();
    } finally {
        xa.end(xid, XAResource.TMSUCCESS);
        xa.rollback(xid);
    }
}
 
Example 7
Source File: RMXAConnectionResource.java    From FHIR with Apache License 2.0 6 votes vote down vote up
/**
 * This method will walk the list of proxied XAConnections and obtain an XAResource for each one.
 */
private void buildProxiedXAResources() throws SQLException {
    log.entering(this.getClass().getName(), "buildProxiedXAResources");
    try {
        List<XAResource> resources = new ArrayList<>();
        if (getProxiedXAConnections() != null) {
            for (XAConnection connection : getProxiedXAConnections()) {
                XAResource resource = connection.getXAResource();
                resources.add(resource);
            }
        }
        setProxiedXAResources(resources);
    } finally {
        log.exiting(this.getClass().getName(), "buildProxiedXAResources");
    }
}
 
Example 8
Source File: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * DERBY-4232: Test that two branches can be joined after the timeout has
 * been set.
 */
public void testTransactionTimeoutAndJoin() throws Exception {
    XADataSource xads = J2EEDataSource.getXADataSource();
    XAConnection xac1 = xads.getXAConnection();
    XAResource xar1 = xac1.getXAResource();
    Xid xid1 = XATestUtil.getXid(4, 5, 6);

    // Start/end work in a new transaction
    xar1.setTransactionTimeout(500);
    xar1.start(xid1, XAResource.TMNOFLAGS);
    xar1.end(xid1, XAResource.TMSUCCESS);

    // Create a new branch that can be joined with the existing one
    XAConnection xac2 = xads.getXAConnection();
    XAResource xar2 = xac2.getXAResource();
    xar2.setTransactionTimeout(500);

    // Do some work on the new branch before joining (the bug won't be
    // reproduced if we join with a fresh branch)
    Xid xid2 = XATestUtil.getXid(4, 5, 7);
    xar2.start(xid2, XAResource.TMNOFLAGS);
    xar2.end(xid2, XAResource.TMSUCCESS);
    xar2.rollback(xid2);

    assertTrue(
            "Branches can only be joined if RM is same",
            xar1.isSameRM(xar2));

    // Join the branches. This used to fail with XAER_PROTO on the
    // network client.
    xar2.start(xid1, XAResource.TMJOIN);

    // End the transaction and free up the resources
    xar2.end(xid1, XAResource.TMSUCCESS);
    xar2.rollback(xid1);
    xac1.close();
    xac2.close();
}
 
Example 9
Source File: XATransactionTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testSimpleXATransaction() throws Exception {
  Statement stm = getConnection().createStatement();
  stm.execute("create table XATT2 (i int, text char(10))");

  XADataSource xaDataSource = (XADataSource)TestUtil.getXADataSource(TestUtil.EmbeddedeXADsClassName);
  // create large enough xid
  byte[] gid = new byte[64];
  byte[] bid = new byte[64];
  for (int i = 0; i < 64; i++) {
    gid[i] = (byte)i;
    bid[i] = (byte)(64 - i);
  }
  Xid xid = new ClientXid(0x1234, gid, bid);

  // get the stuff required to execute the global transaction
  XAConnection xaConn = xaDataSource.getXAConnection();
  XAResource xaRes = xaConn.getXAResource();
  Connection conn = xaConn.getConnection();
  conn.setTransactionIsolation(getIsolationLevel());
  // start the transaction with that xid
  xaRes.start(xid, XAResource.TMNOFLAGS);

  // do some work
  stm = conn.createStatement();
  stm.execute("insert into XATT2 values (1234, 'Test_Entry')");
  stm.close();

  stm = getConnection().createStatement();
  stm.execute("select * from XATT2");
  ResultSet rs = stm.getResultSet();
  assertFalse(rs.next());
  // end the work on the transaction branch
  xaRes.end(xid, XAResource.TMSUCCESS);
  xaRes.prepare(xid);
  xaRes.commit(xid, false);
  stm.execute("select * from XATT2");
  rs = stm.getResultSet();
  assertTrue(rs.next());
}
 
Example 10
Source File: XATransactionTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testFromNetClient() throws Exception {    
  setupConnection();
  int netport = startNetserverAndReturnPort("create table XATT2 "
      + "(i int, text char(10))");
  ClientXADataSource xaDataSource = (ClientXADataSource)TestUtil
      .getXADataSource(TestUtil.NetClientXADsClassName);
  byte[] gid = new byte[64];
  byte[] bid = new byte[64];
  for (int i = 0; i < 64; i++) {
    gid[i] = (byte)i;
    bid[i] = (byte)(64 - i);
  }
  Xid xid = new ClientXid(0x1234, gid, bid);

  String localhost = SocketCreator.getLocalHost().getHostName(); 
  xaDataSource.setServerName(localhost);
  xaDataSource.setPortNumber(netport);

  xaDataSource.setDatabaseName("gemfirexd");
  // get the stuff required to execute the global transaction
  XAConnection xaConn = xaDataSource.getXAConnection();
  XAResource xaRes = xaConn.getXAResource();
  Connection conn = xaConn.getConnection();

  // start the transaction with that xid
  xaRes.start(xid, XAResource.TMNOFLAGS);

  conn.setTransactionIsolation(getIsolationLevel());
  // do some work
  Statement stm = conn.createStatement();
  stm.execute("insert into XATT2 values (1234, 'Test_Entry')");
  stm.close();

  stm = getConnection().createStatement();
  stm.execute("select * from XATT2");
  ResultSet rs = stm.getResultSet();
  assertFalse(rs.next());
  // end the work on the transaction branch
  xaRes.end(xid, XAResource.TMSUCCESS);
  xaRes.prepare(xid);
  xaRes.commit(xid, false);
  stm.execute("select * from XATT2");
  rs = stm.getResultSet();
  assertTrue(rs.next());
}
 
Example 11
Source File: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <p>
 * Regression test case for DERBY-5562.
 * </p>
 *
 * <p>
 * The timer that aborts long-running transactions if a transaction timeout
 * has been specified, was not cancelled when preparing a read-only
 * transaction. Since read-only transactions are implicitly committed when
 * they are prepared, this meant that the timer would try to abort an
 * already completed transaction. In addition to printing a confusing
 * message in db.log about the transaction being rolled back, when it
 * actually had been committed, this could also make the timer roll back
 * the wrong transaction, if a new transaction with the same Xid was
 * started later.
 * </p>
 *
 * <p>
 * This test case exposes the bug by running a read-only transaction with
 * a timeout and preparing it, and then starting a new transaction with the
 * same Xid and no timeout. The bug would cause the second transaction to
 * time out.
 * </p>
 */
public void testDerby5562ReadOnlyTimeout()
        throws InterruptedException, SQLException, XAException {
    XADataSource xads = J2EEDataSource.getXADataSource();
    XAConnection xac = xads.getXAConnection();
    XAResource xar = xac.getXAResource();

    Xid xid = createXid(55, 62);

    // Set a transaction timeout. This should be relatively short so that
    // the test case doesn't need to wait very long to trigger the timeout.
    // However, it needs to be long enough to let the first transaction go
    // through without hitting the timeout. Hopefully, four seconds is
    // enough. If the test case starts failing intermittently during the
    // first transaction, we might have to raise the timeout (and raise the
    // sleep time in the second transaction correspondingly).
    assertTrue(xar.setTransactionTimeout(4));

    // Start first transaction.
    xar.start(xid, XAResource.TMNOFLAGS);
    Connection c = xac.getConnection();
    Statement s = c.createStatement();
    JDBC.assertSingleValueResultSet(
            s.executeQuery("select * from sysibm.sysdummy1"),
            "Y");
    s.close();
    c.close();
    xar.end(xid, XAResource.TMSUCCESS);

    // Prepare the first transaction. Since it's a read-only transaction,
    // it'll be automatically committed, so there's no need to call commit.
    assertEquals("XA_RDONLY", XAResource.XA_RDONLY, xar.prepare(xid));

    // Reset the timeout for the second transaction.
    assertTrue(xar.setTransactionTimeout(0));

    // Start second transaction.
    xar.start(xid, XAResource.TMNOFLAGS);
    c = xac.getConnection();
    s = c.createStatement();
    JDBC.assertSingleValueResultSet(
            s.executeQuery("select * from sysibm.sysdummy1"),
            "Y");
    s.close();
    c.close();

    // Keep the transaction running so long that it must have exceeded the
    // timeout for the previous transaction.
    Thread.sleep(5000);

    // End the transaction. Since there's no timeout on this transaction,
    // it should work. Before DERBY-5562 was fixed, it would fail because
    // it had been rolled back by the timer from the previous transaction.
    xar.end(xid, XAResource.TMSUCCESS);
    assertEquals("XA_RDONLY", XAResource.XA_RDONLY, xar.prepare(xid));

    xac.close();
}
 
Example 12
Source File: XATransactionTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testGlobalXIDinTransactionTable() throws Exception {
    Statement stm = getConnection().createStatement();
    stm.execute("create table XATT2 (i int, text char(10))");

    XADataSource xaDataSource = J2EEDataSource.getXADataSource();
    XAConnection xaConn = xaDataSource.getXAConnection();
    XAResource xaRes = xaConn.getXAResource();
    Connection conn = xaConn.getConnection();

    // create large enough xid
    byte[] gid = new byte[64];
    byte[] bid = new byte[64];
    for (int i=0; i < 64; i++) {
        gid[i] = (byte) i;
        bid[i] = (byte) (64 - i);
    }
    Xid xid = new ClientXid(0x1234, gid, bid);

    // get the stuff required to execute the global transaction
    xaConn = xaDataSource.getXAConnection();
    xaRes = xaConn.getXAResource();
    conn = xaConn.getConnection();

    // start the transaction with that xid
    xaRes.start(xid, XAResource.TMNOFLAGS);

    // do some work
    stm = conn.createStatement();
    stm.execute("insert into XATT2 values (1234, 'Test_Entry')");
    stm.close();

    // end the wotk on the transaction branch
    xaRes.end(xid, XAResource.TMSUCCESS);

    ResultSet rs = null;
    stm = null;

    try {

        // check the output of the global xid in syscs_diag.transaction_table
        stm = getConnection().createStatement();

        String query = "select global_xid from syscs_diag.transaction_table"
                     + " where global_xid is not null";

        // execute the query to obtain the xid of the global transaction
        rs = stm.executeQuery(query);

        // there should be at least one globaltransaction in progress
        Assert.assertTrue(rs.next());

        // check whether the xid obtained matches the original xid
        Xid rXid = parseXid(rs.getString(1));
        Assert.assertEquals(xid, rXid);

        // there should be at most one global transaction in progress
        Assert.assertFalse(rs.next());

    } catch (Exception ex) {
        try {
            // close all the stuff
            if (rs != null)
                rs.close();
            if (stm != null)
                stm.close();

            // rollback the global transaction
            xaRes.rollback(xid);
            // close the connection
            xaConn.close();
        } catch (Exception e) {
            // ignore the exception because it
            // would hide the original exception
        }
        // throw the stuff further
        throw ex;
    }

    // close all the stuff
    rs.close();
    stm.close();

    // rollback the global transaction
    xaRes.rollback(xid);

    // close the connection
    xaConn.close();
}
 
Example 13
Source File: DataSourceRegressionTest.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Tests fix for BUG#72890 - Java jdbc driver returns incorrect return code when it's part of XA transaction
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug72890() throws Exception {
    MysqlXADataSource myDs = new MysqlXADataSource();
    myDs.setUrl(BaseTestCase.dbUrl);

    try {
        final Xid xid = new MysqlXid("72890".getBytes(), "72890".getBytes(), 1);

        final XAConnection xaConn = myDs.getXAConnection();
        final XAResource xaRes = xaConn.getXAResource();
        final Connection dbConn = xaConn.getConnection();
        final long connId = ((MysqlConnection) ((MysqlConnection) dbConn).getConnectionMutex()).getSession().getThreadId();

        xaRes.start(xid, XAResource.TMNOFLAGS);
        xaRes.end(xid, XAResource.TMSUCCESS);
        assertEquals(XAResource.XA_OK, xaRes.prepare(xid));

        // Simulate a connection hang and make sure the connection really dies.
        this.stmt.execute("KILL CONNECTION " + connId);
        int connAliveChecks = 4;
        while (connAliveChecks > 0) {
            this.rs = this.stmt.executeQuery("SHOW PROCESSLIST");
            boolean connIsAlive = false;
            while (!connIsAlive && this.rs.next()) {
                connIsAlive = this.rs.getInt(1) == connId;
            }
            this.rs.close();
            if (connIsAlive) {
                connAliveChecks--;
                System.out.println("Connection id " + connId + " is still alive. Checking " + connAliveChecks + " more times.");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            } else {
                connAliveChecks = -1;
            }
        }
        if (connAliveChecks == 0) {
            fail("Failed to kill the Connection id " + connId + " in a timely manner.");
        }

        XAException xaEx = assertThrows(XAException.class, "Undetermined error occurred in the underlying Connection - check your data for consistency",
                new Callable<Void>() {
                    public Void call() throws Exception {
                        xaRes.commit(xid, false);
                        return null;
                    }
                });
        assertEquals("XAException error code", XAException.XAER_RMFAIL, xaEx.errorCode);

        dbConn.close();
        xaConn.close();

    } finally {
        /*
         * After MySQL 5.7.7 a prepared XA transaction is no longer rolled back at disconnect. It needs to be rolled back manually to prevent test failures
         * in subsequent runs.
         * Other MySQL versions won't have any transactions to recover.
         */
        final XAConnection xaConnRecovery = myDs.getXAConnection();
        final XAResource xaResRecovery = xaConnRecovery.getXAResource();

        final Xid[] xidsToRecover = xaResRecovery.recover(XAResource.TMSTARTRSCAN);
        for (Xid xidToRecover : xidsToRecover) {
            xaResRecovery.rollback(xidToRecover);
        }

        xaConnRecovery.close();
    }
}
 
Example 14
Source File: XATest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This test checks the fix on DERBY-4310, for not repreparing PreparedStatements
 * upon calling close() on them.
 */
public void testDerby4310PreparedStatement() throws SQLException, XAException {
    XADataSource xads = J2EEDataSource.getXADataSource();
    J2EEDataSource.setBeanProperty(xads, "databaseName", "wombat");

    XAConnection xaconn = xads.getXAConnection();
   
    XAResource xar = xaconn.getXAResource();
    Xid xid = XATestUtil.getXid(1,93,18);
    
    /* Create the table and insert some records into it. */
    Connection conn = xaconn.getConnection();
    Statement s = conn.createStatement();
    s.executeUpdate("CREATE TABLE foo4310_PS (I INT)");

    conn.createStatement().executeUpdate("insert into SPLICE.foo4310_PS values (0)");
    conn.createStatement().executeUpdate("insert into SPLICE.foo4310_PS values (1)");
    conn.createStatement().executeUpdate("insert into SPLICE.foo4310_PS values (2)");
    conn.commit();
    
    /* Prepare and execute the statement to be tested */
    PreparedStatement ps = conn.prepareStatement("SELECT * FROM SPLICE.foo4310_PS");
    ps.executeQuery().close();

    /* Start and end a transaction on the XAResource object */
    xar.start(xid, XAResource.TMNOFLAGS);
    xar.end(xid, XAResource.TMSUCCESS);
    
    /* Drop the table on a parallel, regular connection */
    Connection conn2 = getConnection();
    Statement s2 = conn2.createStatement();
    s2.execute("DROP TABLE foo4310_PS");
    conn2.commit();
    conn2.close();
    
    try {
        /* Try to close the prepared statement. This would throw an exception
         * before the fix, claiming that the table was not found. */
        ps.close();
    } finally {
        /* Rollback the transaction and close the connections */
        xar.rollback(xid);
        conn.close();
        xaconn.close();
    }
    
}
 
Example 15
Source File: XaTest.java    From jTDS with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Test to demonstrate the use of the XA_JOIN command.
 *
 * @throws Exception if an error condition occurs
 */
public void testXAJoinTran() throws Exception {
    if ("true".equalsIgnoreCase(props.getProperty(Messages.get(Driver.XAEMULATION)))) {
        // Emulation mode does not joining transactions.
        return;
    }
    Connection con2 = null;
    Connection con3 = null;
    XAConnection xaCon = null;
    XAConnection xaCon2 = null;

    try {
        dropTable("jTDS_XATEST");
        dropTable("jTDS_XATEST2");

        Statement stmt = con.createStatement();
        stmt.execute("CREATE TABLE jTDS_XATEST (id int primary key, data varchar(255))");
        stmt.execute("CREATE TABLE jTDS_XATEST2 (id int primary key, data varchar(255))");
        assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST"));
        assertNotNull(stmt.executeQuery("SELECT * FROM jTDS_XATEST2"));
        stmt.close();

        XADataSource xaDS = getDataSource();
        XAResource xaRes;
        XAResource xaRes2;
        Xid  xid;
        xaCon = xaDS.getXAConnection();
        xaRes = xaCon.getXAResource();
        xaCon2 = xaDS.getXAConnection();
        xaRes2 = xaCon2.getXAResource();
        con2 = xaCon.getConnection();
        con3 = xaCon2.getConnection();
        stmt = con2.createStatement();
        Statement stmt2 = con3.createStatement();
        xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});

        xaRes.start(xid, XAResource.TMNOFLAGS);
        stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
        assertTrue(xaRes.isSameRM(xaRes2));
        xaRes2.start(xid, XAResource.TMJOIN);
        stmt2.executeUpdate("INSERT INTO jTDS_XATEST2 VALUES (1, 'TEST LINE 2')");
        xaRes.end(xid, XAResource.TMSUCCESS);
        xaRes2.end(xid, XAResource.TMSUCCESS);

        int ret = xaRes.prepare(xid);
        if (ret == XAResource.XA_OK) {
            xaRes.commit(xid, false);
        }
        stmt.close();
        stmt2.close();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
        assertNotNull(rs);
        assertTrue(rs.next());
        rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST2");
        assertNotNull(rs);
        assertTrue(rs.next());
        stmt.close();
    } finally {
        if (con2 != null) {
            con2.close();
        }
        if (con3 != null) {
            con3.close();
        }
        if (xaCon != null) {
            xaCon.close();
        }
        if (xaCon2 != null) {
            xaCon2.close();
        }

        dropTable("jTDS_XATEST");
        dropTable("jTDS_XATEST2");
    }
}
 
Example 16
Source File: TransactionDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testXATransactionFromPeerClient_commit() throws Exception {
  startServerVMs(2, 0, null);
  startClientVMs(1, 0, null);

  serverSQLExecute(1, "create schema test");
  serverSQLExecute(1, "create table test.XATT2 (intcol int not null, text varchar(100) not null)"+ getSuffix());
  serverSQLExecute(1, "insert into test.XATT2 values (1, 'ONE')");
  
  EmbeddedXADataSource xaDataSource = (EmbeddedXADataSource)TestUtil
      .getXADataSource(TestUtil.EmbeddedeXADsClassName);
  byte[] gid = new byte[64];
  byte[] bid = new byte[64];
  for (int i = 0; i < 64; i++) {
    gid[i] = (byte)i;
    bid[i] = (byte)(64 - i);
  }
  Xid xid = new ClientXid(0x1234, gid, bid);

  // get the stuff required to execute the global transaction
  XAConnection xaConn = xaDataSource.getXAConnection();
  XAResource xaRes = xaConn.getXAResource();
  Connection conn = xaConn.getConnection();

  // start the transaction with that xid
  xaRes.start(xid, XAResource.TMNOFLAGS);

  conn.setTransactionIsolation(getIsolationLevel());
  // do some work
  Statement stm = conn.createStatement();
  stm.execute("insert into test.XATT2 values (2, 'TWO')");
  
  String jdbcSQL = "select * from test.XATT2";
  String xmlFile = TestUtil.getResourcesDir() + "/lib/checkQuery.xml";
  
  sqlExecuteVerify(null, new int[] {1}, jdbcSQL, xmlFile, "before_xa_commit");
  stm.execute("select * from test.XATT2");
  ResultSet r = stm.getResultSet();
  int cnt = 0;
  while(r.next()) {
    cnt++;
  }
  assertEquals(2, cnt);
  xaRes.end(xid, XAResource.TMSUCCESS);
  xaRes.prepare(xid);
  xaRes.commit(xid, false);
  VM servervm = getServerVM(1);
  servervm.invoke(TransactionDUnit.class, "waitForPendingCommit");
  TXManagerImpl.waitForPendingCommitForTest();

  sqlExecuteVerify(null, new int[] { 1 }, jdbcSQL, xmlFile, "after_xa_commit");
}
 
Example 17
Source File: XATest.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public void testSuspendableTx() throws Exception {
    Connection conn1 = null;

    MysqlXADataSource suspXaDs = new MysqlXADataSource();
    suspXaDs.setUrl(BaseTestCase.dbUrl);
    suspXaDs.<Boolean> getProperty(PropertyKey.pinGlobalTxToPhysicalConnection).setValue(true);
    suspXaDs.<Boolean> getProperty(PropertyKey.rollbackOnPooledClose).setValue(true);

    XAConnection xaConn1 = null;

    Xid xid = createXid();

    try {
        /*
         * -- works using RESUME
         * xa start 0x123,0x456;
         * select * from foo;
         * xa end 0x123,0x456;
         * xa start 0x123,0x456 resume;
         * select * from foo;
         * xa end 0x123,0x456;
         * xa commit 0x123,0x456 one phase;
         */

        xaConn1 = suspXaDs.getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaRes1.start(xid, XAResource.TMNOFLAGS);
        conn1.createStatement().execute("SELECT 1");
        xaRes1.end(xid, XAResource.TMSUCCESS);
        xaRes1.start(xid, XAResource.TMRESUME);
        conn1.createStatement().execute("SELECT 1");
        xaRes1.end(xid, XAResource.TMSUCCESS);
        xaRes1.commit(xid, true);

        xaConn1.close();

        /*
         * 
         * -- fails using JOIN
         * xa start 0x123,0x456;
         * select * from foo;
         * xa end 0x123,0x456;
         * xa start 0x123,0x456 join;
         * select * from foo;
         * xa end 0x123,0x456;
         * xa commit 0x123,0x456 one phase;
         */

        xaConn1 = suspXaDs.getXAConnection();
        xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();
        xaRes1.start(xid, XAResource.TMNOFLAGS);
        conn1.createStatement().execute("SELECT 1");
        xaRes1.end(xid, XAResource.TMSUCCESS);
        xaRes1.start(xid, XAResource.TMJOIN);
        conn1.createStatement().execute("SELECT 1");
        xaRes1.end(xid, XAResource.TMSUCCESS);
        xaRes1.commit(xid, true);
    } finally {
        if (xaConn1 != null) {
            xaConn1.close();
        }
    }
}
 
Example 18
Source File: TransactionDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testXATransactionFromClient_rollback() throws Exception {
  startServerVMs(2, 0, null);
  startClientVMs(1, 0, null);
  final int netport = startNetworkServer(1, null, null);
  serverSQLExecute(1, "create schema test");
  serverSQLExecute(1, "create table test.XATT2 (intcol int not null, text varchar(100) not null)"+ getSuffix());
  serverSQLExecute(1, "insert into test.XATT2 values (1, 'ONE')");
  
  ClientXADataSource xaDataSource = (ClientXADataSource)TestUtil
      .getXADataSource(TestUtil.NetClientXADsClassName);
  byte[] gid = new byte[64];
  byte[] bid = new byte[64];
  for (int i = 0; i < 64; i++) {
    gid[i] = (byte)i;
    bid[i] = (byte)(64 - i);
  }
  Xid xid = new ClientXid(0x1234, gid, bid);

  String localhost = SocketCreator.getLocalHost().getHostName();
  xaDataSource.setServerName(localhost);
  xaDataSource.setPortNumber(netport);

  xaDataSource.setDatabaseName("gemfirexd");
  // get the stuff required to execute the global transaction
  XAConnection xaConn = xaDataSource.getXAConnection();
  XAResource xaRes = xaConn.getXAResource();
  Connection conn = xaConn.getConnection();

  // start the transaction with that xid
  xaRes.start(xid, XAResource.TMNOFLAGS);

  conn.setTransactionIsolation(getIsolationLevel());
  // do some work
  Statement stm = conn.createStatement();
  stm.execute("insert into test.XATT2 values (2, 'TWO')");
  
  String jdbcSQL = "select * from test.XATT2";
  String xmlFile = TestUtil.getResourcesDir() + "/lib/checkQuery.xml";
  
  sqlExecuteVerify(null, new int[] {1}, jdbcSQL, xmlFile, "before_xa_commit");
  
  stm.execute("select * from test.XATT2");
  ResultSet r = stm.getResultSet();
  int cnt = 0;
  while(r.next()) {
    cnt++;
  }
  assertEquals(2, cnt);
  xaRes.end(xid, XAResource.TMSUCCESS);
  xaRes.prepare(xid);
  xaRes.rollback(xid);
  
  VM servervm = getServerVM(1);
  servervm.invoke(TransactionDUnit.class, "waitForPendingCommit");
  sqlExecuteVerify(null, new int[] {1}, jdbcSQL, xmlFile, "before_xa_commit");
}
 
Example 19
Source File: JdbcXaTest.java    From hazelcast-jet-contrib with Apache License 2.0 4 votes vote down vote up
/** */
public static void main(String[] args) throws Exception {
    // replace this line with a factory for your database, for example:
    //    PGXADataSource factory = new PGXADataSource();
    XADataSource factory = getXADataSource();

    if (factory == null) {
        throw new IllegalArgumentException("Provide XADataSource for your broker in the getXADataSource() method");
    }

    // create an xa-connection, connection and XA transaction
    XAConnection xaConn = factory.getXAConnection();
    Connection conn = xaConn.getConnection();
    XAResource xaRes = xaConn.getXAResource();
    Xid xid = new MyXid(1);

    // create a table "foo"
    Statement stmt = conn.createStatement();
    stmt.execute("create table foo(a numeric)");

    // start the transaction and insert one record
    xaRes.start(xid, XAResource.TMNOFLAGS);
    stmt.execute("insert into foo values (1)");
    xaRes.end(xid, XAResource.TMSUCCESS);
    xaRes.prepare(xid);

    // Now disconnect. Some brokers roll back the transaction, but this is not
    // compatible with Jet's fault tolerance.
    xaConn.close();

    // connect again
    xaConn = factory.getXAConnection();
    conn = xaConn.getConnection();
    xaRes = xaConn.getXAResource();

    // commit the prepared transaction
    xaRes.commit(xid, false);

    // check that record is inserted
    stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select a from foo");
    if (!rs.next() || rs.getInt(1) != 1) {
        System.err.println("Failure: record missing or has wrong value");
    } else {
        System.out.println("Success!");
    }
}
 
Example 20
Source File: XATest.java    From gemfirexd-oss with Apache License 2.0 2 votes vote down vote up
/**
 * A single connection and 1 phase commit.
 * 
 * 
 * Original "SQL" from xaSimplePositive.sql <code>
 xa_connect ;
 xa_start xa_noflags 0;
 xa_getconnection;
 drop table foo;
 create table foo (a int);
 insert into foo values (0);
 select * from foo;
 run resource '/org/apache/derbyTesting/functionTests/tests/store/global_xactTable.view';
 select * from global_xactTable where gxid is not null order by gxid;
 xa_end xa_success 0;
 xa_commit xa_1phase 0;
 
 xa_datasource 'wombat' shutdown;
 </code>
 * 
 * @throws SQLException
 * @throws XAException
 * @throws XAException
 */
public void testSingleConnectionOnePhaseCommit() throws SQLException,
        XAException {

    XADataSource xads = J2EEDataSource.getXADataSource();
    J2EEDataSource.setBeanProperty(xads, "databaseName", "gemfirexd");

    XAConnection xac = xads.getXAConnection();

    XAResource xar = xac.getXAResource();

    Xid xid = XATestUtil.getXid(0, 32, 46);

    xar.start(xid, XAResource.TMNOFLAGS);

    Connection conn = xac.getConnection();
    assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());

    Statement s = conn.createStatement();
    assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, s
            .getResultSetHoldability());

    s.execute("create table foo (a int)");
    s.executeUpdate("insert into foo values (0)");

    ResultSet rs = s.executeQuery("select * from foo");
    JDBC.assertDrainResults(rs, 1);

    String[][] expectedRows = { { "(0", "ACTIVE", "false", "APP",
            "UserTransaction" } };

    ///XATestUtil.checkXATransactionView(conn, expectedRows); //Ticket 44422

    s.close();
    xar.end(xid, XAResource.TMSUCCESS);

    // 1 phase commit
    xar.commit(xid, true);

    conn.close();
    xac.close();

}