Java Code Examples for javax.transaction.xa.XAResource#rollback()

The following examples show how to use javax.transaction.xa.XAResource#rollback() . 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: TestFBXAResource.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Tests whether a connection obtained from a managed connection during a distributed transaction can be closed.
 * <p>
 * See <a href="http://tracker.firebirdsql.org/browse/JDBC-362">JDBC-362</a>.
 * </p>
 */
@Test
public void testCloseConnectionDuringXA() throws Throwable {
    FBManagedConnectionFactory mcf = initMcf();
    FBManagedConnection mc = mcf.createManagedConnection();
    try {
        XAResource xa = mc.getXAResource();
        Connection con = mc.getConnection();
        Xid xid = new XidImpl();
        xa.start(xid, XAResource.TMNOFLAGS);

        try {
            con.close();

            xa.end(xid, XAResource.TMSUCCESS);
            xa.commit(xid, true);
        } catch (Throwable t) {
            xa.end(xid, XAResource.TMSUCCESS);
            xa.rollback(xid);
            throw t;
        }
    } finally {
        mc.destroy();
    }
}
 
Example 2
Source File: TestFBXADataSource.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test if calling setSavePoint (no param) throws an exception when participating in a distributed transaction (JDBC 4.0 section 12.4).
 */
@Test
public void testInDistributed_setSavepoint() 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.setSavepoint();
    } finally {
        xa.end(xid, XAResource.TMSUCCESS);
        xa.rollback(xid);
    }
}
 
Example 3
Source File: TopicDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublisherWithRollback() throws Exception {

    String subscriptionId = "sub-testPublisherWithRollback";
    String topicName = "testPublisherWithRollback";
    String testMessage = "testPublisherWithRollback-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory().withTopic(topicName).build();
    Topic topic = (Topic) initialContext.lookup(topicName);

    // Setup XA producer.
    XATopicConnectionFactory xaTopicConnectionFactory =
            (XATopicConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);
    XATopicConnection xaTopicConnection = xaTopicConnectionFactory.createXATopicConnection();
    XATopicSession xaTopicSession = xaTopicConnection.createXATopicSession();
    XAResource xaResource = xaTopicSession.getXAResource();
    MessageProducer producer = xaTopicSession.createProducer(topic);

    // Setup non-transactional consumer.
    TopicSession topicSession = xaTopicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
    xaTopicConnection.start();

    // Send message withing a XA transaction.
    XidImpl xid = new XidImpl(0, "branchId".getBytes(), "globalId".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(xaTopicSession.createTextMessage(testMessage));
    xaResource.end(xid, XAResource.TMSUCCESS);

    int response = xaResource.prepare(xid);
    Assert.assertEquals(response, XAResource.XA_OK, "Prepare stage failed.");

    xaResource.rollback(xid);

    durableSubscriber.close();
    xaTopicSession.close();
    xaTopicConnection.close();
    QueueMetadata queueMetadata = restApiClient.getQueueMetadata("carbon:" + subscriptionId);
    Assert.assertEquals((int) queueMetadata.getSize(), 0, "Queue is not empty");
}
 
Example 4
Source File: RMXAConnectionResource.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Override
public void rollback(Xid xid) throws XAException {
    log.entering(this.getClass().getName(), "rollback");
    // log.fine(FHIRUtilities.getCurrentStacktrace());
    try {
        // Retrieve the XAResource(s) associated with this Xid.
        List<XAResource> resources = getXAResourcesForXid(xid);
        if (resources == null) {
            throw new XAException("rollback: Unknown Xid");
        }

        String xidString = displayXid(xid);
        log.info("Initiating recovery 'rollback' processing for Xid:\n" + xidString);
        
        // Make sure our artificial failures are not triggered during recovery processing :)
        setBypassFailures(Boolean.TRUE);

        // Drive the method calls to each of the XAResource instances.
        for (XAResource resource : resources) {
            resource.rollback(xid);
        }
        
        log.info("Finished recovery 'rollback' processing for Xid:\n" + xidString);
    } finally {
        setBypassFailures(Boolean.FALSE);
        log.exiting(this.getClass().getName(), "rollback");
    }
}
 
Example 5
Source File: DtxPrepareNegativeTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if preparing a DTX branch after setting fail flag in dtx.end throws an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class)
public void prepareDtxBranchAfterEndFails()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxPrepareTestCasePrepareDtxBranchAfterEndFails";

    InitialContext initialContext = JMSClientHelper
            .createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort())
            .withQueue(queueName)
            .build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    // We are not starting the dtx branch
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage("Test 1"));
    xaResource.end(xid, XAResource.TMFAIL);

    xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.close();
}
 
Example 6
Source File: TestFBXAResource.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testRollback2PCXATrans() throws Exception {
    FBManagedConnectionFactory mcf = initMcf();
    FBManagedConnection mc = mcf.createManagedConnection();
    XAResource xa = mc.getXAResource();
    Xid xid = new XidImpl();
    xa.start(xid, XAResource.TMNOFLAGS);
    assertNotNull("no db handle after start xid", mc.getGDSHelper().getCurrentDatabase());
    xa.end(xid, XAResource.TMSUCCESS);
    xa.prepare(xid);
    xa.rollback(xid);
    mc.destroy();
}
 
