All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.dreampie.common.plugin.db.tx.XAXid Maven / Gradle / Ivy

There is a newer version: 1.2.2
Show newest version
package cn.dreampie.common.plugin.db.tx;

import java.net.Inet4Address;
import java.util.Random;

/**
 * Created by wangrenhui on 2014/5/9.
 */
public class XAXid implements javax.transaction.xa.Xid {

  int formatId;
  byte[] globalTransactionId;
  byte[] branchQualifier;

  public XAXid(int formatId, byte[] globalTransactionId, byte[] branchQualifier) {
    this.formatId = formatId;
    this.globalTransactionId = globalTransactionId;
    this.branchQualifier = branchQualifier;
  }

  @Override
  public int getFormatId() {
    return formatId;
  }

  @Override
  public byte[] getGlobalTransactionId() {
    return globalTransactionId;
  }

  @Override
  public byte[] getBranchQualifier() {
    return branchQualifier;
  }

  // Returns a globally unique transaction id.
  static byte[] localIP = null;
  static int txnUniqueID = 0;

  public static XAXid uniqueXid(int tid) {

    Random rnd = new Random(System.currentTimeMillis());
    txnUniqueID++;
    int txnUID = txnUniqueID;
    int tidID = tid;
    int randID = rnd.nextInt();
    byte[] gtrid = new byte[64];
    byte[] bqual = new byte[64];
    if (null == localIP) {
      try {
        localIP = Inet4Address.getLocalHost().getAddress();
      } catch (Exception ex) {
        localIP = new byte[]{0x01, 0x02, 0x03, 0x04};
      }
    }
    System.arraycopy(localIP, 0, gtrid, 0, 4);
    System.arraycopy(localIP, 0, bqual, 0, 4);

    // Bytes 4 -> 7 - unique transaction id.
    // Bytes 8 ->11 - thread id.
    // Bytes 12->15 - random number generated by using seed from current time in milliseconds.
    for (int i = 0; i <= 3; i++) {
      gtrid[i + 4] = (byte) (txnUID % 0x100);
      bqual[i + 4] = (byte) (txnUID % 0x100);
      txnUID >>= 8;
      gtrid[i + 8] = (byte) (tidID % 0x100);
      bqual[i + 8] = (byte) (tidID % 0x100);
      tidID >>= 8;
      gtrid[i + 12] = (byte) (randID % 0x100);
      bqual[i + 12] = (byte) (randID % 0x100);
      randID >>= 8;
    }
    return new XAXid(0x1234, gtrid, bqual);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy