Example usage for javax.transaction.xa Xid getGlobalTransactionId

List of usage examples for javax.transaction.xa Xid getGlobalTransactionId

Introduction

In this page you can find the example usage for javax.transaction.xa Xid getGlobalTransactionId.

Prototype

byte[] getGlobalTransactionId();

Source Link

Document

Obtain the global transaction identifier part of XID as an array of bytes.

Usage

From source file:org.bytesoft.bytetcc.logging.SampleCompensableLogger.java

public void recover(TransactionRecoveryCallback callback) {

    final Map<Xid, TransactionArchive> xidMap = new HashMap<Xid, TransactionArchive>();
    final ArchiveDeserializer deserializer = this.beanFactory.getArchiveDeserializer();
    final XidFactory xidFactory = this.beanFactory.getCompensableXidFactory();

    this.traversal(new VirtualLoggingListener() {
        public void recvOperation(VirtualLoggingRecord action) {
            Xid xid = action.getIdentifier();
            int operator = action.getOperator();
            if (VirtualLoggingSystem.OPERATOR_DELETE == operator) {
                xidMap.remove(xid);/*from w  w w. ja va  2 s. com*/
            } else if (xidMap.containsKey(xid) == false) {
                xidMap.put(xid, null);
            }
        }
    });

    this.traversal(new VirtualLoggingListener() {
        public void recvOperation(VirtualLoggingRecord action) {
            Xid xid = action.getIdentifier();
            if (xidMap.containsKey(xid)) {
                this.execOperation(action);
            }
        }

        public void execOperation(VirtualLoggingRecord action) {
            Xid identifier = action.getIdentifier();

            TransactionXid xid = xidFactory.createGlobalXid(identifier.getGlobalTransactionId());

            Object obj = deserializer.deserialize(xid, action.getValue());
            if (TransactionArchive.class.isInstance(obj)) {
                TransactionArchive archive = (TransactionArchive) obj;
                xidMap.put(identifier, archive);
            } else if (XAResourceArchive.class.isInstance(obj)) {
                TransactionArchive archive = xidMap.get(identifier);
                if (archive == null) {
                    logger.error("Error occurred while recovering resource archive: {}", obj);
                    return;
                }

                XAResourceArchive resourceArchive = (XAResourceArchive) obj;
                boolean matched = false;

                List<XAResourceArchive> remoteResources = archive.getRemoteResources();
                for (int i = 0; matched == false && remoteResources != null
                        && i < remoteResources.size(); i++) {
                    XAResourceArchive element = remoteResources.get(i);
                    if (resourceArchive.getXid().equals(element.getXid())) {
                        matched = true;
                        remoteResources.set(i, resourceArchive);
                    }
                }

                if (matched == false) {
                    remoteResources.add(resourceArchive);
                }

            } else if (CompensableArchive.class.isInstance(obj)) {
                TransactionArchive archive = xidMap.get(identifier);
                if (archive == null) {
                    logger.error("Error occurred while recovering compensable archive: {}", obj);
                    return;
                }

                List<CompensableArchive> compensables = archive.getCompensableResourceList();
                CompensableArchive resourceArchive = (CompensableArchive) obj;

                // if (VirtualLoggingSystem.OPERATOR_CREATE == action.getOperator()) {
                // compensables.add(resourceArchive);
                // } else {
                boolean matched = false;
                for (int i = 0; matched == false && compensables != null && i < compensables.size(); i++) {
                    CompensableArchive element = compensables.get(i);
                    if (resourceArchive.getIdentifier().equals(element.getIdentifier())) {
                        matched = true;
                        compensables.set(i, resourceArchive);
                    }
                }

                if (matched == false) {
                    compensables.add(resourceArchive);
                }

                // }

            }

        }
    });

    for (Iterator<Map.Entry<Xid, TransactionArchive>> itr = xidMap.entrySet().iterator(); itr.hasNext();) {
        Map.Entry<Xid, TransactionArchive> entry = itr.next();
        TransactionArchive archive = entry.getValue();
        if (archive == null) {
            continue;
        } else {
            try {
                callback.recover(archive);
            } catch (RuntimeException rex) {
                logger.error("Error occurred while recovering transaction(xid= {}).", archive.getXid(), rex);
            }
        }
    }

}

From source file:org.bytesoft.bytetcc.TransactionRecoveryImpl.java

