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

The following examples show how to use javax.transaction.xa.XAResource#end() . 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: TransactionImpl.java    From clearpool with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean delistResource(XAResource xaresource, int i) throws SystemException {
  if (this.status != Status.STATUS_ACTIVE) {
    throw new IllegalStateException("the transaction is not active");
  }
  TransactionAdapter txAdapt =
      (TransactionAdapter) TransactionManagerImpl.getManager().getTransaction();
  if (txAdapt.getTx() != this) {
    throw new IllegalStateException("the transaction is not held");
  }
  Xid xid = this.xaResMap.get(xaresource);
  if (xid == null) {
    return false;
  }
  try {
    xaresource.end(xid, i);
  } catch (XAException e) {
    String error = "can't end XA: " + e + " (error code = " + e.errorCode + ") " + e.getMessage();
    throw new SystemException(error);
  }
  return true;
}
 
Example 2
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 3
Source File: TestFBXAResource.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testStartXATrans() 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.commit(xid, true);
    mc.destroy();
}
 
Example 4
Source File: QueueDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublisherWithRollback() throws NamingException, JMSException, XAException, IOException {
    String queueName = "testPublisherWithRollback";
    String testMessage = "testPublisherWithRollback-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory()
                                                         .withQueue(queueName)
                                                         .build();

    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);
    xaConnection.start();

    XidImpl xid = new XidImpl(0, "branchId_1".getBytes(), "globalId_1".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage(testMessage));
    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);

    // Check whether the message is published to queue.
    QueueMetadata queueMetadata = restApiClient.getQueueMetadata(queueName);

    Assert.assertEquals((int) queueMetadata.getSize(), 0, "Queue should be empty");

    session.close();
    xaConnection.close();
}
 
Example 5
Source File: TestFBXAResource.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test2PCXATrans() 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.commit(xid, false);
    mc.destroy();
}
 
Example 6
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 7
Source File: DtxRecoverPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if recovering transactions return empty set when no prepared transactions are there. Steps are,
 *    1. A distributed sessions is started
 *    2. Before preparing recover and see we get an empty list
 *    3. Go to prepare stage and see if we get one item in the list
 *    4. Rollback and see if we get an empty list
 */
@Test(groups = { "wso2.mb", "dtx" })
public void performDtxRecoverWithPublishTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxRecoverPositiveTestCasePerformDtxRecoverWithPublishTestCase";

    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[] recoveredTransactions = xaResource.recover(XAResource.TMNOFLAGS);
    Assert.assertEquals(recoveredTransactions.length, 0, "Recovered Transaction list length should be 0 since "
            + "we don't have not started any transaction");

    Xid xid = JMSClientHelper.getNewXid();

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

    recoveredTransactions = xaResource.recover(XAResource.TMNOFLAGS);
    Assert.assertEquals(recoveredTransactions.length, 0, "Recovered Transaction list length should be 0 since "
            + "the transaction is not prepared yet");

    int ret = xaResource.prepare(xid);
    Assert.assertEquals(ret, XAResource.XA_OK, "Dtx.prepare was not successful.");

    recoveredTransactions = xaResource.recover(XAResource.TMNOFLAGS);
    Assert.assertEquals(recoveredTransactions.length, 1, "Recovered Transaction list length should be 1 since "
            + "the transaction is in prepared yet");

    byte[] originalBranchQualifier = xid.getBranchQualifier();
    byte[] originalGlobalTransactionId = xid.getGlobalTransactionId();
    byte[] receivedBranchQualifier = recoveredTransactions[0].getBranchQualifier();
    byte[] receivedGlobalTransactionId = recoveredTransactions[0].getGlobalTransactionId();

    boolean matching = Arrays.equals(originalBranchQualifier, receivedBranchQualifier) &&
            Arrays.equals(originalGlobalTransactionId, receivedGlobalTransactionId);

    Assert.assertTrue(matching, "Received xid does not match the original xid" );

    xaResource.rollback(xid);

    recoveredTransactions = xaResource.recover(XAResource.TMNOFLAGS);
    Assert.assertEquals(recoveredTransactions.length, 0, "Recovered Transaction list length should be 0 since "
            + "the transaction is not in prepared state");

    session.close();
    xaConnection.close();
}
 
