Java Code Examples for javax.sql.XAConnection#close()

The following examples show how to use javax.sql.XAConnection#close() . 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: 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 2
Source File: J2EEDataSourceTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Test that connections retrieved from {@code XADataSource} that are not
 * part of a global XA transaction, behave as expected when {@code close()}
 * is called and the transaction is active.
 */
public void testCloseActiveConnection_XA_local() throws SQLException {
    XADataSource ds = J2EEDataSource.getXADataSource();
    XAConnection xa = ds.getXAConnection();
    testCloseActiveConnection(xa.getConnection(), true, false);
    Connection c = xa.getConnection();
    c.setAutoCommit(false);
    testCloseActiveConnection(c, false, false);
    xa.close();
}
 
Example 3
Source File: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Further test case prompted by DERBY-1016. Tests that XAER_NOTA is thrown
 * if no transaction exists.
 */
public void testForgetExceptionDerby1016NOTA() throws XAException, SQLException {      
    XADataSource xads = J2EEDataSource.getXADataSource();
    J2EEDataSource.setBeanProperty(xads, "databaseName", "wombat");
    
    XAConnection xaconn = xads.getXAConnection();
    XAResource xar = xaconn.getXAResource();
    Xid xid = createXid(93,18);
    xar.start(xid, XAResource.TMNOFLAGS);
    Connection conn = xaconn.getConnection();
    Statement s = conn.createStatement();
    s.executeUpdate("CREATE TABLE Derby1016 (I INT)");
    xar.end(xid, XAResource.TMSUCCESS);
    xar.prepare(xid);
    xar.commit(xid, false);
    try {
        // since the transaction was committed, it should no longer exist
        // thus, forget should now throw an XAER_NOTA
        xar.forget(xid);
        fail("FAIL: able to forget committed XA-Transaction");
    } catch (XAException XAeForget) {
        assertEquals("FAIL: Got unexpected exception "
                      + XAeForget.getMessage()   + " errorCode: " 
                      + XAeForget.errorCode  + "  calling forget on a committed transaction",
                    XAException.XAER_NOTA, XAeForget.errorCode);
    } finally {
        s.executeUpdate("DROP TABLE Derby1016");
        conn.commit();
        s.close();
        conn.close(); 
        xaconn.close();
    }
}
 
Example 4
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testClosedXADSConnection() throws SQLException, Exception {
    // verify that outstanding updates from a closed connection, obtained
    // from an XADataSource, are not committed, but rolled back.
    XADataSource dsx = J2EEDataSource.getXADataSource();
    XAConnection xac = dsx.getXAConnection();
    Connection c1 = xac.getConnection();
    Statement s = c1.createStatement();

    c1.setAutoCommit(false);

    // this update should be rolled back
    s.executeUpdate("insert into intTable values(2)");
    
    c1 = xac.getConnection();

    ResultSet rs = c1.createStatement().executeQuery(
       "select count(*) from intTable");
    rs.next();

    assertEquals(0, rs.getInt(1));

    rs.close();
    c1.close();
    xac.close();
    xac = null;

    PoolReset("XADataSource", dsx.getXAConnection());
}
 
Example 5
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 6
Source File: XaTest.java    From jTDS with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Test to demonstrate the XA_COMMIT function.
 *
 * @throws Exception if an error condition occurs
 */
public void testXaCommit() throws Exception {
    Connection con2 = null;
    XAConnection xaCon = null;

    try {
        dropTable("jTDS_XATEST");

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

        XADataSource xaDS = getDataSource();
        XAResource xaRes;
        Xid  xid;
        xaCon = xaDS.getXAConnection();
        xaRes = xaCon.getXAResource();
        con2 = xaCon.getConnection();
        stmt = con2.createStatement();
        xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});

        xaRes.start(xid, XAResource.TMNOFLAGS);
        stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
        xaRes.end(xid, XAResource.TMSUCCESS);
        int ret = xaRes.prepare(xid);
        if (ret == XAResource.XA_OK) {
            xaRes.commit(xid, false);
        }
        stmt.close();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
        assertNotNull(rs);
        assertTrue(rs.next());
        stmt.close();
    } finally {
        if (con2 != null) {
            con2.close();
        }
        if (xaCon != null) {
            xaCon.close();
        }

        dropTable("jTDS_XATEST");
    }
}
 