Example 7
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 8
Source File: DtxStartNegativeTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if joining a new XID will throw an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class,
      expectedExceptionsMessageRegExp = ".*Error while starting dtx session.*")
public void joinANonExistingDtxBranch()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxStartTestCaseJoinANonExistingDtxBranch";

    InitialContext initialContext = JMSClientHelper
            .createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort())
            .withQueue(queueName)
            .build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    xaResource.start(xid, XAResource.TMJOIN);

    // Below this line should not execute
    producer.send(session.createTextMessage("Test 1"));
    xaResource.end(xid, XAResource.TMSUCCESS);

    xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.close();
}
 
Example 9
Source File: XaTest.java    From jTDS with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Demonstrate interleaving local transactions and distributed
 * transactions.
 *
 * @throws Exception if an error condition occurs
 */
public void testLocalTran() throws Exception {
    if ("true".equalsIgnoreCase(props.getProperty(Messages.get(Driver.XAEMULATION)))) {
        // Emulation mode does not support suspending transactions.
        return;
    }
    Connection con2 = null;
    XAConnection xaCon = 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;
        Xid  xid;
        xaCon = xaDS.getXAConnection();
        xaRes = xaCon.getXAResource();
        con2 = xaCon.getConnection();
        stmt = con2.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')");
        xaRes.end(xid, XAResource.TMSUSPEND);
        stmt.executeUpdate("INSERT INTO jTDS_XATEST2 VALUES (1, 'TEST LINE')");
        xaRes.start(xid, XAResource.TMRESUME);
        stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (2, 'TEST LINE 2')");
        xaRes.end(xid, XAResource.TMSUCCESS);
        xaRes.rollback(xid);
        stmt.close();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
        assertNotNull(rs);
        assertFalse(rs.next());
        rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST2");
        assertNotNull(rs);
        assertTrue(rs.next());
        stmt.close();
    } finally {
        if (con2 != null) {
            con2.close();
        }
        if (xaCon != null) {
            xaCon.close();
        }

        dropTable("jTDS_XATEST");
        dropTable("jTDS_XATEST2");
    }
}
 
Example 10
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 11
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 CallableStatements
 * upon calling close() on them.
 */
public void testDerby4310CallableStatement() 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 procedure bazed on XATest.zeroArg() */
    Connection conn = xaconn.getConnection();
    Statement s = conn.createStatement();
    s.executeUpdate("CREATE PROCEDURE ZA() LANGUAGE JAVA "+
                    "EXTERNAL NAME 'com.splicemachine.dbTesting.functionTests.tests.jdbcapi.XATest.zeroArg' "+
                    "PARAMETER STYLE JAVA");
    conn.commit();
    
    /* Prepare and execute CallableStatement based on the procedure above */
    CallableStatement cs = conn.prepareCall("CALL ZA()");
    cs.execute();

    /* Start and end a transaction on the XAResource object */
    xar.start(xid, XAResource.TMNOFLAGS);
    xar.end(xid, XAResource.TMSUCCESS);
    
    /* Drop the procedure on a parallel, regular connection */
    Connection conn2 = getConnection();
    Statement s2 = conn2.createStatement();
    s2.execute("DROP PROCEDURE ZA");
    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. */
        cs.close();
    } finally {
        /* Rollback the transaction and close the connections */
        xar.rollback(xid);
        conn.close();
        xaconn.close();
    }
    
}
 
Example 12
Source File: DtxRollbackNegativeTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if rolling back a DTX branch without starting it throws an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class,
      expectedExceptionsMessageRegExp = ".*Error while rolling back dtx session.*")
public void rollbackDtxBranchWithoutEnding()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxRollbackTestCaseRollbackDtxBranchWithoutEnding";

    InitialContext initialContext = JMSClientHelper
            .createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort())
            .withQueue(queueName)
            .build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    // We are not starting the dtx branch
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage("Test 1"));
    // xaResource.end(xid, XAResource.TMFAIL);

    // xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.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: DtxEndNegativeTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if ending a dtx branch started in a different session throws an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class,
      expectedExceptionsMessageRegExp = ".*Error while ending dtx session.*")
public void endDtxBranchBelongToADifferentSession()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxEndTestCaseEndDtxBranchBelongToADifferentSession";

    InitialContext initialContext = JMSClientHelper
            .createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort())
            .withQueue(queueName)
            .build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

     // We are not starting the dtx branch
     xaResource.start(xid, XAResource.TMNOFLAGS);

    XAConnection secondXaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession secondXaSession = secondXaConnection.createXASession();

    XAResource secondXaResource = secondXaSession.getXAResource();


    producer.send(session.createTextMessage("Test 1"));
    secondXaResource.end(xid, XAResource.TMSUCCESS);

    xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.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_ROLLBACK command.
 *
 * @throws Exception if an error condition occurs
 */