Example 8
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 9
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testReadOnlyToWritableTran() throws SQLException, Exception
{
    // This fixture will run twice, once with embedded, once with client,
    // and insert 2 rows in addition to the 5 rows inserted during setup. 
    // The fixture tests a commit, so before running, try to remove row 
    // 6 and 7 in case this is the second run of the fixture.
    Statement s = createStatement();
    s.executeUpdate("delete from autocommitxastart where i = 6");
    s.executeUpdate("delete from autocommitxastart where i = 7");
    
    // TESTING READ_ONLY TRANSACTION FOLLOWED BY WRITABLE TRANSACTION
    // Test following sequence of steps
    // 1)start a read-only global transaction 
    // 2)finish that read-only transaction
    // 3)start another global transaction 

    XADataSource dsx = J2EEDataSource.getXADataSource();
    XAConnection xac5 = dsx.getXAConnection();
    Xid xid5a = new cdsXid(5, (byte) 119, (byte) 129);
    Connection conn5 = xac5.getConnection();
    Statement sru5a = conn5.createStatement();
    XAResource xar = xac5.getXAResource();
    xar.start(xid5a, XAResource.TMNOFLAGS);
    conn5.setReadOnly(true);

    // Read-Only XA transaction;
    // holdability: (hold, or close cursors over commit) , 
    // transaction isolation: read-committed, 
    // auto-commit false, read-only true (with embedded)
    if (usingEmbedded()) 
    {
        assertConnectionState(
            ResultSet.CLOSE_CURSORS_AT_COMMIT, 
            Connection.TRANSACTION_READ_COMMITTED,
            false, true, conn5);
    }
    // Note: the original test had no comments about this difference
    //       between Embedded and DerbyNetClient, this has apparently
    //       been accepted behavior.
    else if (usingDerbyNetClient())
    {
        assertConnectionState(
            ResultSet.CLOSE_CURSORS_AT_COMMIT, 
            Connection.TRANSACTION_READ_COMMITTED,
            false, false, conn5);
    }
    
    ResultSet rs5 = sru5a.executeQuery(
        "select count(*) from autocommitxastart");
    rs5.next();
    assertEquals(5, rs5.getInt(1));
    rs5.close();
    xar.end(xid5a, XAResource.TMSUCCESS);
    xar.commit(xid5a, true);
    conn5.close();
    
    //now start a new transaction
    conn5 = xac5.getConnection();
    sru5a = conn5.createStatement();
    xar.start(xid5a, XAResource.TMNOFLAGS);
    
    // Writeable XA transaction
    // holdability: (hold, or close cursors over commit) , 
    // transaction isolation: read-committed, 
    // auto-commit false, read-only false
    assertConnectionState(
            ResultSet.CLOSE_CURSORS_AT_COMMIT, 
            Connection.TRANSACTION_READ_COMMITTED,
            false, false, conn5);
    sru5a.executeUpdate("insert into autocommitxastart values 6,7");
    rs5 = sru5a.executeQuery("select count(*) from autocommitxastart");
    rs5.next();
    assertEquals(7, rs5.getInt(1));
    xar.end(xid5a, XAResource.TMSUCCESS);
    xar.commit(xid5a, true);
    conn5.close();
    xac5.close();
    sru5a.close();
}
 
Example 10
Source File: DtxStartPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if acknowledging a messages works correctly with session joining. Steps are,
 * 1. Publish two messages to two queues using two non-transacted sessions
 * 2. Create two distributed transaction sessions and join one session to other.
 * 3. Receive messages and ack using two sessions.
 * 4. Commit the session
 * 5. Subscribe to the published queue and see if any message is received.
 */
