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

The following examples show how to use javax.transaction.xa.XAResource#start() . 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: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * DERBY-4141 XAExceptions caused by SQLExceptions should have a
 * non-zero errorCode. SESSION_SEVERITY or greater map to
 * XAException.XAER_RMFAIL. Lesser exceptions map to XAException.XAER_RMERR 
 * @throws Exception
 */
public void testXAExceptionErrorCodeOnSQLExceptionDerby4141() throws Exception {
    XADataSource xaDataSource = J2EEDataSource.getXADataSource();
    XAConnection xaConn = xaDataSource.getXAConnection();
    XAResource xaRes = xaConn.getXAResource();        
    Xid xid = createXid(123, 1);
    // close the XAConnection so we get an SQLException on
    // start();
    xaConn.close();
    try {
        xaRes.start(xid, XAResource.TMNOFLAGS);
        fail("Should have gotten an XAException. xaConn is closed.");
    } catch (XAException xae) {
        assertEquals(XAException.XAER_RMFAIL, xae.errorCode);
    }
}
 
Example 2
Source File: TestFBXADataSource.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test if calling commit throws an exception when participating in a distributed transaction (JDBC 4.0 section 12.4).
 */
@Test
public void testInDistributed_commit() throws Exception {
    XAConnection pc = getXAConnection();
    XAResource xa = pc.getXAResource();
    Xid xid = new XidImpl();
    try (Connection con = pc.getConnection()) {
        con.setAutoCommit(false);
        xa.start(xid, XAResource.TMNOFLAGS);

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

        con.commit();
    } finally {
        xa.end(xid, XAResource.TMSUCCESS);
        xa.rollback(xid);
    }
}
 
Example 3
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 4
Source File: DistributedTransactionTest.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testRecover() throws Exception {
  XAConnection xaConnection = dataSource.getXAConnection();
  try {
    Connection connection = xaConnection.getConnection();
    Xid xid = newXid();
    XAResource xaResource = xaConnection.getXAResource();
    xaResource.start(xid, XAResource.TMNOFLAGS);
    connection.createStatement().executeQuery("SELECT 1");
    xaResource.end(xid, XAResource.TMSUCCESS);
    xaResource.prepare(xid);
    Xid[] recoveredXids = xaResource.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);
    assertTrue(recoveredXids != null);
    assertTrue(recoveredXids.length > 0);
    boolean found = false;

    for (Xid x : recoveredXids) {
      if (x != null && x.equals(xid)) {
        found = true;
        break;
      }
    }
    assertTrue(found);
  } finally {
    xaConnection.close();
  }
}
 
Example 5
Source File: DtxPrepareNegativeTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if preparing a DTX branch after setting fail flag in dtx.end throws an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class)
public void prepareDtxBranchAfterEndFails()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxPrepareTestCasePrepareDtxBranchAfterEndFails";

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

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

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

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

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

    Xid xid = JMSClientHelper.getNewXid();

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

    xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.close();
}
 
Example 6
Source File: ActiveMQXAConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testCloseSendConnection() throws Exception {
   String brokerName = "closeSend";
   BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName));
   broker.start();
   broker.waitUntilStarted();
   ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri());
   XAConnection connection = (XAConnection) cf.createConnection();
   connection.start();
   XASession session = connection.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);

   connection.close();

   //comment out this check as it doesn't apply to artemis
   //assertTransactionGoneFromBroker(tid);

   broker.stop();
}
 
Example 7
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 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: 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 10
Source File: XATest.java    From FoxTelem 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, 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;
    }

    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 11