public void testXaRollback() throws Exception {
    Connection con2 = null;
    XAConnection xaCon = null;

    try {
        dropTable("jTDS_XATEST");

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

        XADataSource xaDS = getDataSource();
        XAResource xaRes;
        Xid  xid;
        xaCon = xaDS.getXAConnection();
        xaRes = xaCon.getXAResource();
        con2 = xaCon.getConnection();
        stmt = con2.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')");
        xaRes.end(xid, XAResource.TMSUCCESS);
        xaRes.rollback(xid);
        stmt.close();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
        assertNotNull(rs);
        assertFalse(rs.next());
        stmt.close();
    } finally {
        if (con2 != null) {
            con2.close();
        }
        if (xaCon != null) {
            xaCon.close();
        }

        dropTable("jTDS_XATEST");
    }
}
 
Example 16
Source File: TransactionDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testXATransactionFromPeerClient_rollback() 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.rollback(xid);
  //TXManagerImpl.waitForPendingCommitForTest();
  VM servervm = getServerVM(1);
  servervm.invoke(TransactionDUnit.class, "waitForPendingCommit");
  
  sqlExecuteVerify(null, new int[] {1}, jdbcSQL, xmlFile, "before_xa_commit");
}
 
Example 17
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 18
Source File: DataSourceRegressionTest.java    From r-course with MIT License 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) ((com.mysql.jdbc.Connection) dbConn).getConnectionMutex()).getId();

        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 19
Source File: QueueDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Test
public void testConsumerWithRollback() throws Exception {
    String queueName = "testConsumerWithRollback";
    String testMessage = "testConsumerWithRollback-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory()
                                                         .withQueue(queueName)
                                                         .build();
    // Setup XA connection
    XAConnectionFactory xaConnectionFactory =
            (XAConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);

    XAConnection xaConnection = xaConnectionFactory.createXAConnection();
    XASession xaSession = xaConnection.createXASession();
    XAResource xaResource = xaSession.getXAResource();

    Session session = xaSession.getSession();
    Queue queue = session.createQueue(queueName);
    MessageProducer producer = session.createProducer(queue);
    MessageConsumer consumer = session.createConsumer(queue);
    xaConnection.start();
    producer.send(session.createTextMessage(testMessage));

    XidImpl xid = new XidImpl(0, "branchId_1".getBytes(), "globalId_1".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    TextMessage message = (TextMessage) consumer.receive(2000);
    xaResource.end(xid, XAResource.TMSUCCESS);

    int prepareOK = xaResource.prepare(xid);
    Assert.assertEquals(prepareOK, XAResource.XA_OK, "Prepare phase should return XA_OK.");

    xaResource.rollback(xid);

    session.close();
    xaConnection.close();

    Assert.assertNotNull(message, "Sent message should be consumed by the consumer.");
    Assert.assertEquals(message.getText(), testMessage, "Received message should match the sent message.");

    // Check whether the message is published to queue.
    QueueMetadata queueMetadata = restApiClient.getQueueMetadata(queueName);
    Assert.assertEquals((int) queueMetadata.getSize(), 1, "Queue should be non empty");


}
 
Example 20
Source File: TopicDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubscriberWithRollback() throws Exception {

    String subscriptionId = "sub-testSubscriberWithRollback";
    String topicName = "testSubscriberWithCommit";
    String testMessage = "testSubscriberWithCommit-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory().withTopic(topicName).build();
    Topic topic = (Topic) initialContext.lookup(topicName);

    // Setup XA consumer.
    XATopicConnectionFactory xaTopicConnectionFactory =
            (XATopicConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);
    XATopicConnection xaTopicConnection = xaTopicConnectionFactory.createXATopicConnection();
    XATopicSession xaTopicSession = xaTopicConnection.createXATopicSession();
    XAResource xaResource = xaTopicSession.getXAResource();
    TopicSubscriber durableSubscriber = xaTopicSession.createDurableSubscriber(topic, subscriptionId);

    // Setup non-transactional message publisher.
    TopicSession topicSession = xaTopicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    MessageProducer producer = topicSession.createProducer(topic);

    xaTopicConnection.start();

    producer.send(xaTopicSession.createTextMessage(testMessage));

    // Consume messages within a XA transaction.
    XidImpl xid = new XidImpl(0, "branchId".getBytes(), "globalId".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    TextMessage message = (TextMessage) durableSubscriber.receive(2000);
    xaResource.end(xid, XAResource.TMSUCCESS);

    int response = xaResource.prepare(xid);
    Assert.assertEquals(response, XAResource.XA_OK, "Prepare stage failed.");

    xaResource.rollback(xid);

    Assert.assertNotNull(message, "Didn't receive a message");
    Assert.assertEquals(message.getText(), testMessage, "Received message content didn't match sent message.");

    topicSession.close();
    xaTopicSession.close();
    xaTopicConnection.close();

    QueueMetadata queueMetadata = restApiClient.getQueueMetadata("carbon:" + subscriptionId);
    Assert.assertEquals((int) queueMetadata.getSize(), 1, "Queue shouldn't be empty.");
}