Example 7
Source File: XATransactionTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/** Tests whether it is possible to reconstruct the original Xid value
  * correctly from SYSCS_DIAG.TRANSACTION_TABLE. */
public void testGlobalXIDinTransactionTable() throws Exception {
    Statement stm = getConnection().createStatement();
    stm.execute("create table XATT2 (i int, text char(10))");

    XADataSource xaDataSource = J2EEDataSource.getXADataSource();
    XAConnection xaConn = xaDataSource.getXAConnection();
    XAResource xaRes = xaConn.getXAResource();
    Connection conn = xaConn.getConnection();

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

    // get the stuff required to execute the global transaction
    xaConn = xaDataSource.getXAConnection();
    xaRes = xaConn.getXAResource();
    conn = xaConn.getConnection();

    // start the transaction with that xid
    xaRes.start(xid, XAResource.TMNOFLAGS);

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

    // end the wotk on the transaction branch
    xaRes.end(xid, XAResource.TMSUCCESS);

    ResultSet rs = null;
    stm = null;

    try {
        // check the output of the global xid in 
        // syscs_diag.transaction_table
        stm = getConnection().createStatement();

        String query = "select global_xid from syscs_diag.transaction_table"
                     + " where global_xid is not null";

        // execute the query to obtain the xid of the global transaction
        rs = stm.executeQuery(query);

        // there should be at least one globaltransaction in progress
        assertTrue(rs.next());

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

        // there should be at most one global transaction in progress
        assertFalse(rs.next());

    } catch (Exception ex) {
        try {
            // close all the stuff
            if (rs != null)
                rs.close();
            if (stm != null)
                stm.close();

            // rollback the global transaction
            xaRes.rollback(xid);
            // close the connection
            xaConn.close();
        } catch (Exception e) {
            // ignore the exception because it
            // would hide the original exception
        }
        // throw the stuff further
        throw ex;
    }

    // close all the stuff
    rs.close();
    stm.close();

    // rollback the global transaction
    xaRes.rollback(xid);

    // close the connection
    xaConn.close();
}
 
Example 8
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 9
Source File: xaHelper.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void XADataSourceStatement(ij parser, Token dbname, Token shutdown,
								String create)
	 throws SQLException
{
	try
	{
		  currentXADataSource = (XADataSource) getXADataSource();

		  databaseName = parser.stringValue(dbname.image);
		  
		  if (isJCC || isNetClient)
		  {
		  	String hostName = System.getProperty("hostName");
		  	if ((hostName != null ) && (!hostName.equals("localhost")))
			{			
		  		xaHelper.setDataSourceProperty(currentXADataSource,
										 "ServerName", hostName);
			}
		  	else
			{			
		  		xaHelper.setDataSourceProperty(currentXADataSource,
						 "ServerName", "localhost");
			}
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "portNumber", 1527);
		  
		  String user;
		  String password;
		  user = "APP";
		  password = "APP";
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "user", user);
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "password", password);
		  //xaHelper.setDataSourceProperty(currentXADataSource,
		  //"traceFile", "trace.out." + framework);
		  }
		  if (isJCC)
		  {
			  xaHelper.setDataSourceProperty(currentXADataSource,
											 "driverType", 4);

			  xaHelper.setDataSourceProperty(currentXADataSource, 
											 "retrieveMessagesFromServerOnGetMessage", true);
		  }
		  xaHelper.setDataSourceProperty(currentXADataSource, "databaseName", databaseName);

		if (shutdown != null && shutdown.toString().toLowerCase(Locale.ENGLISH).equals("shutdown"))
		{	
			if (isJCC || isNetClient)
				xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";shutdown=true");
			else
				xaHelper.setDataSourceProperty(currentXADataSource, "shutdownDatabase", "shutdown");

			// do a getXAConnection to shut it down */
			currentXADataSource.getXAConnection().getConnection();
			currentXADataSource = null;
			currentXAConnection = null;
		}
		else if (create != null && create.toLowerCase(java.util.Locale.ENGLISH).equals("create"))
		{
			if (isJCC || isNetClient)
				xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";create=true");
			else
				xaHelper.setDataSourceProperty(currentXADataSource,
											   "createDatabase", "create");

			/* do a getXAConnection to create it */
			XAConnection conn = currentXADataSource.getXAConnection();
			conn.close();
			
			xaHelper.setDataSourceProperty(currentXADataSource, "createDatabase", null);
		}
	}
	catch (Throwable t)
	{
		handleException(t);
	}	
}
 
Example 10
Source File: J2EEDataSourceTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
public void testAutoCommitOnXAResourceStart() throws SQLException, XAException {

        XADataSource dsx = J2EEDataSource.getXADataSource();
        XAConnection xac4 = dsx.getXAConnection();
        Xid xid4a= null;

        // We get an XAID_DUP error from networkserver when attempting
        // the XAResource.start below if we use the same xid.
        // Possibly because we're in the same jvm.
        // When the test is run with clientserverSuite, rather than default,
        // this wasn't needed, so just create a different id for client
        if (usingEmbedded())
            xid4a = new cdsXid(4, (byte) 23, (byte) 76);
        else if (usingDerbyNetClient())
            xid4a = new cdsXid(5, (byte) 23, (byte) 76);

        Connection conn4 = xac4.getConnection();
        assertTrue(conn4.getAutoCommit());

        Statement s4 = conn4.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
        ResultSet rs4 = s4.executeQuery("select i from autocommitxastart");
        rs4.next();
        assertEquals(1, rs4.getInt(1));
        rs4.next();
        assertEquals(2, rs4.getInt(1));

        // XAResource().start should commit the transaction
        xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
        xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS);

        try {
            rs4.next();
            fail ("expected an exception indicating resultset is closed.");
        } catch (SQLException sqle) {
            // Embedded gets 08003. No current connection (DERBY-2620)        	
            if (usingDerbyNetClient())
                assertSQLState("XCL16",sqle);
        }

        conn4.setAutoCommit(false);
        assertFalse(conn4.getAutoCommit());

        rs4 = s4.executeQuery("select i from autocommitxastart");
        rs4.next();
        assertEquals(1, rs4.getInt(1));
        rs4.next();
        assertEquals(2, rs4.getInt(1));

        // Get a new xid to begin another transaction.
        if (usingEmbedded())
            xid4a = new cdsXid(4, (byte) 93, (byte) 103);
        else if (usingDerbyNetClient())
            xid4a = new cdsXid(5, (byte) 93, (byte) 103);

        try {
            xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
        } catch (XAException xae) {
            if (usingEmbedded())
                assertNull(xae.getMessage());
            else if (usingDerbyNetClient())
            {
                // This should give XAER_OUTSIDE exception because
                // the resource manager is busy in the local transaction
                assertTrue(xae.getMessage().indexOf("XAER_OUTSIDE") >=0 );
            }
            assertEquals(-9, xae.errorCode);
        }

        rs4.next();
        assertEquals(3, rs4.getInt(1));
        rs4.close();

        conn4.rollback();
        conn4.close();
        xac4.close();
    }
 
Example 11
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 12
Source File: xaHelper.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
public void XADataSourceStatement(ij parser, Token dbname, Token shutdown,
								String create)
	 throws SQLException
{
	try
	{
		  currentXADataSource = (XADataSource) getXADataSource();

		  databaseName = parser.stringValue(dbname.image);
		  
		  if (isJCC || isNetClient)
		  {
		  	String hostName = System.getProperty("hostName");
		  	if ((hostName != null ) && (!hostName.equals("localhost")))
			{			
		  		xaHelper.setDataSourceProperty(currentXADataSource,
										 "ServerName", hostName);
			}
		  	else
			{			
		  		xaHelper.setDataSourceProperty(currentXADataSource,
						 "ServerName", "localhost");
			}
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "portNumber", 1527);
		  
		  String user;
		  String password;
		  user = "SPLICE";
		  password = "SPLICE";
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "user", user);
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "password", password);
		  //xaHelper.setDataSourceProperty(currentXADataSource,
		  //"traceFile", "trace.out." + framework);
		  }
		  if (isJCC)
		  {
			  xaHelper.setDataSourceProperty(currentXADataSource,
											 "driverType", 4);

			  xaHelper.setDataSourceProperty(currentXADataSource, 
											 "retrieveMessagesFromServerOnGetMessage", true);
		  }
		  xaHelper.setDataSourceProperty(currentXADataSource, "databaseName", databaseName);

		if (shutdown != null && shutdown.toString().toLowerCase(Locale.ENGLISH).equals("shutdown"))
		{	
			if (isJCC || isNetClient)
				xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";shutdown=true");
			else
				xaHelper.setDataSourceProperty(currentXADataSource, "shutdownDatabase", "shutdown");

			// do a getXAConnection to shut it down */
			currentXADataSource.getXAConnection().getConnection();
			currentXADataSource = null;
			currentXAConnection = null;
		}
		else if (create != null && create.toLowerCase(java.util.Locale.ENGLISH).equals("create"))
		{
			if (isJCC || isNetClient)
				xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";create=true");
			else
				xaHelper.setDataSourceProperty(currentXADataSource,
											   "createDatabase", "create");

			/* do a getXAConnection to create it */
			XAConnection conn = currentXADataSource.getXAConnection();
			conn.close();
			
			xaHelper.setDataSourceProperty(currentXADataSource, "createDatabase", null);
		}
	}
	catch (Throwable t)
	{
		handleException(t);
	}	
}
 
Example 13
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testAutoCommitOnXAResourceStart() throws SQLException, XAException {

        XADataSource dsx = J2EEDataSource.getXADataSource();
        XAConnection xac4 = dsx.getXAConnection();
        Xid xid4a= null;

        // We get an XAID_DUP error from networkserver when attempting
        // the XAResource.start below if we use the same xid.
        // Possibly because we're in the same jvm.
        // When the test is run with clientserverSuite, rather than default,
        // this wasn't needed, so just create a different id for client
        if (usingEmbedded())
            xid4a = new cdsXid(4, (byte) 23, (byte) 76);
        else if (usingDerbyNetClient())
            xid4a = new cdsXid(5, (byte) 23, (byte) 76);
            
        Connection conn4 = xac4.getConnection();
        assertTrue(conn4.getAutoCommit());

        Statement s4 = conn4.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
        ResultSet rs4 = s4.executeQuery("select i from autocommitxastart");
        rs4.next();
        assertEquals(1, rs4.getInt(1));
        rs4.next();
        assertEquals(2, rs4.getInt(1));

        // XAResource().start should commit the transaction
        xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
        xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS);

        try {
            rs4.next();
            fail ("expected an exception indicating resultset is closed.");
        } catch (SQLException sqle) {
            // Embedded gets 08003. No current connection (DERBY-2620)        	
        	if (usingDerbyNetClient())
        		assertSQLState("XCL16",sqle);
        }

        conn4.setAutoCommit(false);
        assertFalse(conn4.getAutoCommit());

        rs4 = s4.executeQuery("select i from autocommitxastart");
        rs4.next();
        assertEquals(1, rs4.getInt(1));
        rs4.next();
        assertEquals(2, rs4.getInt(1));
        
         // Get a new xid to begin another transaction. 
        if (usingEmbedded())
            xid4a = new cdsXid(4, (byte) 93, (byte) 103);
        else if (usingDerbyNetClient())
            xid4a = new cdsXid(5, (byte) 93, (byte) 103);

        try {
            xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
        } catch (XAException xae) {
            if (usingEmbedded())
                assertNull(xae.getMessage());
            else if (usingDerbyNetClient())
            {
                // This should give XAER_OUTSIDE exception because
                // the resource manager is busy in the local transaction
                assertTrue(xae.getMessage().indexOf("XAER_OUTSIDE") >=0 );
            }
            assertEquals(-9, xae.errorCode);
        }
        
        rs4.next();
        assertEquals(3, rs4.getInt(1));
        rs4.close();

        conn4.rollback();
        conn4.close();
        xac4.close();
    }
 
Example 14
Source File: XATransactionTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void testGlobalXIDinTransactionTable() throws Exception {
    Statement stm = getConnection().createStatement();
    stm.execute("create table XATT2 (i int, text char(10))");

    XADataSource xaDataSource = J2EEDataSource.getXADataSource();
    XAConnection xaConn = xaDataSource.getXAConnection();
    XAResource xaRes = xaConn.getXAResource();
    Connection conn = xaConn.getConnection();

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

    // get the stuff required to execute the global transaction
    xaConn = xaDataSource.getXAConnection();
    xaRes = xaConn.getXAResource();
    conn = xaConn.getConnection();

    // start the transaction with that xid
    xaRes.start(xid, XAResource.TMNOFLAGS);

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

    // end the wotk on the transaction branch
    xaRes.end(xid, XAResource.TMSUCCESS);

    ResultSet rs = null;
    stm = null;

    try {

        // check the output of the global xid in syscs_diag.transaction_table
        stm = getConnection().createStatement();

        String query = "select global_xid from syscs_diag.transaction_table"
                     + " where global_xid is not null";

        // execute the query to obtain the xid of the global transaction
        rs = stm.executeQuery(query);

        // there should be at least one globaltransaction in progress
        Assert.assertTrue(rs.next());

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

        // there should be at most one global transaction in progress
        Assert.assertFalse(rs.next());

    } catch (Exception ex) {
        try {
            // close all the stuff
            if (rs != null)
                rs.close();
            if (stm != null)
                stm.close();

            // rollback the global transaction
            xaRes.rollback(xid);
            // close the connection
            xaConn.close();
        } catch (Exception e) {
            // ignore the exception because it
            // would hide the original exception
        }
        // throw the stuff further
        throw ex;
    }

    // close all the stuff
    rs.close();
    stm.close();

    // rollback the global transaction
    xaRes.rollback(xid);

    // close the connection
    xaConn.close();
}
 
Example 15
Source File: xaHelper.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void XADataSourceStatement(ij parser, Token dbname, Token shutdown,
								String create)
	 throws SQLException
{
	try
	{
		  currentXADataSource = (XADataSource) getXADataSource();

		  databaseName = parser.stringValue(dbname.image);
		  
		  if (isJCC || isNetClient)
		  {
		  	String hostName = System.getProperty("hostName");
		  	if ((hostName != null ) && (!hostName.equals("localhost")))
			{			
		  		xaHelper.setDataSourceProperty(currentXADataSource,
										 "ServerName", hostName);
			}
		  	else
			{			
		  		xaHelper.setDataSourceProperty(currentXADataSource,
						 "ServerName", "localhost");
			}
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "portNumber", 1527);
		  
		  String user;
		  String password;
		  user = "APP";
		  password = "APP";
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "user", user);
		  xaHelper.setDataSourceProperty(currentXADataSource,
										 "password", password);
		  //xaHelper.setDataSourceProperty(currentXADataSource,
		  //"traceFile", "trace.out." + framework);
		  }
		  if (isJCC)
		  {
			  xaHelper.setDataSourceProperty(currentXADataSource,
											 "driverType", 4);

			  xaHelper.setDataSourceProperty(currentXADataSource, 
											 "retrieveMessagesFromServerOnGetMessage", true);
		  }
		  xaHelper.setDataSourceProperty(currentXADataSource, "databaseName", databaseName);

		if (shutdown != null && shutdown.toString().toLowerCase(Locale.ENGLISH).equals("shutdown"))
		{	
			if (isJCC || isNetClient)
				xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";shutdown=true");
			else
				xaHelper.setDataSourceProperty(currentXADataSource, "shutdownDatabase", "shutdown");

			// do a getXAConnection to shut it down */
			currentXADataSource.getXAConnection().getConnection();
			currentXADataSource = null;
			currentXAConnection = null;
		}
		else if (create != null && create.toLowerCase(java.util.Locale.ENGLISH).equals("create"))
		{
			if (isJCC || isNetClient)
				xaHelper.setDataSourceProperty(currentXADataSource,"databaseName", databaseName + ";create=true");
			else
				xaHelper.setDataSourceProperty(currentXADataSource,
											   "createDatabase", "create");

			/* do a getXAConnection to create it */
			XAConnection conn = currentXADataSource.getXAConnection();
			conn.close();
			
			xaHelper.setDataSourceProperty(currentXADataSource, "createDatabase", null);
		}
	}
	catch (Throwable t)
	{
		handleException(t);
	}	
}
 
Example 16
Source File: DataSourceRegressionTest.java    From Komondor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Tests fix for BUG#72890 - Java jdbc driver returns incorrect return code when it's part of XA transaction
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug72890() throws Exception {
    MysqlXADataSource myDs = new MysqlXADataSource();
    myDs.setUrl(BaseTestCase.dbUrl);

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

        final XAConnection xaConn = myDs.getXAConnection();
        final XAResource xaRes = xaConn.getXAResource();
        final Connection dbConn = xaConn.getConnection();
        final long connId = ((MySQLConnection) ((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 17
Source File: XaTest.java    From jTDS with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Demonstrate interleaving local transactions and distributed
 * transactions.
 *
 * @throws Exception if an error condition occurs
 */
public void testLocalTran() throws Exception {
    if ("true".equalsIgnoreCase(props.getProperty(Messages.get(Driver.XAEMULATION)))) {
        // Emulation mode does not support suspending transactions.
        return;
    }
    Connection con2 = null;
    XAConnection xaCon = null;

    try {
        dropTable("jTDS_XATEST");
        dropTable("jTDS_XATEST2");

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

        XADataSource xaDS = getDataSource();
        XAResource xaRes;
        Xid  xid;
        xaCon = xaDS.getXAConnection();
        xaRes = xaCon.getXAResource();
        con2 = xaCon.getConnection();
        stmt = con2.createStatement();
        xid = new JtdsXid(new byte[]{0x01}, new byte[]{0x02});

        xaRes.start(xid, XAResource.TMNOFLAGS);
        stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (1, 'TEST LINE')");
        xaRes.end(xid, XAResource.TMSUSPEND);
        stmt.executeUpdate("INSERT INTO jTDS_XATEST2 VALUES (1, 'TEST LINE')");
        xaRes.start(xid, XAResource.TMRESUME);
        stmt.executeUpdate("INSERT INTO jTDS_XATEST VALUES (2, 'TEST LINE 2')");
        xaRes.end(xid, XAResource.TMSUCCESS);
        xaRes.rollback(xid);
        stmt.close();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST");
        assertNotNull(rs);
        assertFalse(rs.next());
        rs = stmt.executeQuery("SELECT * FROM jTDS_XATEST2");
        assertNotNull(rs);
        assertTrue(rs.next());
        stmt.close();
    } finally {
        if (con2 != null) {
            con2.close();
        }
        if (xaCon != null) {
            xaCon.close();
        }

        dropTable("jTDS_XATEST");
        dropTable("jTDS_XATEST2");
    }
}
 
Example 18
Source File: XATest.java    From r-course with MIT License 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 19
Source File: J2EEDataSourceTest.java    From spliceengine with GNU Affero General Public License v3.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 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();

}