private void recoverStatusIfNecessary(Transaction transaction) {
    CompensableTransactionImpl compensable = (CompensableTransactionImpl) transaction;
    List<CompensableArchive> archiveList = compensable.getCompensableArchiveList();

    XAResourceDeserializer resourceDeserializer = this.beanFactory.getResourceDeserializer();
    CompensableLogger compensableLogger = this.beanFactory.getCompensableLogger();

    Map<TransactionBranchKey, Boolean> triedMap = new HashMap<TransactionBranchKey, Boolean>();
    for (int i = 0; i < archiveList.size(); i++) {
        CompensableArchive archive = archiveList.get(i);

        if (archive.isTried()) {
            switch (transaction.getTransactionStatus()) {
            case Status.STATUS_ACTIVE:
            case Status.STATUS_MARKED_ROLLBACK:
            case Status.STATUS_PREPARING:
            case Status.STATUS_ROLLING_BACK:
            case Status.STATUS_UNKNOWN:
                transaction.setTransactionStatus(Status.STATUS_PREPARED);
                transaction.getTransactionContext().setCompensating(true);
                compensableLogger.updateTransaction(compensable.getTransactionArchive());
                break;
            case Status.STATUS_PREPARED:
            case Status.STATUS_COMMITTING:
            case Status.STATUS_COMMITTED:
            case Status.STATUS_ROLLEDBACK:
            default:
                // ignore
            }// w ww. j a  v  a  2  s .c om
        } else {
            Xid transactionXid = archive.getTransactionXid();
            String resourceKey = archive.getTransactionResourceKey();

            TransactionBranchKey recordKey = new TransactionBranchKey();
            recordKey.xid = transactionXid;
            recordKey.resource = resourceKey;

            if (StringUtils.isBlank(resourceKey)) {
                logger.warn(
                        "There is no valid resource participated in the trying branch transaction, the status of the branch transaction is unknown!");
            } else if (triedMap.containsKey(recordKey)) {
                Boolean tried = triedMap.get(recordKey);
                if (Boolean.TRUE.equals(tried)) {
                    transaction.setTransactionStatus(Status.STATUS_COMMITTING); // TODO
                } else {
                    transaction.setTransactionStatus(Status.STATUS_MARKED_ROLLBACK);
                }
                transaction.getTransactionContext().setCompensating(true);
                compensableLogger.updateTransaction(compensable.getTransactionArchive());
            } else {
                XAResource xares = resourceDeserializer.deserialize(resourceKey);
                if (RecoveredResource.class.isInstance(xares)) {
                    RecoveredResource resource = (RecoveredResource) xares;
                    try {
                        resource.recoverable(archive.getTransactionXid());
                        archive.setTried(true);
                        triedMap.put(recordKey, Boolean.TRUE);

                        transaction.setTransactionStatus(Status.STATUS_COMMITTING); // TODO
                        transaction.getTransactionContext().setCompensating(true);
                        compensableLogger.updateTransaction(compensable.getTransactionArchive());
                    } catch (XAException xaex) {
                        switch (xaex.errorCode) {
                        case XAException.XAER_NOTA:
                            triedMap.put(recordKey, Boolean.FALSE);

                            transaction.setTransactionStatus(Status.STATUS_MARKED_ROLLBACK);
                            transaction.getTransactionContext().setCompensating(true);
                            compensableLogger.updateTransaction(compensable.getTransactionArchive());
                            break;
                        case XAException.XAER_RMERR:
                            logger.warn(
                                    "The database table 'bytejta' cannot found, the status of the trying branch transaction is unknown!");
                            break;
                        case XAException.XAER_RMFAIL:
                            logger.error("Error occurred while recovering the branch transaction service: {}",
                                    ByteUtils.byteArrayToString(transactionXid.getGlobalTransactionId()), xaex);
                            break;
                        default:
                            logger.error(
                                    "Illegal state, the status of the trying branch transaction is unknown!");
                        }
                    }
                } else {
                    logger.error("Illegal resources, the status of the trying branch transaction is unknown!");
                }
            }
        } // end-else-if (archive.isTried())
    } // end-for
}

From source file:org.bytesoft.bytetcc.work.CleanupWork.java

public void forget(Xid xid, String resourceId) throws RuntimeException {
    byte[] globalTransactionId = xid.getGlobalTransactionId();
    byte[] branchQualifier = xid.getBranchQualifier();
    byte[] keyByteArray = resourceId.getBytes();

    byte sizeOfkeyByteArray = (byte) keyByteArray.length;
    if (sizeOfkeyByteArray > CONSTANTS_RES_ID_MAX_SIZE) {
        throw new IllegalStateException("The resource name is too long!");
    }/*from   w  w  w  .ja  va2 s .c  o m*/

    byte[] resourceByteArray = new byte[CONSTANTS_RES_ID_MAX_SIZE];
    System.arraycopy(keyByteArray, 0, resourceByteArray, 0, keyByteArray.length);

    ByteBuffer buffer = ByteBuffer.allocate(1 + CONSTANTS_RECORD_SIZE);
    buffer.put((byte) 0x1);

    buffer.put(globalTransactionId);
    buffer.put(branchQualifier);
    buffer.put(resourceByteArray);

    buffer.flip();

    this.invokeForget(xid, resourceId, buffer);
}