@Test(groups = { "wso2.mb", "dtx" })
public void xaStartJoinMessageAckTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueNameOne = "DtxStartPositiveTestCaseXaStartJoinMessageAckTestCaseOne";
    String queueNameTwo = "DtxStartPositiveTestCaseXaStartJoinMessageAckTestCaseTwo";

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

    ConnectionFactory nonXaConnectionFactory = (ConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY);
    Connection nonXaQueueConnection = nonXaConnectionFactory.createConnection();
    nonXaQueueConnection.start();
    Session nonXaQueueSessionOne = nonXaQueueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    Destination xaTestQueueOne = nonXaQueueSessionOne.createQueue(queueNameOne);
    Destination xaTestQueueTwo = nonXaQueueSessionOne.createQueue(queueNameTwo);

    MessageProducer nonXaQueueSessionProducerOne = nonXaQueueSessionOne.createProducer(xaTestQueueOne);
    MessageProducer nonXaQueueSessionProducerTwo = nonXaQueueSessionOne.createProducer(xaTestQueueTwo);

    nonXaQueueSessionProducerOne.send(nonXaQueueSessionOne.createTextMessage("Message 1"));
    nonXaQueueSessionProducerTwo.send(nonXaQueueSessionOne.createTextMessage("Message 2"));

    nonXaQueueSessionProducerOne.close();
    nonXaQueueSessionProducerTwo.close();

    XAConnectionFactory xaConnectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    // Create XA resource one
    XAConnection xaConnectionOne = xaConnectionFactory.createXAConnection();
    xaConnectionOne.start();
    XASession xaSessionOne = xaConnectionOne.createXASession();

    XAResource xaResourceOne = xaSessionOne.getXAResource();
    Session sessionOne = xaSessionOne.getSession();

    MessageConsumer xaConsumerOne = sessionOne.createConsumer(xaTestQueueOne);

    // Create XA resource two
    XAConnection xaConnectionTwo = xaConnectionFactory.createXAConnection();
    xaConnectionTwo.start();
    XASession xaSessionTwo = xaConnectionTwo.createXASession();

    XAResource xaResourceTwo = xaSessionTwo.getXAResource();
    Session sessionTwo = xaSessionTwo.getSession();

    MessageConsumer xaConsumerTwo = sessionTwo.createConsumer(xaTestQueueTwo);

    Xid xid = JMSClientHelper.getNewXid();

    boolean sameRM = xaResourceOne.isSameRM(xaResourceTwo);

    Assert.assertEquals(sameRM, true, "Resource one and resource two are connected to different resource "
            + "managers");

    xaResourceOne.start(xid, XAResource.TMNOFLAGS);
    xaResourceTwo.start(xid, XAResource.TMJOIN);

    Message receivedMessageForQueueOne = xaConsumerOne.receive(5000);
    Assert.assertNotNull(receivedMessageForQueueOne, "A message was not received for queue " + queueNameOne);
    Message receivedMessageForQueueTwo = xaConsumerTwo.receive(5000);
    Assert.assertNotNull(receivedMessageForQueueTwo, "A message was not received for queue " + queueNameTwo);

    xaResourceOne.end(xid, XAResource.TMSUCCESS);

    xaResourceOne.prepare(xid);
    xaResourceOne.commit(xid, false);

    xaConnectionOne.close();
    xaConnectionTwo.close();

    // subscribe and see if the message is received
    MessageConsumer nonXaConsumerOne = nonXaQueueSessionOne.createConsumer(xaTestQueueOne);

    Session nonXaQueueSessionTwo = nonXaQueueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer nonXaConsumerTwo = nonXaQueueSessionTwo.createConsumer(xaTestQueueTwo);

    // wait 3 seconds
    receivedMessageForQueueOne = nonXaConsumerOne.receive(3000);
    Assert.assertNull(receivedMessageForQueueOne, "Message received after committing for queue " + queueNameOne);

    receivedMessageForQueueTwo = nonXaConsumerTwo.receive(3000);
    Assert.assertNull(receivedMessageForQueueTwo, "Message received after committing for queue " + queueNameTwo);

    nonXaQueueConnection.close();
}
 
Example 11
Source File: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/** Tests whether it is possible to reconstruct the original Xid value
  * correctly from SYSCS_DIAG.TRANSACTION_TABLE. */
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
        assertTrue(rs.next());

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

        // there should be at most one global transaction in progress
        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 12
Source File: ClientIDNullTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if committing a published message works correctly without a client ID.Steps are,
 *    1. Using a distributed transaction a message is published to a queue and committed
 *    2. Subscribe to the published queue and see if the message is received.
 */
