Java Code Examples for javax.transaction.xa.Xid#getGlobalTransactionId()

The following examples show how to use javax.transaction.xa.Xid#getGlobalTransactionId() . 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: MysqlXAConnection.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void appendXid(StringBuilder builder, Xid xid) {
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] btrid = xid.getBranchQualifier();

    if (gtrid != null) {
        StringUtils.appendAsHex(builder, gtrid);
    }

    builder.append(',');
    if (btrid != null) {
        StringUtils.appendAsHex(builder, btrid);
    }

    builder.append(',');
    StringUtils.appendAsHex(builder, xid.getFormatId());
}
 
Example 2
Source File: MysqlXAConnection.java    From r-course with MIT License 6 votes vote down vote up
private static void appendXid(StringBuilder builder, Xid xid) {
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] btrid = xid.getBranchQualifier();

    if (gtrid != null) {
        StringUtils.appendAsHex(builder, gtrid);
    }

    builder.append(',');
    if (btrid != null) {
        StringUtils.appendAsHex(builder, btrid);
    }

    builder.append(',');
    StringUtils.appendAsHex(builder, xid.getFormatId());
}
 
Example 3
Source File: NetXAConnectionRequest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
void writeXID(int codepoint, Xid xid) throws SqlException {
    int len = 0;
    int formatId = xid.getFormatId();
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] bqual = xid.getBranchQualifier();

    markLengthBytes(codepoint);

    len = 4;                    // length of formatId
    len += (bqual.length + 4);  // bqual length
    len += (gtrid.length + 4);  // gtrid length

    write4Bytes(formatId);
    write4Bytes(gtrid.length);
    write4Bytes(bqual.length);

    writeBytes(gtrid);
    writeBytes(bqual);

    updateLengthBytes();

}
 
Example 4
Source File: DummyXid.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final Object other) {
   if (this == other) {
      return true;
   }
   if (!(other instanceof Xid)) {
      return false;
   }
   Xid xother = (Xid) other;
   if (xother.getFormatId() != formatId) {
      return false;
   }
   if (xother.getBranchQualifier().length != branchQualifier.length) {
      return false;
   }
   if (xother.getGlobalTransactionId().length != globalTransactionId.length) {
      return false;
   }
   for (int i = 0; i < branchQualifier.length; i++) {
      byte[] otherBQ = xother.getBranchQualifier();
      if (branchQualifier[i] != otherBQ[i]) {
         return false;
      }
   }
   for (int i = 0; i < globalTransactionId.length; i++) {
      byte[] otherGtx = xother.getGlobalTransactionId();
      if (globalTransactionId[i] != otherGtx[i]) {
         return false;
      }
   }
   return true;
}
 
Example 5
Source File: FBXid.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a new instance copying an existing one.
 */
public FBXid(Xid xid) {
    formatId = xid.getFormatId();
    globalId = xid.getGlobalTransactionId();
    branchId = xid.getBranchQualifier();
    firebirdTransactionId = 0;
}
 
Example 6
Source File: DummyXid.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static byte[] toByteArray(final Xid xid) {
   byte[] branchQualifier = xid.getBranchQualifier();
   byte[] globalTransactionId = xid.getGlobalTransactionId();
   int formatId = xid.getFormatId();

   byte[] hashBytes = new byte[branchQualifier.length + globalTransactionId.length + 4];
   System.arraycopy(branchQualifier, 0, hashBytes, 0, branchQualifier.length);
   System.arraycopy(globalTransactionId, 0, hashBytes, branchQualifier.length, globalTransactionId.length);
   byte[] intBytes = new byte[4];
   for (int i = 0; i < 4; i++) {
      intBytes[i] = (byte) ((formatId >> i * 8) % 0xFF);
   }
   System.arraycopy(intBytes, 0, hashBytes, branchQualifier.length + globalTransactionId.length, 4);
   return hashBytes;
}
 
Example 7
Source File: DummyXid.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final Object other) {
   if (this == other) {
      return true;
   }
   if (!(other instanceof Xid)) {
      return false;
   }
   Xid xother = (Xid) other;
   if (xother.getFormatId() != formatId) {
      return false;
   }
   if (xother.getBranchQualifier().length != branchQualifier.length) {
      return false;
   }
   if (xother.getGlobalTransactionId().length != globalTransactionId.length) {
      return false;
   }
   for (int i = 0; i < branchQualifier.length; i++) {
      byte[] otherBQ = xother.getBranchQualifier();
      if (branchQualifier[i] != otherBQ[i]) {
         return false;
      }
   }
   for (int i = 0; i < globalTransactionId.length; i++) {
      byte[] otherGtx = xother.getGlobalTransactionId();
      if (globalTransactionId[i] != otherGtx[i]) {
         return false;
      }
   }
   return true;
}
 
Example 8
Source File: XidImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final Object other) {
   if (this == other) {
      return true;
   }
   if (!(other instanceof Xid)) {
      return false;
   }
   Xid xother = (Xid) other;
   if (xother.getFormatId() != formatId) {
      return false;
   }
   if (xother.getBranchQualifier().length != branchQualifier.length) {
      return false;
   }
   if (xother.getGlobalTransactionId().length != globalTransactionId.length) {
      return false;
   }
   for (int i = 0; i < branchQualifier.length; i++) {
      byte[] otherBQ = xother.getBranchQualifier();
      if (branchQualifier[i] != otherBQ[i]) {
         return false;
      }
   }
   for (int i = 0; i < globalTransactionId.length; i++) {
      byte[] otherGtx = xother.getGlobalTransactionId();
      if (globalTransactionId[i] != otherGtx[i]) {
         return false;
      }
   }
   return true;
}
 
Example 9
Source File: SpringBootCoordinator.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String serialize(Serializable arg) throws IOException {
	if (Xid.class.isInstance(arg)) {
		Xid xid = (Xid) arg;
		byte[] globalTransactionId = xid.getGlobalTransactionId();
		return ByteUtils.byteArrayToString(globalTransactionId);
	} else if (Integer.class.isInstance(arg) || Integer.TYPE.isInstance(arg)) {
		return String.valueOf(arg);
	} else if (Boolean.class.isInstance(arg) || Boolean.TYPE.isInstance(arg)) {
		return String.valueOf(arg);
	} else {
		byte[] byteArray = SerializeUtils.serializeObject(arg);
		return ByteUtils.byteArrayToString(byteArray);
	}
}
 
Example 10
Source File: RedisHelper.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
public static byte[] getRedisKey(String keyPrefix, Xid xid) {

        byte[] prefix = keyPrefix.getBytes();
        byte[] globalTransactionId = xid.getGlobalTransactionId();
        byte[] branchQualifier = xid.getBranchQualifier();

        byte[] key = new byte[prefix.length + globalTransactionId.length + branchQualifier.length];
        System.arraycopy(prefix, 0, key, 0, prefix.length);
        System.arraycopy(globalTransactionId, 0, key, prefix.length, globalTransactionId.length);
        System.arraycopy(branchQualifier, 0, key, prefix.length + globalTransactionId.length, branchQualifier.length);
        return key;
    }
 
Example 11
Source File: NetXAResource.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static boolean xidsEqual(Xid xid1, Xid xid2) { // determine if the 2 xids contain the same values even if not same object
    // comapre the format ids
    if (xid1.getFormatId() != xid2.getFormatId()) {
        return false; // format ids are not the same
    }

    // compare the global transaction ids
    int xid1Length = xid1.getGlobalTransactionId().length;
    if (xid1Length != xid2.getGlobalTransactionId().length) {
        return false; // length of the global trans ids are not the same
    }
    byte[] xid1Bytes = xid1.getGlobalTransactionId();
    byte[] xid2Bytes = xid2.getGlobalTransactionId();
    int i;
    for (i = 0; i < xid1Length; ++i) { // check all bytes are the same
        if (xid1Bytes[i] != xid2Bytes[i]) {
            return false; // bytes in the global trans ids are not the same
        }
    }

    // compare the branch qualifiers
    xid1Length = xid1.getBranchQualifier().length;
    if (xid1Length != xid2.getBranchQualifier().length) {
        return false; // length of the global trans ids are not the same
    }
    xid1Bytes = xid1.getBranchQualifier();
    xid2Bytes = xid2.getBranchQualifier();
    for (i = 0; i < xid1Length; ++i) { // check all bytes are the same
        if (xid1Bytes[i] != xid2Bytes[i]) {
            return false; // bytes in the global trans ids are not the same
        }
    }

    return true; // all of the fields are the same, xid1 == xid2
}
 
Example 12
Source File: NetXAConnectionRequest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
void writeXID(int codepoint, Xid xid) throws SqlException {
    int len = 0;
    int formatId = xid.getFormatId();
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] bqual = xid.getBranchQualifier();

    markLengthBytes(codepoint);

    len = 4;                    // length of formatId
    len += (bqual.length + 4);  // bqual length
    len += (gtrid.length + 4);  // gtrid length

    write4Bytes(formatId);
    write4Bytes(gtrid.length);
    write4Bytes(bqual.length);

    // Mare sure request buffer has enough space to write this byte array.
    ensureLength(offset_ + gtrid.length);
    System.arraycopy(gtrid, 0, bytes_, offset_, gtrid.length);
    offset_ += gtrid.length;

    ensureLength(offset_ + bqual.length);
    System.arraycopy(bqual, 0, bytes_, offset_, bqual.length);
    offset_ += bqual.length;

    updateLengthBytes();

}
 
Example 13
Source File: XidWrapperImpl.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new XidWrapperImpl instance.
 * @param xid The Xid instances
 * @param pad Should the branch qualifier be padded
 * @param jndiName The JNDI name
 */
public XidWrapperImpl(Xid xid, boolean pad, String jndiName)
{
   this.branchQualifier = pad ? new byte[Xid.MAXBQUALSIZE] : new byte[xid.getBranchQualifier().length];      
   System.arraycopy(xid.getBranchQualifier(), 0, branchQualifier, 0, xid.getBranchQualifier().length);      

   this.globalTransactionId = xid.getGlobalTransactionId();
   this.formatId = xid.getFormatId();
   this.jndiName = jndiName;
}
 
Example 14
Source File: XidWrapperImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new XidWrapperImpl instance.
 * @param xid The Xid instances
 * @param pad Should the branch qualifier be padded
 * @param jndiName The JNDI name
 */
public XidWrapperImpl(Xid xid, boolean pad, String jndiName)
{
   this.branchQualifier = pad ? new byte[Xid.MAXBQUALSIZE] : new byte[xid.getBranchQualifier().length];      
   System.arraycopy(xid.getBranchQualifier(), 0, branchQualifier, 0, xid.getBranchQualifier().length);      

   this.globalTransactionId = xid.getGlobalTransactionId();
   this.formatId = xid.getFormatId();
   this.jndiName = jndiName;
}
 
Example 15
Source File: DtxRecoverPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if recovering transactions return empty set when no prepared transactions are there. Steps are,
 *    1. A distributed sessions is started
 *    2. Before preparing recover and see we get an empty list
 *    3. Go to prepare stage and see if we get one item in the list
 *    4. Rollback and see if we get an empty list
 */
@Test(groups = { "wso2.mb", "dtx" })
public void performDtxRecoverWithPublishTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxRecoverPositiveTestCasePerformDtxRecoverWithPublishTestCase";

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

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

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

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

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

    Xid[] recoveredTransactions = xaResource.recover(XAResource.TMNOFLAGS);
    Assert.assertEquals(recoveredTransactions.length, 0, "Recovered Transaction list length should be 0 since "
            + "we don't have not started any transaction");

    Xid xid = JMSClientHelper.getNewXid();

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

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

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

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

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

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

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

    xaResource.rollback(xid);

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

    session.close();
    xaConnection.close();
}
 
Example 16
Source File: DistributedTransactionTest.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Xid newXid(Xid branchFrom) {
  return new MariaDbXid(
      1, branchFrom.getGlobalTransactionId(), UUID.randomUUID().toString().getBytes());
}
 
Example 17
Source File: CompensableArchiveDeserializer.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
public byte[] serialize(TransactionXid xid, Object obj) {
	CompensableArchive archive = (CompensableArchive) obj;

	CompensableInvocation compensable = archive.getCompensable();
	byte[] byteArray = new byte[0];
	try {
		byteArray = SerializeUtils.serializeObject(compensable);
	} catch (Exception ex) {
		if (compensable == null) {
			logger.error("Error occurred while serializing compensable: {}", compensable, ex);
		} else {
			logger.error("Error occurred while serializing args: {}", compensable.getArgs(), ex);
		}
	}

	String transactionResourceKey = archive.getTransactionResourceKey();
	String compensableResourceKey = archive.getCompensableResourceKey();

	byte[] transactionResourceKeyByteArray = transactionResourceKey == null ? new byte[0]
			: transactionResourceKey.getBytes();
	byte[] compensableResourceKeyByteArray = compensableResourceKey == null ? new byte[0]
			: compensableResourceKey.getBytes();

	byte[] resultArray = new byte[XidFactory.GLOBAL_TRANSACTION_LENGTH + XidFactory.BRANCH_QUALIFIER_LENGTH
			+ LENGTH_OF_XID * 2 + 1 //
			+ 2 + transactionResourceKeyByteArray.length //
			+ 2 + compensableResourceKeyByteArray.length //
			+ byteArray.length];

	Xid identifier = archive.getIdentifier();
	byte[] globalByteArray = identifier.getGlobalTransactionId();
	byte[] branchByteArray = identifier.getBranchQualifier();
	System.arraycopy(globalByteArray, 0, resultArray, 0, XidFactory.GLOBAL_TRANSACTION_LENGTH);
	System.arraycopy(branchByteArray, 0, resultArray, XidFactory.GLOBAL_TRANSACTION_LENGTH,
			XidFactory.BRANCH_QUALIFIER_LENGTH);

	Xid transactionXid = archive.getTransactionXid();
	Xid compensableXid = archive.getCompensableXid();
	byte[] transactionGlobalTransactionId = null;
	byte[] transactionBranchQualifier = null;
	byte[] compensableGlobalTransactionId = null;
	byte[] compensableBranchQualifier = null;
	if (transactionXid == null) {
		transactionGlobalTransactionId = new byte[XidFactory.GLOBAL_TRANSACTION_LENGTH];
		transactionBranchQualifier = new byte[XidFactory.BRANCH_QUALIFIER_LENGTH];
	} else {
		transactionGlobalTransactionId = transactionXid.getGlobalTransactionId();
		transactionBranchQualifier = transactionXid.getBranchQualifier();
	}
	System.arraycopy(transactionGlobalTransactionId, 0, resultArray, LENGTH_OF_XID, XidFactory.GLOBAL_TRANSACTION_LENGTH);
	System.arraycopy(transactionBranchQualifier, 0, resultArray, LENGTH_OF_XID + XidFactory.GLOBAL_TRANSACTION_LENGTH,
			XidFactory.BRANCH_QUALIFIER_LENGTH);

	if (compensableXid == null) {
		compensableGlobalTransactionId = new byte[XidFactory.GLOBAL_TRANSACTION_LENGTH];
		compensableBranchQualifier = new byte[XidFactory.BRANCH_QUALIFIER_LENGTH];
	} else {
		compensableGlobalTransactionId = compensableXid.getGlobalTransactionId();
		compensableBranchQualifier = compensableXid.getBranchQualifier();
	}
	System.arraycopy(compensableGlobalTransactionId, 0, resultArray, LENGTH_OF_XID * 2,
			XidFactory.GLOBAL_TRANSACTION_LENGTH);
	System.arraycopy(compensableBranchQualifier, 0, resultArray, LENGTH_OF_XID * 2 + XidFactory.GLOBAL_TRANSACTION_LENGTH,
			XidFactory.BRANCH_QUALIFIER_LENGTH);

	int value = archive.isCoordinator() ? 0x1 : 0x0;
	int triedValue = archive.isTried() ? 0x1 : 0x0;
	int confirmValue = archive.isConfirmed() ? 0x1 : 0x0;
	int cancelValue = archive.isCancelled() ? 0x1 : 0x0;
	// int mixedValue = archive.isTxMixed() ? 0x1 : 0x0;

	value = value | (triedValue << 1);
	value = value | (confirmValue << 2);
	value = value | (cancelValue << 3);
	// value = value | (mixedValue << 4);
	resultArray[LENGTH_OF_XID * 3] = (byte) value;

	byte[] lengthOfTransactionResourceKey = ByteUtils.shortToByteArray((short) transactionResourceKeyByteArray.length);
	byte[] lengthOfCompensableResourceKey = ByteUtils.shortToByteArray((short) compensableResourceKeyByteArray.length);

	int index = LENGTH_OF_XID * 3 + 1;
	System.arraycopy(lengthOfTransactionResourceKey, 0, resultArray, index, lengthOfTransactionResourceKey.length);
	index += lengthOfTransactionResourceKey.length;

	System.arraycopy(transactionResourceKeyByteArray, 0, resultArray, index, transactionResourceKeyByteArray.length);
	index += transactionResourceKeyByteArray.length;

	System.arraycopy(lengthOfCompensableResourceKey, 0, resultArray, index, lengthOfCompensableResourceKey.length);
	index += lengthOfCompensableResourceKey.length;

	System.arraycopy(compensableResourceKeyByteArray, 0, resultArray, index, compensableResourceKeyByteArray.length);
	index += compensableResourceKeyByteArray.length;

	System.arraycopy(byteArray, 0, resultArray, index, byteArray.length);

	return resultArray;
}
 