From source file:org.csc.phynixx.xa.PhynixxManagedXAConnection.java

/**
 * call by the XAResource when/*from w ww .j  a v  a 2  s  .co m*/
 * {@link javax.transaction.xa.XAResource#start(javax.transaction.xa.Xid, int)}
 * is called. A TransactionalBranch for the given XID ist expected to be
 * created.
 *
 * @param xid
 */
void startTransactionalBranch(Xid xid) {

    cleanupTransactionBinding();

    final TransactionBindingType transactionBindingType = this.transactionBinding.getTransactionBindingType();

    // already associated to a local transaction
    if (transactionBindingType == TransactionBindingType.LocalTransaction) {
        LocalTransactionProxy<C> localTransactionProxy = this.toLocalTransaction();
        Validate.isTrue(!localTransactionProxy.hasTransactionalData(),
                "Connection is associated to a local transaction and has uncommitted transactional data");
        if (localTransactionProxy.hasTransactionalData()) {
            throw new IllegalStateException(
                    "Connection is associated to a local transaction and has uncommitted transactional data");
        }

        XATransactionalBranch<C> xaTransactionalBranch = this.xaTransactionalBranchDictionary
                .findTransactionalBranch(xid);
        // xaTransactionalBranch!=null => joining a existing transactional branch
        if (xaTransactionalBranch == null) {
            IPhynixxManagedConnection<C> connection = localTransactionProxy.getConnection();
            if (connection == null || connection.isClosed()) {
                connection = this.createPhysicalConnection();
            }
            xaTransactionalBranch = this.xaTransactionalBranchDictionary.instanciateTransactionalBranch(xid,
                    connection);
        } else {
            localTransactionProxy.close();
        }
        // forget the Local transaction
        this.transactionBinding.release();

        XATransactionalBranch<C> transactionalBranch = this.xaTransactionalBranchDictionary
                .findTransactionalBranch(xid);
        Validate.isTrue(xaTransactionalBranch != null, "Expect a transactional branch to be created");

        this.transactionBinding.activateGlobalTransaction(new GlobalTransactionProxy<C>(transactionalBranch));

        // no transaction binding
    } else if (transactionBindingType == TransactionBindingType.NoTransaction) {
        XATransactionalBranch<C> transactionalBranch = this.xaTransactionalBranchDictionary
                .findTransactionalBranch(xid);

        // / xaTransactionalBranch!=null => joining a existing transactional
        // branch
        if (transactionalBranch == null) {
            IPhynixxManagedConnection<C> physicalConnection = this.createPhysicalConnection();
            transactionalBranch = this.xaTransactionalBranchDictionary.instanciateTransactionalBranch(xid,
                    physicalConnection);
            this.xaTransactionalBranchDictionary.instanciateTransactionalBranch(xid, physicalConnection);
        }
        this.transactionBinding.activateGlobalTransaction(new GlobalTransactionProxy<C>(transactionalBranch));

        // if bound to a global TX , check if same XID
    } else if (transactionBindingType == TransactionBindingType.GlobalTransaction) {

        XATransactionalBranch<C> transactionalBranch = this.xaTransactionalBranchDictionary
                .findTransactionalBranch(xid);

        // xaTransactionalBranch!=null => joining a existing transactional
        // branch
        if (transactionalBranch == null) {
            IPhynixxManagedConnection<C> physicalConnection = this.createPhysicalConnection();
            transactionalBranch = this.xaTransactionalBranchDictionary.instanciateTransactionalBranch(xid,
                    physicalConnection);
            this.xaTransactionalBranchDictionary.instanciateTransactionalBranch(xid, physicalConnection);
        }

        // Check if previous XID are compatible to the current
        GlobalTransactionProxy<C> previousGlobalTransactionProxy = this.transactionBinding
                .getEnlistedGlobalTransaction();
        if (previousGlobalTransactionProxy != null) {
            Xid previousXid = previousGlobalTransactionProxy.getXid();
            byte[] currentTransactionId = previousXid.getGlobalTransactionId();
            if (!Arrays.equals(xid.getGlobalTransactionId(), currentTransactionId)) {
                LOG.warn(
                        "TransactionId of the new Transaction doenn't corresponds to the transactionId of the previous Ids");
            }
            previousGlobalTransactionProxy.release();
        }

        this.transactionBinding.activateGlobalTransaction(new GlobalTransactionProxy<C>(transactionalBranch));

    }

}

From source file:org.mule.util.xa.MuleXid.java

public MuleXid(Xid txId) {
    this.formatId = txId.getFormatId();
    this.globalTransactionId = txId.getGlobalTransactionId();
    this.branchQualifier = txId.getBranchQualifier();
}

From source file:org.mule.util.xa.MuleXid.java

@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Xid)) {
        return false;
    }//from   w  w w  .  j a v a 2 s  .  co m
    Xid other = (Xid) obj;
    return Arrays.equals(getGlobalTransactionId(), other.getGlobalTransactionId())
            && Arrays.equals(getBranchQualifier(), other.getBranchQualifier())
            && getFormatId() == other.getFormatId();
}

