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

The following examples show how to use javax.transaction.xa.XAResource#commit() . 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: XATransactionTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testSimpleXATransaction() throws Exception {
  Statement stm = getConnection().createStatement();
  stm.execute("create table XATT2 (i int, text char(10))");

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

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

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

  stm = getConnection().createStatement();
  stm.execute("select * from XATT2");
  ResultSet rs = stm.getResultSet();
  assertFalse(rs.next());
  // end the work on the transaction branch
  xaRes.end(xid, XAResource.TMSUCCESS);
  xaRes.prepare(xid);
  xaRes.commit(xid, false);
  stm.execute("select * from XATT2");
  rs = stm.getResultSet();
  assertTrue(rs.next());
}
 
Example 3
Source File: ActiveMQXAResourceWrapper.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void commit(final Xid xid, final boolean onePhase) throws XAException {
   XAResource xaResource = getDelegate(true);
   if (ActiveMQXARecoveryLogger.LOGGER.isDebugEnabled()) {
      ActiveMQXARecoveryLogger.LOGGER.debug("Commit " + xaResource + " xid " + " onePhase=" + onePhase);
   }
   try {
      xaResource.commit(xid, onePhase);
   } catch (XAException e) {
      throw check(e);
   }
}
 
Example 4
Source File: TestFBConnection.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testUseStatement() throws Exception {
    FBManagedConnectionFactory mcf = initMcf();
    FBManagedConnection mc = mcf.createManagedConnection();
    try {
        Connection c = mc.getConnection();
        Statement s = c.createStatement();
        XAResource xa = mc.getXAResource();
        Exception ex = null;
        Xid xid = new XidImpl();
        xa.start(xid, XAResource.TMNOFLAGS);
        try {
            s.execute("CREATE TABLE T1 ( C1 SMALLINT, C2 SMALLINT)");
            //s.close();
        } catch (Exception e) {
            ex = e;
        }
        xa.end(xid, XAResource.TMSUCCESS);
        xa.commit(xid, true);

        xid = new XidImpl();
        xa.start(xid, XAResource.TMNOFLAGS);
        s.execute("DROP TABLE T1");
        s.close();
        xa.end(xid, XAResource.TMSUCCESS);
        xa.commit(xid, true);
        if (ex != null) {
            throw ex;
        }
    } finally {
        mc.destroy();
    }
}
 
Example 5
Source File: TestFBXAResource.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test that use of multiple statements in distributed transactions does not close result sets.
 * <p>
 * See <a href="http://tracker.firebirdsql.org/browse/JDBC-344">JDBC-344</a>
 * </p>
 */
@Test
public void testXAMultipleStatements() 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 (Statement stmt1 = con.createStatement();
             Statement stmt2 = con.createStatement()) {
            ResultSet rs1 = stmt1.executeQuery("SELECT RDB$CHARACTER_SET_NAME FROM RDB$CHARACTER_SETS");
            assertTrue("Expected rs1 row 1", rs1.next());
            assertNotNull("Expected rs1 value for row 1, column 1", rs1.getString(1));
            ResultSet rs2 = stmt2.executeQuery("SELECT 1 FROM RDB$DATABASE");
            assertTrue("Expected rs2 row 1", rs2.next());
            assertEquals("Expected value 1 for rs2 row 1, column 1", 1, rs2.getInt(1));
            assertFalse("Expected rs1 to be open as the resultset shouldn't have been closed by interleaved execution of stmt2", rs1.isClosed());

            rs1.close();
            rs2.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 6
Source File: FailureXATest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void doTestCrashServerAfterXACommit(boolean onePhase) throws Exception {
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
   XAConnection connection = connectionFactory.createXAConnection();

   try {
      Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
      Queue queue = session.createQueue("Queue1");
      final XASession xaSession = connection.createXASession();
      MessageConsumer consumer = xaSession.createConsumer(queue);

      MessageProducer producer = session.createProducer(queue);
      producer.send(session.createTextMessage("hello " + 1));
      session.commit();

      XAResource xaResource = xaSession.getXAResource();
      final Xid xid = newXID();
      xaResource.start(xid, XAResource.TMNOFLAGS);

      connection.start();
      Assert.assertNotNull(consumer.receive(5000));

      xaResource.end(xid, XAResource.TMSUCCESS);

      try {
         xaResource.commit(xid, onePhase);
         Assert.fail("didn't get expected exception!");
      } catch (XAException xae) {
         if (onePhase) {
            //expected error code is XAER_RMFAIL
            Assert.assertEquals(XAException.XAER_RMFAIL, xae.errorCode);
         } else {
            //expected error code is XA_RETRY
            Assert.assertEquals(XAException.XA_RETRY, xae.errorCode);
         }
      }
   } finally {
      connection.close();
   }
}
 
Example 7
Source File: ActiveMQXAConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void testConsumerCloseTransactionalSendReceive() throws Exception {

      ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false");
      XAConnection connection1 = (XAConnection) cf1.createConnection();
      connection1.start();
      XASession session = connection1.createXASession();
      XAResource resource = session.getXAResource();
      Destination dest = new ActiveMQQueue(getName());

      // publish a message
      Xid tid = createXid();
      resource.start(tid, XAResource.TMNOFLAGS);
      MessageProducer producer = session.createProducer(dest);
      ActiveMQTextMessage message = new ActiveMQTextMessage();
      message.setText(getName());
      producer.send(message);
      producer.close();
      resource.end(tid, XAResource.TMSUCCESS);
      resource.commit(tid, true);
      session.close();

      session = connection1.createXASession();
      MessageConsumer consumer = session.createConsumer(dest);
      tid = createXid();
      resource = session.getXAResource();
      resource.start(tid, XAResource.TMNOFLAGS);
      TextMessage receivedMessage = (TextMessage) consumer.receive(1000);
      consumer.close();
      assertNotNull(receivedMessage);
      assertEquals(getName(), receivedMessage.getText());
      resource.end(tid, XAResource.TMSUCCESS);
      resource.commit(tid, true);

      session = connection1.createXASession();
      consumer = session.createConsumer(dest);
      tid = createXid();
      resource = session.getXAResource();
      resource.start(tid, XAResource.TMNOFLAGS);
      assertNull(consumer.receive(1000));
      resource.end(tid, XAResource.TMSUCCESS);
      resource.commit(tid, true);

   }
 
Example 8
Source File: EI737DTXOnePhaseCommitTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if one-phase commit in distributed transactions, is working correctly for message publishing.
 * Steps are,
 * 1. Using a distributed transaction publish a message to a  queue and commit in one-phase
 * 2. Subscribe to the published queue and see if the message is received.
 */
@Test(groups = { "wso2.mb", "dtx" })
public void performClientQueuePublishTestCase() throws Exception {
    String queueName = "DtxOnePhaseCommitMessagePublishingTest";

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

    // Publish to queue and commit in one-phase
    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 Message publishing"));
    xaResource.end(xid, XAResource.TMSUCCESS);

    xaResource.commit(xid, true);

    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(10000);
    Assert.assertNotNull(receive, "Message was not received. One-phase commit might have failed");

    queueConnection.close();
}
 
Example 9
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 10
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 11
Source File: ActiveMQXAConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void testSessionCloseTransactionalSendReceive() throws Exception {

      ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false");
      XAConnection connection1 = (XAConnection) cf1.createConnection();
      connection1.start();
      XASession session = connection1.createXASession();
      XAResource resource = session.getXAResource();
      Destination dest = new ActiveMQQueue(getName());

      // publish a message
      Xid tid = createXid();
      resource.start(tid, XAResource.TMNOFLAGS);
      MessageProducer producer = session.createProducer(dest);
      ActiveMQTextMessage message = new ActiveMQTextMessage();
      message.setText(getName());
      producer.send(message);
      session.close();
      resource.end(tid, XAResource.TMSUCCESS);
      resource.commit(tid, true);

      session = connection1.createXASession();
      MessageConsumer consumer = session.createConsumer(dest);
      tid = createXid();
      resource = session.getXAResource();
      resource.start(tid, XAResource.TMNOFLAGS);
      TextMessage receivedMessage = (TextMessage) consumer.receive(1000);
      session.close();
      assertNotNull(receivedMessage);
      assertEquals(getName(), receivedMessage.getText());
      resource.end(tid, XAResource.TMSUCCESS);
      resource.commit(tid, true);

      session = connection1.createXASession();
      consumer = session.createConsumer(dest);
      tid = createXid();
      resource = session.getXAResource();
      resource.start(tid, XAResource.TMNOFLAGS);
      assertNull(consumer.receive(1000));
      resource.end(tid, XAResource.TMSUCCESS);
      resource.commit(tid, true);
   }
 
Example 12
Source File: TransactionDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testXATransactionFromClient_commit() 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.commit(xid, false);

  //TXManagerImpl.waitForPendingCommitForTest();
  
  VM servervm = getServerVM(1);
  servervm.invoke(TransactionDUnit.class, "waitForPendingCommit");
  sqlExecuteVerify(null, new int[] {1}, jdbcSQL, xmlFile, "after_xa_commit");
}
 