@Test(groups = { "wso2.mb", "dtx" })
public void performDtxClientQueuePublishTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "ClientIDNullTestCaseDtxPerformClientQueuePublishTestCase";

    InitialContext initialContext = JMSClientHelper.createInitialContextBuilder("admin",
                                                                                "admin",
                                                                                "localhost",
                                                                                getAMQPPort())
                                                   .withNoClientId()
                                                   .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.TMNOFLAGS);
    producer.send(session.createTextMessage("Test 1"));
    xaResource.end(xid, XAResource.TMSUCCESS);

    int ret = xaResource.prepare(xid);
    Assert.assertEquals(ret, XAResource.XA_OK, "Dtx.prepare was not successful.");

    xaResource.commit(xid, false);

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

    // subscribe and see if the message is received
    ConnectionFactory queueConnectionFactory = (ConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY);
    Connection queueConnection = queueConnectionFactory.createConnection();
    queueConnection.start();
    Session queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer messageConsumer = queueSession.createConsumer(xaTestQueue);

    // wait 5 seconds
    Message receive = messageConsumer.receive(5000);
    Assert.assertNotNull(receive, "Message was not received.");

    queueConnection.close();
}
 
Example 13
Source File: XATest.java    From r-course with MIT License 4 votes vote down vote up
/**
 * Tests that XA RECOVER works as expected.
 * 
 * @throws Exception
 *             if test fails
 */
public void testRecover() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }

    if (versionMeetsMinimum(5, 7) && !versionMeetsMinimum(5, 7, 5)) {
        // Test is broken in 5.7.0 - 5.7.4 after server bug#14670465 fix which changed the XA RECOVER output format.
        // Fixed in 5.7.5 server version
        return;
    }

    // BUG#14670465 fix broke this functionality in 5.7.1 - 5.7.2
    if (versionMeetsMinimum(5, 7, 1) && !versionMeetsMinimum(5, 7, 3)) {
        return;
    }

    XAConnection xaConn = null, recoverConn = null;

    try {
        xaConn = getXAConnection();

        Connection c = xaConn.getConnection();
        Xid xid = createXid();

        XAResource xaRes = xaConn.getXAResource();
        xaRes.start(xid, XAResource.TMNOFLAGS);
        c.createStatement().execute("SELECT 1");
        xaRes.end(xid, XAResource.TMSUCCESS);
        xaRes.prepare(xid);

        // Now try and recover
        recoverConn = getXAConnection();

        XAResource recoverRes = recoverConn.getXAResource();

        Xid[] recoveredXids = recoverRes.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);

        assertTrue(recoveredXids != null);
        assertTrue(recoveredXids.length > 0);

        boolean xidFound = false;

        for (int i = 0; i < recoveredXids.length; i++) {
            if (recoveredXids[i] != null && recoveredXids[i].equals(xid)) {
                xidFound = true;

                break;
            }
        }

        assertTrue(xidFound);

        recoverRes = recoverConn.getXAResource();

        recoveredXids = recoverRes.recover(XAResource.TMSTARTRSCAN);

        assertTrue(recoveredXids != null);
        assertTrue(recoveredXids.length > 0);

        xidFound = false;

        for (int i = 0; i < recoveredXids.length; i++) {
            if (recoveredXids[i] != null && recoveredXids[i].equals(xid)) {
                xidFound = true;

                break;
            }
        }

        assertTrue(xidFound);

        // Test flags
        recoverRes.recover(XAResource.TMSTARTRSCAN);
        recoverRes.recover(XAResource.TMENDRSCAN);
        recoverRes.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);

        // This should fail
        try {
            recoverRes.recover(XAResource.TMSUCCESS);
            fail("XAException should have been thrown");
        } catch (XAException xaEx) {
            assertEquals(XAException.XAER_INVAL, xaEx.errorCode);
        }
    } finally {
        if (xaConn != null) {
            xaConn.close();
        }

        if (recoverConn != null) {
            recoverConn.close();
        }
    }
}
 
Example 14
Source File: DtxStartNegativeTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if resuming a new XID will throw an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class,
      expectedExceptionsMessageRegExp = ".*Error while starting dtx session.*")
public void resumeANonExistingDtxBranch()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxStartTestCaseResumeANonExistingDtxBranch";

    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.TMRESUME);

    // 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 15
Source File: DistributedTransactionTest.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void resumeAndJoinTest() throws Exception {
  Connection conn1;
  MariaDbDataSource ds = new MariaDbDataSource();
  ds.setUrl(connU);
  ds.setDatabaseName(database);
  ds.setUser(username);
  ds.setPassword(password);
  ds.setPort(port);
  XAConnection xaConn1 = null;
  Xid xid = newXid();
  try {
    xaConn1 = ds.getXAConnection();
    XAResource xaRes1 = xaConn1.getXAResource();
    conn1 = xaConn1.getConnection();
    xaRes1.start(xid, XAResource.TMNOFLAGS);
    conn1.createStatement().executeQuery("SELECT 1");
    xaRes1.end(xid, XAResource.TMSUCCESS);
    xaRes1.start(xid, XAResource.TMRESUME);
    conn1.createStatement().executeQuery("SELECT 1");
    xaRes1.end(xid, XAResource.TMSUCCESS);
    xaRes1.commit(xid, true);
    xaConn1.close();

    xaConn1 = ds.getXAConnection();
    xaRes1 = xaConn1.getXAResource();
    conn1 = xaConn1.getConnection();
    xaRes1.start(xid, XAResource.TMNOFLAGS);
    conn1.createStatement().executeQuery("SELECT 1");
    xaRes1.end(xid, XAResource.TMSUCCESS);
    try {
      xaRes1.start(xid, XAResource.TMJOIN);
      fail(); // without pinGlobalTxToPhysicalConnection=true
    } catch (XAException xaex) {
      xaConn1.close();
    }

    xid = newXid();
    ds.setUrl(connU + "?pinGlobalTxToPhysicalConnection=true");
    xaConn1 = ds.getXAConnection();
    xaRes1 = xaConn1.getXAResource();
    conn1 = xaConn1.getConnection();
    xaRes1.start(xid, XAResource.TMNOFLAGS);
    conn1.createStatement().executeQuery("SELECT 1");
    xaRes1.end(xid, XAResource.TMSUCCESS);
    xaRes1.start(xid, XAResource.TMJOIN);
    conn1.createStatement().executeQuery("SELECT 1");
    xaRes1.end(xid, XAResource.TMSUCCESS);
    xaRes1.commit(xid, true);
  } finally {
    if (xaConn1 != null) {
      xaConn1.close();
    }
  }
}
 
Example 16
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 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: XATest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * DERBY-5552 Check that lock timeout does not destroy connection
 * during an XA Transaction.
 * 
 * @throws SQLException
 * @throws XAException
 */
public void testXALockTimeout() throws SQLException, XAException {
    XADataSource xads = J2EEDataSource.getXADataSource();
    J2EEDataSource.setBeanProperty(xads, "databaseName", "wombat");
   
    // Get the first connection and lock table in 
    // xa transaction
    XAConnection xaconn = xads.getXAConnection();
    XAResource xar = xaconn.getXAResource();
    Xid xid = XATestUtil.getXid(998,10,50);
   
    Connection conn = xaconn.getConnection();
    Statement s = conn.createStatement();
    xar.start(xid, XAResource.TMNOFLAGS);
    s.executeUpdate("INSERT INTO TABLT VALUES(2)");
    
    // Get a second connection and global xact
    // and try to select causing lock timeout
    XAConnection xaconn2 = xads.getXAConnection();
    XAResource xar2 = xaconn2.getXAResource();
    Xid xid2 = XATestUtil.getXid(999,11,51);
    Connection conn2 = xaconn2.getConnection();
    // Set to serializable so we get lock timeout
    conn2.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    xar2.start(xid2, XAResource.TMNOFLAGS);
    Statement s2 = conn2.createStatement();
    s2.executeUpdate("INSERT INTO TABLT VALUES(3)");
    assertGlobalXactCount(2);
    try {
        ResultSet rs = s2.executeQuery("SELECT * FROM TABLT");
        fail("Should have gotten lock timeout error: " + LOCKTIMEOUT);
    } catch (SQLException se) {
        assertSQLState(LOCKTIMEOUT,se);
        }
    // After the lock timeout we just have one global transaction.
    // lock timeout implicitly rolled back xid2
    assertGlobalXactCount(1);
    assertConnOK(conn);
    // DERBY-5552 Make sure connection is ok after lock timeout
    assertConnOK(conn2);
    //Should be able to end and commit xid1
    xar.end(xid, XAResource.TMSUCCESS);
    xar.prepare(xid);
    xar.commit(xid, false);
    
    // xid2 should have already been rolled back so end should fail
    try {    
        xar2.end(xid2, XAResource.TMSUCCESS);
        fail("Should have gotten exception ending xid2");
    } catch (XAException xae) {
        //xae.printStackTrace();
        assertEquals(XAException.XA_RBTIMEOUT, xae.errorCode);
        
    } 
 
    // Should have no locks on TABLT
    Statement drops = createStatement();
    drops.executeUpdate("DROP TABLE TABLT");
    // verify there are no more global transactions
    assertGlobalXactCount(0);
    
    // Need to explicitly rollback xid2 as it ended with
    // an implicit rollback XA_RBTIMEOUT
    xar2.rollback(xid2);
    
    // Make sure both connections can be used to make a new global xact
    xar.start(xid, XAResource.TMNOFLAGS);
    s.executeUpdate("CREATE TABLE TABLT (I INT)");
    s.executeUpdate("INSERT INTO TABLT VALUES(1)");
    xar.end(xid, XAResource.TMSUCCESS);
    xar.prepare(xid);
    xar.commit(xid, false);
    
    // now the other connection ..
    xar2.start(xid2, XAResource.TMNOFLAGS);
    s2.executeUpdate("INSERT INTO TABLT VALUES(2)");
    xar2.end(xid2, XAResource.TMSUCCESS);
    xar.prepare(xid2);
    xar.commit(xid2, false);
    assertGlobalXactCount(0);
    conn.close();
    xaconn.close();
    conn2.close();
    xaconn2.close();
    
}
 
