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

The following examples show how to use javax.transaction.xa.XAResource#prepare() . 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: ActiveMQXAResourceWrapper.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public int prepare(final Xid xid) throws XAException {
   XAResource xaResource = getDelegate(true);
   if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) {
      ActiveMQXARecoveryLogger.LOGGER.debug("prepare " + xaResource + " xid ");
   }
   try {
      return xaResource.prepare(xid);
   } catch (XAException e) {
      throw check(e);
   }
}
 
Example 2
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 3
Source File: RMXAConnectionResource.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Override
public int prepare(Xid xid) throws XAException {
    log.entering(this.getClass().getName(), "prepare");
    // log.fine(FHIRUtilities.getCurrentStacktrace());
    int vote = XAResource.XA_OK;
    try {
        // Retrieve the XAResource(s) associated with this Xid.
        List<XAResource> resources = getXAResourcesForXid(xid);
        if (resources == null) {
            throw new XAException("prepare: Unknown Xid");
        }

        String xidString = displayXid(xid);
        log.info("Initiating recovery 'prepare' 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) {
            int resourceVote = resource.prepare(xid);
            if (resourceVote > vote) {
                vote = resourceVote;
            }
        }
        
        log.info("Finished recovery 'prepare' processing for Xid:\n" + xidString);
        return vote;
    } finally {
        setBypassFailures(Boolean.FALSE);
        log.exiting(this.getClass().getName(), "prepare", new Object[] {
                "vote", vote
        });
    }
}
 
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: 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 6
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 7
Source File: DtxEndNegativeTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if ending DTX branch without starting it throws an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class,
      expectedExceptionsMessageRegExp = ".*Error while ending dtx session.*")
public void endDtxBranchWithoutStarting()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxEndTestCaseEndDtxBranchWithoutStarting";

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

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

    xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.close();
}
 
Example 8
Source File: DtxRollbackPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if rolling back a message acknowledgement works correctly.Steps are,
 *    1. Publish a message to a queue
 *    2. Using a distributed transacted session receive the message and roll back
 *    3. Subscribe again using a normal session and see if the message is received
 */
@Test(groups = { "wso2.mb", "dtx" })
public void performClientQueueAcknowledgeTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "RollbackTestCasePerformClientQueueAcknowledgeTestCase";

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

    // Publish message to queue
    ConnectionFactory queueConnectionFactory = (ConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY);
    Connection queueConnection = queueConnectionFactory.createConnection();
    Session queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    queueSession.createQueue(queueName);
    MessageProducer messageProducer = queueSession.createProducer(xaTestQueue);

    messageProducer.send(queueSession.createTextMessage("Test message"));

    messageProducer.close();

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

    MessageConsumer xaConsumer = session.createConsumer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    xaResource.start(xid, XAResource.TMNOFLAGS);
    Message receivedMessage = xaConsumer.receive(5000);
    xaResource.end(xid, XAResource.TMSUCCESS);

    Assert.assertNotNull(receivedMessage, "No message received");

    xaResource.prepare(xid);

    xaResource.rollback(xid);


    xaResource.start(xid, XAResource.TMNOFLAGS);
    receivedMessage = xaConsumer.receive(5000);
    xaResource.end(xid, XAResource.TMSUCCESS);

    Assert.assertNotNull(receivedMessage, "No message received. Roll back might have failed");

    xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.close();
    queueConnection.close();
}
 
Example 9
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 10
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 11
Source File: XATest.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Tests that simple distributed transaction processing works as expected.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testCoordination() throws Exception {
    createTable("testCoordination", "(field1 int) ENGINE=InnoDB");

    Connection conn1 = null;
    Connection conn2 = null;
    XAConnection xaConn1 = null;
    XAConnection xaConn2 = null;

    try {
        xaConn1 = getXAConnection();
        XAResource xaRes1 = xaConn1.getXAResource();
        conn1 = xaConn1.getConnection();

        xaConn2 = getXAConnection();
        XAResource xaRes2 = xaConn2.getXAResource();
        conn2 = xaConn2.getConnection();

        Xid xid1 = createXid();
        Xid xid2 = createXid(xid1);

        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");
        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");
        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);

        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);

        xaRes1.commit(xid1, false);
        xaRes2.commit(xid2, false);

        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");

        assertTrue(this.rs.next());
        assertEquals(1, this.rs.getInt(1));

        assertTrue(this.rs.next());
        assertEquals(2, this.rs.getInt(1));

        this.stmt.executeUpdate("TRUNCATE TABLE testCoordination");

        //
        // Now test rollback
        //

        xid1 = createXid();
        xid2 = createXid(xid1);

        xaRes1.start(xid1, XAResource.TMNOFLAGS);
        xaRes2.start(xid2, XAResource.TMNOFLAGS);
        conn1.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (1)");

        // ensure visibility
        assertEquals("1", getSingleIndexedValueWithQuery(conn1, 1, "SELECT field1 FROM testCoordination WHERE field1=1").toString());

        conn2.createStatement().executeUpdate("INSERT INTO testCoordination VALUES (2)");

        // ensure visibility
        assertEquals("2", getSingleIndexedValueWithQuery(conn2, 1, "SELECT field1 FROM testCoordination WHERE field1=2").toString());

        xaRes1.end(xid1, XAResource.TMSUCCESS);
        xaRes2.end(xid2, XAResource.TMSUCCESS);

        xaRes1.prepare(xid1);
        xaRes2.prepare(xid2);

        xaRes1.rollback(xid1);
        xaRes2.rollback(xid2);

        this.rs = this.stmt.executeQuery("SELECT field1 FROM testCoordination ORDER BY field1");

        assertTrue(!this.rs.next());
    } finally {
        if (conn1 != null) {
            conn1.close();
        }

        if (conn2 != null) {
            conn2.close();
        }

        if (xaConn1 != null) {
            xaConn1.close();
        }

        if (xaConn2 != null) {
            xaConn2.close();
        }
    }
}
 
Example 12
Source File: XATest.java    From Komondor with GNU General Public License v3.0 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 13
Source File: DtxCommitPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if rolling back a message acknowledgement works correctly. Steps are,
 *    1. Publish a message to a queue
 *    2. Using a distributed transacted session receive the message and commit
 *    3. Subscribe again using a normal session and see if any message is received
 */
@Test(groups = { "wso2.mb", "dtx" })
public void performClientQueueAcknowledgeTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "CommitTestCasePerformClientQueueAcknowledgeTestCase";

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

    // Publish message to queue
    ConnectionFactory queueConnectionFactory = (ConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY);
    Connection queueConnection = queueConnectionFactory.createConnection();
    queueConnection.start();
    Session queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    queueSession.createQueue(queueName);
    MessageProducer messageProducer = queueSession.createProducer(xaTestQueue);

    messageProducer.send(queueSession.createTextMessage("Test message"));

    messageProducer.close();

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

    MessageConsumer xaConsumer = session.createConsumer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    xaResource.start(xid, XAResource.TMNOFLAGS);
    Message receivedMessage = xaConsumer.receive(5000);
    xaResource.end(xid, XAResource.TMSUCCESS);

    Assert.assertNotNull(receivedMessage, "No message received");


    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
    MessageConsumer messageConsumer = queueSession.createConsumer(xaTestQueue);

    // wait 5 seconds
    Message receivedMessageFromNormalConnection = messageConsumer.receive(5000);
    Assert.assertNull(receivedMessageFromNormalConnection, "Message received. Commit might have failed");

    queueConnection.close();
}
 
Example 14
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 15
Source File: QueueDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Test
public void testConsumerWithCommit() throws Exception {
    String queueName = "testConsumerWithCommit";
    String testMessage = "testConsumerWithCommit-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.commit(xid, false);

    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(), 0, "Queue should be empty");

}
 
Example 16
Source File: WorkDoneOutsideTransactionTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Publish and then consume outside a distributed transaction
 *
 * @throws XPathExpressionException
 * @throws NamingException
 * @throws JMSException
 * @throws XAException
 */
@Test(groups = { "wso2.mb", "dtx" })
public void publishConsumeOutsideTransactionTestCase() throws XPathExpressionException, NamingException,
                                                              JMSException, XAException {

    String queueName = "publishConsumeOutsideTransactionTestCase";
    String outsideTransactionMessage = "outside transaction";

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


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

    MessageConsumer consumer = session.createConsumer(xaTestQueue);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = new TestXidImpl(100, new byte[] { 0x01 }, new byte[] { 0x05 });

    producer.send(session.createTextMessage(outsideTransactionMessage));

    xaResource.start(xid, XAResource.TMNOFLAGS);
    consumer.receive(30000);
    xaResource.end(xid, XAResource.TMSUCCESS);

    int status  = xaResource.prepare(xid);
    Assert.assertEquals(status, XAResource.XA_OK, "Prepare state failed for distributed transaction");

    xaResource.rollback(xid);
    JMSTextMessage message = (JMSTextMessage) consumer.receive(30000);

    Assert.assertNotNull(message, "Message did not receive from server");
    Assert.assertEquals(message.getText(), outsideTransactionMessage, "Invalid Message received");

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

}
 
Example 17
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 18
Source File: TopicDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubscriberWithCommit() throws Exception {

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

    // Create 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);

    // Create non transactional producer.
    TopicSession topicSession = xaTopicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    MessageProducer producer = topicSession.createProducer(topic);

    xaTopicConnection.start();

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

    // Consume message 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.commit(xid, false);

    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(), 0, "Queue should be empty.");
}
 
Example 19
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 20
Source File: TopicDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Test
public void testPublisherWithCommit() throws Exception {

    String subscriptionId = "sub-testPublisherWithCommit";
    String topicName = "testPublisherWithCommit";
    String testMessage = "testPublisherWithCommit-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 within 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.commit(xid, false);

    TextMessage message = (TextMessage) durableSubscriber.receive(2000);
    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();
}