From source file:org.mule.util.xa.MuleXid.java

@Override
public int compareTo(Xid o) {
    if (formatId == o.getFormatId() && Arrays.equals(globalTransactionId, o.getGlobalTransactionId())
            && Arrays.equals(branchQualifier, o.getBranchQualifier())) {
        return 0;
    }//from w  w w. ja v  a2 s .  c om
    return this.hashCode() > o.hashCode() ? 1 : -1;
}

From source file:org.wso2.andes.client.XASession_9_1.java

/**
 * Send startDtx command to server/*from  ww  w  .  j  a va 2 s . co  m*/
 *
 * @param xid  q global transaction identifier to be associated with the resource
 * @param flag one of TMNOFLAGS, TMJOIN, or TMRESUME
 * @return XaStatus returned by server
 * @throws FailoverException when a connection issue is detected
 * @throws AMQException      when an error is detected in AMQ state manager
 */
XaStatus startDtx(Xid xid, int flag) throws FailoverException, AMQException, XAException {

    throwErrorIfClosed();

    DtxStartBody dtxStartBody = methodRegistry.createDtxStartBody(xid.getFormatId(),
            xid.getGlobalTransactionId(), xid.getBranchQualifier(), flag == XAResource.TMJOIN,
            flag == XAResource.TMRESUME);

    AMQMethodEvent amqMethodEvent = _connection._protocolHandler
            .syncWrite(dtxStartBody.generateFrame(_channelId), DtxStartOkBody.class);

    DtxStartOkBodyImpl response = (DtxStartOkBodyImpl) amqMethodEvent.getMethod();

    return XaStatus.valueOf(response.getXaResult());
}

From source file:org.wso2.andes.client.XASession_9_1.java

/**
 * Send endDtx command to server/*from w  w w.j a  va  2  s  .  c om*/
 *
 * @param xid  a global transaction identifier to be associated with the resource
 * @param flag one of TMSUCCESS, TMFAIL, or TMSUSPEND.
 * @return XaStatus returned by server
 * @throws FailoverException when a connection issue is detected
 * @throws AMQException      when an error is detected in AMQ state manager
 */
XaStatus endDtx(Xid xid, int flag) throws FailoverException, AMQException, XAException {

    throwErrorIfClosed();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Sending dtx.end for channel " + _channelId + ", xid " + xid);
    }

    DtxEndBody dtxEndBody = methodRegistry.createDtxEndBody(xid.getFormatId(), xid.getGlobalTransactionId(),
            xid.getBranchQualifier(), flag == XAResource.TMFAIL, flag == XAResource.TMSUSPEND);

    AMQMethodEvent amqMethodEvent = _connection._protocolHandler.syncWrite(dtxEndBody.generateFrame(_channelId),
            DtxEndOkBody.class);

    DtxEndOkBodyImpl response = (DtxEndOkBodyImpl) amqMethodEvent.getMethod();

    return XaStatus.valueOf(response.getXaResult());
}

From source file:org.wso2.andes.client.XASession_9_1.java

XaStatus prepareDtx(Xid xid) throws FailoverException, AMQException, XAException {

    throwErrorIfClosed();//from w  w  w.j a  v  a  2s.c o m

    DtxPrepareBody dtxPrepareBody = methodRegistry.createDtxPrepareBody(xid.getFormatId(),
            xid.getGlobalTransactionId(), xid.getBranchQualifier());

    AMQMethodEvent amqMethodEvent = _connection._protocolHandler
            .syncWrite(dtxPrepareBody.generateFrame(_channelId), DtxPrepareOkBody.class);

    DtxPrepareOkBodyImpl response = (DtxPrepareOkBodyImpl) amqMethodEvent.getMethod();

    return XaStatus.valueOf(response.getXaResult());
}