Example 18
Source File: LocalXAResource.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void createTransactionLogIfNecessary(Xid xid) throws XAException {
	byte[] globalTransactionId = xid.getGlobalTransactionId();
	byte[] branchQualifier = xid.getBranchQualifier();

	String gxid = ByteUtils.byteArrayToString(globalTransactionId);
	String bxid = null;
	if (branchQualifier == null || branchQualifier.length == 0) {
		bxid = gxid;
	} else {
		bxid = ByteUtils.byteArrayToString(branchQualifier);
	}

	String identifier = this.getIdentifier(globalTransactionId, branchQualifier);

	Connection connection = this.managedConnection.getPhysicalConnection();

	PreparedStatement stmt = null;
	try {
		stmt = connection.prepareStatement("insert into bytejta(xid, gxid, bxid, ctime) values(?, ?, ?, ?)");
		stmt.setString(1, identifier);
		stmt.setString(2, gxid);
		stmt.setString(3, bxid);
		stmt.setLong(4, System.currentTimeMillis());
		int value = stmt.executeUpdate();
		if (value == 0) {
			throw new IllegalStateException("The operation failed and the data was not written to the database!");
		}
	} catch (SQLException ex) {
		boolean tableExists = false;
		try {
			tableExists = this.isTableExists(connection);
		} catch (Exception sqlEx) {
			logger.error("Error occurred while ending local-xa-resource: {}", ex.getMessage());
			throw new XAException(XAException.XAER_RMFAIL);
		}

		if (tableExists) {
			logger.error("Error occurred while ending local-xa-resource: {}", ex.getMessage());
			throw new XAException(XAException.XAER_RMERR);
		} else {
			logger.debug("Error occurred while ending local-xa-resource: {}", ex.getMessage());
		}
	} catch (RuntimeException rex) {
		logger.error("Error occurred while ending local-xa-resource: {}", rex.getMessage());
		throw new XAException(XAException.XAER_RMERR);
	} finally {
		this.closeQuietly(stmt);
	}
}
 
Example 19
Source File: XATest.java    From FoxTelem with GNU General Public License v3.0 3 votes vote down vote up
private Xid createXid(Xid xidToBranch) throws IOException {
    ByteArrayOutputStream bqualOut = new ByteArrayOutputStream();
    DataOutputStream dataOut = new DataOutputStream(bqualOut);

    new UID().write(dataOut);

    final byte[] bqual = bqualOut.toByteArray();

    Xid xid = new MysqlXid(xidToBranch.getGlobalTransactionId(), bqual, 3306);

    return xid;
}
 
Example 20
Source File: XATest.java    From r-course with MIT License 3 votes vote down vote up
private Xid createXid(Xid xidToBranch) throws IOException {
    ByteArrayOutputStream bqualOut = new ByteArrayOutputStream();
    DataOutputStream dataOut = new DataOutputStream(bqualOut);

    new UID().write(dataOut);

    final byte[] bqual = bqualOut.toByteArray();

    Xid xid = new MysqlXid(xidToBranch.getGlobalTransactionId(), bqual, 3306);

    return xid;
}