Source File: XATest.java    From Komondor with GNU General Public License v3.0 4 votes vote down vote up
public void testSuspendableTx() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }

    Connection conn1 = null;

    MysqlXADataSource suspXaDs = new MysqlXADataSource();
    suspXaDs.setUrl(BaseTestCase.dbUrl);
    suspXaDs.setPinGlobalTxToPhysicalConnection(true);
    suspXaDs.setRollbackOnPooledClose(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 12
Source File: DataSourceRegressionTest.java    From r-course with MIT License 4 votes vote down vote up
/**
 * Tests fix for BUG#72890 - Java jdbc driver returns incorrect return code when it's part of XA transaction
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug72890() throws Exception {
    MysqlXADataSource myDs = new MysqlXADataSource();
    myDs.setUrl(BaseTestCase.dbUrl);

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

        final XAConnection xaConn = myDs.getXAConnection();
        final XAResource xaRes = xaConn.getXAResource();
        final Connection dbConn = xaConn.getConnection();
        final long connId = ((MySQLConnection) ((com.mysql.jdbc.Connection) dbConn).getConnectionMutex()).getId();

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

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

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

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

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

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

        xaConnRecovery.close();
    }
}
 
Example 13
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 14
Source File: TestFBResultSet.java    From jaybird with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testUseResultSetMore() 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 INTEGER not null primary key, C2 SMALLINT, C3 DECIMAL(18,0), C4 FLOAT, C5 DOUBLE PRECISION, C6 CHAR(10), C7 VARCHAR(20), C8 TIME, C9 DATE, C10 TIMESTAMP)");
        } catch (Exception e) {
            ex = e;
        }
        xa.end(xid, XAResource.TMSUCCESS);
        xa.commit(xid, true);

        xid = new XidImpl();
        xa.start(xid, XAResource.TMNOFLAGS);
        assertFalse("execute returned true for insert statement",
                s.execute("insert into T1 values (1, 1, 1, 1.0, 1.0, 'one', 'one', '8:00:03.1234', '2002-JAN-11', '2001-JAN-6 8:00:03.1223')"));
        assertTrue("execute returned false for select statement", s.execute("select C1, C2, C3,  C4, C5, C6, C7, C8, C9, C10 from T1"));
        ResultSet rs = s.getResultSet();
        while (rs.next()) {
            if (log != null) log.info("C1: " + rs.getInt(1)
                    + " C2: " + rs.getShort(2)
                    + " C3: " + rs.getLong(3)
                    + " C4: " + rs.getFloat(4)
                    + " C5: " + rs.getDouble(5)
                    + " C6: " + rs.getString(6)
                    + " C7: " + rs.getString(7)
                    + " C8: " + rs.getTime(8)
                    + " C9: " + rs.getDate(9)
                    + " C10: " + rs.getTimestamp(10)
            );
            if (log != null) log.info("C1: " + rs.getInt("C1")
                    + " C2: " + rs.getShort("C2")
                    + " C3: " + rs.getLong("C3")
                    + " C4: " + rs.getFloat("C4")
                    + " C5: " + rs.getDouble("C5")
                    + " C6: " + rs.getString("C6")
                    + " C7: " + rs.getString("C7")
            );
        }
        rs.close();
        xa.end(xid, XAResource.TMSUCCESS);
        xa.commit(xid, true);

        xid = new XidImpl();
        xa.start(xid, XAResource.TMNOFLAGS);
        s.execute("DROP TABLE T1");
        xa.end(xid, XAResource.TMSUCCESS);
        xa.commit(xid, true);
        if (ex != null) {
            throw ex;
        }
    } finally {
        mc.destroy();
    }
}
 
Example 15
Source File: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <p>
 * Regression test case for DERBY-5562.
 * </p>
 *
 * <p>
 * The timer that aborts long-running transactions if a transaction timeout
 * has been specified, was not cancelled when preparing a read-only
 * transaction. Since read-only transactions are implicitly committed when
 * they are prepared, this meant that the timer would try to abort an
 * already completed transaction. In addition to printing a confusing
 * message in db.log about the transaction being rolled back, when it
 * actually had been committed, this could also make the timer roll back
 * the wrong transaction, if a new transaction with the same Xid was
 * started later.
 * </p>
 *
 * <p>
 * This test case exposes the bug by running a read-only transaction with
 * a timeout and preparing it, and then starting a new transaction with the
 * same Xid and no timeout. The bug would cause the second transaction to
 * time out.
 * </p>
 */
public void testDerby5562ReadOnlyTimeout()
        throws InterruptedException, SQLException, XAException {
    XADataSource xads = J2EEDataSource.getXADataSource();
    XAConnection xac = xads.getXAConnection();
    XAResource xar = xac.getXAResource();

    Xid xid = createXid(55, 62);

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

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

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

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

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

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

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

    xac.close();
}
 
Example 16
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 17
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 18
Source File: MultipleXidTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Publish two messages with the same publisher inside two separate transactions
 * <p>
 * publish messages within two separate transactions
 * commit the second transaction
 * receive the second message published
 * commit the first transaction
 * receive the first message published
 *
 * @throws XPathExpressionException Error on reading AMQP port
 * @throws NamingException          Throws when Initial context lookup failed
 * @throws JMSException             Exception related to JMS
 * @throws XAException              Throws when error occurred in XA transaction
 */
@Test(groups = {"wso2.mb", "dtx"})
public void PublishWithMultipleXidTestCase() throws XPathExpressionException, NamingException,
                                                    JMSException, XAException {

    String queueName = "PublishWithMultipleXidTestCase";
    String xid1Message = "PublishWithMultipleXidTestCase-Msg-1";
    String xid2Message = "PublishWithMultipleXidTestCase-Msg-2";

    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 xid1 = new TestXidImpl(100, new byte[]{0x01}, new byte[]{0x05});
    Xid xid2 = new TestXidImpl(100, new byte[]{0x01}, new byte[]{0x06});

    xaResource.start(xid1, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage(xid1Message));
    xaResource.end(xid1, XAResource.TMSUCCESS);

    xaResource.start(xid2, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage(xid2Message));
    xaResource.end(xid2, XAResource.TMSUCCESS);

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

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

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

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

    xaResource.commit(xid1, false);
    JMSTextMessage message2 = (JMSTextMessage) consumer.receive(30000);

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

    session.close();
    xaConnection.close();
}
 
Example 19
Source File: ActiveMQXAConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void testReadonlyNoLeak() throws Exception {
   final String brokerName = "readOnlyNoLeak";
   BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName));
   broker.setPersistent(false);
   broker.start();
   ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getConnectUri() + ")");
   cf1.setStatsEnabled(true);
   ActiveMQXAConnection xaConnection = (ActiveMQXAConnection) cf1.createConnection();
   xaConnection.start();
   XASession session = xaConnection.createXASession();
   XAResource resource = session.getXAResource();
   Xid tid = createXid();
   resource.start(tid, XAResource.TMNOFLAGS);
   session.close();
   resource.end(tid, XAResource.TMSUCCESS);
   resource.commit(tid, true);

   //not apply to artemis
   //assertTransactionGoneFromBroker(tid);
   //assertTransactionGoneFromConnection(brokerName, xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid);
   assertSessionGone(xaConnection, session);
   assertTransactionGoneFromFailoverState(xaConnection, tid);

   // two phase
   session = xaConnection.createXASession();
   resource = session.getXAResource();
   tid = createXid();
   resource.start(tid, XAResource.TMNOFLAGS);
   session.close();
   resource.end(tid, XAResource.TMSUCCESS);
   assertEquals(XAResource.XA_RDONLY, resource.prepare(tid));

   // no need for a commit on read only
   //assertTransactionGoneFromBroker(tid);
   //assertTransactionGoneFromConnection(brokerName, xaConnection.getClientID(), xaConnection.getConnectionInfo().getConnectionId(), tid);
   assertSessionGone(xaConnection, session);
   assertTransactionGoneFromFailoverState(xaConnection, tid);

   xaConnection.close();
   broker.stop();

}
 
Example 20
Source File: JdbcXaTest.java    From hazelcast-jet-contrib with Apache License 2.0 4 votes vote down vote up
/** */
public static void main(String[] args) throws Exception {
    // replace this line with a factory for your database, for example:
    //    PGXADataSource factory = new PGXADataSource();
    XADataSource factory = getXADataSource();

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

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

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

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

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

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

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

    // check that record is inserted
    stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select a from foo");
    if (!rs.next() || rs.getInt(1) != 1) {
        System.err.println("Failure: record missing or has wrong value");
    } else {
        System.out.println("Success!");
    }
}