Example 13
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 14
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 15
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 16
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 17
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();
}
 
Example 18
Source File: DtxPrepareNegativeTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if preparing a DTX branch with publishing permission issues throws an error
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class)
public void prepareDtxBranchWithNoRoutesIssue()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxPrepareTestCasePrepareDtxBranchWithNoRoutesIssues";

    User adminUser = getSuperTenantAdminUser();
    InitialContext adminInitialContext
            = JMSClientHelper.createInitialContextBuilder(adminUser.getUserNameWithoutDomain(),
                                                          adminUser.getPassword(),
                                                          getBrokerHost(),
                                                          getAMQPPort()).withQueue(queueName).build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory
            = (XAConnectionFactory) adminInitialContext.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 testQueue = (Destination) adminInitialContext.lookup(queueName);
    MessageProducer producer = session.createProducer(testQueue);

    Xid xid = JMSClientHelper.getNewXid();

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

    // Test should fail at prepare stage due to no route issue
    int prepareResponseCode = xaResource.prepare(xid);

    Assert.assertNotEquals(prepareResponseCode, XAResource.XA_OK, "Prepare should fail due to no route issue");

    xaResource.commit(xid, false);

    session.close();
    xaConnection.close();
}
 
Example 19
Source File: XATransactionTest.java    From gemfirexd-oss with Apache License 2.0 2 votes vote down vote up
public void testSingleConnectionOnePhaseCommit() throws SQLException,
    XAException {

  Statement stm = getConnection().createStatement();
  stm.execute("create table XATT2 (i int, text char(10))");

  XADataSource xads = (XADataSource)TestUtil.getXADataSource(TestUtil.EmbeddedeXADsClassName);

  XAConnection xac = xads.getXAConnection();

  XAResource xar = xac.getXAResource();

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

  xar.start(xid, XAResource.TMNOFLAGS);

  Connection conn = xac.getConnection();
  conn.setTransactionIsolation(getIsolationLevel());
  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");
  assertTrue(rs.next());
  assertFalse(rs.next());

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

  // TODO: what to check
  // XATestUtil.checkXATransactionView(conn, expectedRows);

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

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

  conn.close();
  xac.close();
}
 
Example 20
Source File: XATest.java    From spliceengine with GNU Affero General Public License v3.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", "wombat");

    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", "SPLICE",
            "UserTransaction" } };

    XATestUtil.checkXATransactionView(conn, expectedRows);

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

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

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

}