Example 19
Source File: MultipleXidTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Publish with two distinct connections with separate transactions and then consume the messages
 * Messages should preserve the order in which messages were committed
 *
 * @throws XPathExpressionException
 * @throws NamingException
 * @throws JMSException
 * @throws XAException
 */
@Test(groups = {"wso2.mb", "dtx"})
private void publishConsumeWithDistinctConnections() throws XPathExpressionException, NamingException,
                                                            JMSException, XAException {

    String queueName = "publishConsumeWithDistinctConnections";
    String xid1Message = "xid 1";
    String xid2Message = "xid 2";

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

    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection1 = connectionFactory.createXAConnection();
    XAConnection xaConnection2 = connectionFactory.createXAConnection();
    xaConnection1.start();
    xaConnection2.start();
    XASession xaSession1 = xaConnection1.createXASession();
    XASession xaSession2 = xaConnection2.createXASession();

    XAResource xaResource1 = xaSession1.getXAResource();
    XAResource xaResource2 = xaSession2.getXAResource();
    Session session1 = xaSession1.getSession();
    Session session2 = xaSession2.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session1.createQueue(queueName);

    MessageConsumer consumer = session1.createConsumer(xaTestQueue);

    MessageProducer producer = session1.createProducer(xaTestQueue);
    MessageProducer producer2 = session2.createProducer(xaTestQueue);

    Xid xid1 = new TestXidImpl(100, new byte[]{0x01}, new byte[]{0x09});
    Xid xid2 = new TestXidImpl(100, new byte[]{0x01}, new byte[]{0x10});

    xaResource1.start(xid1, XAResource.TMNOFLAGS);
    producer.send(session1.createTextMessage(xid1Message));
    xaResource1.end(xid1, XAResource.TMSUCCESS);

    xaResource2.start(xid2, XAResource.TMNOFLAGS);
    producer2.send(session2.createTextMessage(xid2Message));
    xaResource2.end(xid2, XAResource.TMSUCCESS);

    // Xid 2
    int status = xaResource2.prepare(xid2);
    Assert.assertEquals(status, XAResource.XA_OK, "Prepare state failed for distributed transaction");

    xaResource2.commit(xid2, false);
    JMSTextMessage message = (JMSTextMessage) consumer.receive(30000);

    Assert.assertEquals(message.getText(), xid2Message, "Invalid Message received");

    // Xid 1
    status = xaResource1.prepare(xid1);
    Assert.assertEquals(status, XAResource.XA_OK, "Prepare state failed for distributed transaction");

    xaResource1.commit(xid1, false);
    message = (JMSTextMessage) consumer.receive(30000);

    Assert.assertEquals(message.getText(), xid1Message, "Invalid Message received");

    session1.close();
    session2.close();
    xaConnection1.close();
    xaConnection2.close();

}
 
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();

}